language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <pthread.h>
#include "thpool.h"
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXSIZE 128
void die(char *s)
{
perror(s);
exit(1);
}
typedef struct msgbuf
{
long mtype;
char mtext[MAXSIZE];
};
void recibirMensaje(){
int msqid;
key_t key;
struct msgbuf rcvbuffer;
key = 1778;
if ((msqid = msgget(key, 0666)) < 0)
die("msgget");
//Receive an answer of message type 1.
if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0)
die("msgrcv");
printf("\nMensaje imprimido en el archivo: %s\n", rcvbuffer.mtext);
}
main()
{
int msqid;
int msgflg = IPC_CREAT | 0666;
key_t key;
struct msgbuf sbuf;
size_t buflen;
key = 1777;
if ((msqid = msgget(key, msgflg )) < 0)
die("msgget");
int i;
for(i=0; i<3;i++){
sbuf.mtype = 1;
printf("Escribe un mensaje(Ej: salida.txt:Altura:20:X:100) : ");
scanf("%[^\n]",sbuf.mtext);
getchar();
buflen = strlen(sbuf.mtext) + 1 ;
if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)
{
printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buflen);
die("msgsnd");
}
sleep(1);
recibirMensaje();
}
exit(0);
}
|
C
|
#include <stdio.h>
//typedef int JUNGSU;
typedef struct point{
int x,y,z;
}abc; //typedef abcϸ struct point abc ü ϰڴٴ ǹ
void main (){
abc p1, p2;
p1.x=10, p1.y=20, p1.z=30;
p2=p1;
printf("%d %d %d\n",p1.x,p1.y,p1.z);
printf("%d %d %d\n",p2.x,p2.y,p2.z);
//if(p1==p2) ƴ϶ ̷ X
if(p1.x==p2.x && p1.y==p2.y && p1.z==p2.z){
printf("Ȱ");
}//p1==p2 ̰
struct point p3[100];
p3[0].x=1;
}
|
C
|
/****************************************************************************
return.c 2.15 - return from multi-band display mode
The return command returns the user from the multi-band display mode
(entered through disp) to the single-band-with-graphics mode.
****************************************************************************/
#include <stdio.h>
#include "spam.h"
disp_return(buf)
unsigned char *buf;
{
if (display_mode==0) {
printf("You're not in display mode. Type \"help\" for help.\n");
return;
}
vddispln(&unit,&c4); /* disp all planes again. */
vdflush(&unit);
display_mode=0; /* reset mode flag. */
}
|
C
|
/*
* sensor_opt.c
*
* Created on: 2017年4月12日
* Author: root
*/
#include "my_include.h"
#include "sensor_opt.h"
#include "dev_opt.h"
#include "elevator_module.h"
SENSOR_DEV_INFO sensor_ctx; //定义传感器
void *ReadGyroData(void * arg)
{
int i;
int retval;
int rd_len;
int sync = 0;
fd_set rfds;
float x=0.0, y=0.0, z=0.0;
struct timeval tv;
struct input_event ies[100];
while (!sensor_ctx.exit_flag)
{
FD_ZERO(&rfds);
FD_SET(sensor_ctx.gyro_ctx.dev_fd, &rfds);
//两次SYN_REPORT之间为一组数据
tv.tv_sec = 1;
tv.tv_usec = 0; //500ms
retval = select(sensor_ctx.gyro_ctx.dev_fd + 1, &rfds, NULL, NULL, &tv);
if (retval == -1)
{
perror("select()");
break;
}
else if (retval)
{
rd_len = read(sensor_ctx.gyro_ctx.dev_fd, ies, sizeof(ies));
if (rd_len <= 0)
{
TRACE_ERR("read gyro event failed!\n");
break;
}
for (i = 0; i < rd_len / sizeof(struct input_event); i++)
{
if (EV_SYN == ies[i].type && SYN_REPORT == ies[i].code)
{
if (!sync)
{
sync = 1;
}
else
{
//printf("gyro:%f|%f|%f\n", x, y, z);
sensor_ctx.gyro_x = (long int)x;
sensor_ctx.gyro_y = (long int)y;
sensor_ctx.gyro_z = (long int)z;
//读取陀螺仪数据成功,返回0
// *gyro_x = (long int)x;
// *gyro_y = (long int)y;
// *gyro_z = (long int)z;
sync = 0;
}
}
if (EV_ABS == ies[i].type)
{
switch (ies[i].code)
{
case ABS_X:
// x = ies[i].value * sensor_ctx.gyro_ctx.sensitivity / 1000;
x = ies[i].value * sensor_ctx.gyro_ctx.sensitivity; //内核中此值放大了1000倍,使用时需除1000
break;
case ABS_Y:
// y = ies[i].value * gyro_ctx.sensitivity / 1000;
y = ies[i].value * sensor_ctx.gyro_ctx.sensitivity; //内核中此值放大了1000倍,使用时需除1000
break;
case ABS_Z:
// z = ies[i].value * gyro_ctx.sensitivity / 1000;
z = ies[i].value * sensor_ctx.gyro_ctx.sensitivity; //内核中此值放大了1000倍,使用时需除1000
break;
default:
TRACE_ERR("Invalid e.code!\n");
break;
}
}
}
}
else
{
//timeout
TRACE_ERR("select read gyro data timeout, return value=%d!\n", retval);
break;
}
}
printf("ReadGyroData task exit!\n");
sensor_ctx.exit_flag = 1;
pthread_exit(NULL);
}
//int ReadAcclData(long int *accl_x, long int *accl_y, long int *accl_z)
void *ReadAcclData(void * arg)
{
//pthread_detach(pthread_self());
int i;
int retval;
int rd_len;
int sync = 0;
fd_set rfds;
float x=0.0, y=0.0, z=0.0;
struct timeval tv;
struct input_event ies[100];
while (!sensor_ctx.exit_flag)
{
FD_ZERO(&rfds);
FD_SET(sensor_ctx.accl_ctx.dev_fd, &rfds);
//两次SYN_REPORT之间为一组数据
tv.tv_sec = 1;
tv.tv_usec = 0;
retval = select(sensor_ctx.accl_ctx.dev_fd + 1, &rfds, NULL, NULL, &tv);
if (retval == -1)
{
perror("select()");
break;
}
else if (retval)
{
rd_len = read(sensor_ctx.accl_ctx.dev_fd, ies, sizeof(ies));
if (rd_len <= 0)
{
printf("read Accl failed!\n");
break;
}
for (i = 0; i < rd_len / sizeof(struct input_event); i++)
{
if (EV_SYN == ies[i].type && SYN_REPORT == ies[i].code)
{
if (!sync)
{
sync = 1;
}
else
{
//printf("acc:%f|%f|%f\n", x, y, z);
sensor_ctx.accl_x = (long int)x;
sensor_ctx.accl_y = (long int)y;
sensor_ctx.accl_z = (long int)z;
//
// *accl_x = (long int)x;
// *accl_y = (long int)y;
// *accl_z = (long int)z;
sync=0;
}
}
if (EV_ABS == ies[i].type)
{
switch (ies[i].code)
{
case ABS_X:
//acc_x = ies[i].value * sensor_ctx.accl_ctx.sensitivity / 1000;
x = ies[i].value * sensor_ctx.accl_ctx.sensitivity; //内核中此值放大了1000倍,使用时需除1000
break;
case ABS_Y:
// acc_y = ies[i].value * sensor_ctx.accl_ctx.sensitivity / 1000;
y = ies[i].value * sensor_ctx.accl_ctx.sensitivity; //内核中此值放大了1000倍,使用时需除1000
break;
case ABS_Z:
// acc_z = ies[i].value * sensor_ctx.accl_ctx.sensitivity / 1000;
z = ies[i].value * sensor_ctx.accl_ctx.sensitivity; //内核中此值放大了1000倍,使用时需除1000
break;
default:
printf("Invalid e.code!\n");
break;
}
}
}
}
else
{
TRACE_ERR("select read acc data error, return value=%d!\n", retval);
break;
}
}
printf("ReadAcclData task exit!\n");
sensor_ctx.exit_flag = 1;
pthread_exit(NULL);
}
|
C
|
#include <stdio.h>
void soma_um(int v[], int n) {
int i;
for (i = 0; i < n; i++)
v[i]++;
}
int main() {
int i, v[5] = {1, 2, 3, 4, 5};
soma_um(v, 5);
for (i = 0; i < 5; i++)
printf("%d ", v[i]);
return 0;
}
|
C
|
/**
******************************************************************************
* Author : Farid Mabrouk
* File Name : main.c
* Description : Main program
******************************************************************************/
/* Includes */
#include "main.h"
#include <stdbool.h>
TIM_HandleTypeDef Tim2Handle;
uint32_t uwPrescalerValue=0;
volatile bool ADC_SampleFlag=false;
void SystemClock_Config(void);
void Error_Handler(void);
int main(void)
{
static uint8_t ChannelAddr=0;
/*initialize the HAL Library */
HAL_Init();
/*System Clock Config */
SystemClock_Config();
/*SPI Config */
SPI3_Config();
GPIOs_Config();
/*TIMER2 Config */
Timer2_Interrupt_Config();
/*wait for interrupts*/
while (1)
{
if(ADC_SampleFlag==true) //this flag is turned ON by timer interrupt to signal it's time to read data from ADC
{
HAL_GPIO_TogglePin(GPIOD,GPIO_PIN_12); //toggle an LED jsut for testing/debugging
ADC_SampleFlag=true; //notify main loop that data needs to be sampled
MCP3204_ReadRequest(counter); // Read Channel 0
ADC_SampleFlag=false;
ChannelAddr++;
if(ChannelAddr==0x04)
{
ChannelAddrr=0;
}
}
}
}
/** System Clock Configuration
*/
void SystemClock_Config(void)
{
RCC_ClkInitTypeDef RCC_ClkInitStruct;
RCC_OscInitTypeDef RCC_OscInitStruct;
/* Enable Power Control clock */
__PWR_CLK_ENABLE();
/* The voltage scaling allows optimizing the power consumption when the device is
clocked below the maximum system frequency, to update the voltage scaling value
regarding system frequency refer to product datasheet. */
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/* Enable HSE Oscillator and activate PLL with HSE as source */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 336;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 7;
HAL_RCC_OscConfig(&RCC_OscInitStruct);
/* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */
RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5);
}
void Timer2_Interrupt_Config(void)
{
// TIM2 initialization overflow every 500ms
// TIM2 by default has clock of 84MHz
// After HAL_RCC_OscConfig(&RCC_OscInitStruct) is called SystemCoreClock value is updated to 525000000
// and uwPrescalerValue becomes 26250000
uwPrescalerValue = (uint32_t) ((SystemCoreClock /2) / 10000) - 1;
/* Set TIM2 instance */
Tim2Handle.Instance = TIM2;
Tim2Handle.Init.Period = 1600 - 1; //timer updates every 500ms
Tim2Handle.Init.Prescaler = uwPrescalerValue; // 26250000-1
Tim2Handle.Init.ClockDivision =TIM_CLOCKDIVISION_DIV1;
Tim2Handle.Init.CounterMode = TIM_COUNTERMODE_UP;
if(HAL_TIM_Base_Init(&Tim2Handle) != HAL_OK)
{
/* Initialization Error */
Error_Handler();
}
/*Start the TIM Base generation in interrupt mode */
if(HAL_TIM_Base_Start_IT(&Tim2Handle) != HAL_OK)
{
/* Starting Error */
Error_Handler();
}
}
void Error_Handler(void)
{
while(1)
{
}
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
}
#endif
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a, b;
scanf("%d %d", &a, &b);
getchar();
if(b-a > 0)
{
if(b <= 2) puts("nova");
else if(b <= 96) puts("crescente");
else puts("cheia");
}
else
{
if(b > 96) puts("cheia");
else if(b < 3) puts("nova");
else puts("minguante");
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a=0,b=1,i,temp,n;
printf("Enter the number:");
scanf("%d",&n);
printf("%d",b);
for(i=2;i<=n;i++)
{
temp=a+b;
a=b;
b=temp;
printf("%d",temp);
}
}
|
C
|
// C Program to reverse a string without
// using temp variable
#include <stdio.h>
// Function to reverse string and return revesed string
void reversingString(char* str, int start, int end)
{
// Iterate loop upto start not equal to end
while (start < end)
{
// XOR for swapping the variable
str[start] ^= str[end];
str[end] ^= str[start];
str[start] ^= str[end];
++start;
--end;
}
}
// Driver Code
int main()
{
char s[] = "HelloWorld";
printf("%s reversed to ",s);
reversingString(s, 0, 9);
printf("%s",s);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include"StateIO.h"
#include"WatermanFun.h"
void readfile(int n, const char *filename, unsigned char *sseq, int *sseq_num)
{
int i;
FILE *infile;
int a,b;
infile=fopen(filename,"r");
for(i=0;i<n;i++){
fscanf(infile,"%d",&a);
fscanf(infile,"%d",&b);
sseq[i]=a;
sseq_num[i]=b;
}
fclose(infile);
return;
}
int main(int argc, char **argv)
{
int n;
struct StateIO_Opt opt;
opt.s = 0;
MakeKey_Number(&opt);
n = FILE_CountLine(argv[1],&opt);
printf("\n%d\n",n);
unsigned char *sseq;
unsigned short *sseq_num;
opt.s = 0;
opt.n = 0;
n = Sseq_ReadFile(argv[1],&sseq,&sseq_num,&opt);
int i,j;
int m=0;
for(i=0;i<n;i++){
m+=sseq_num[i];
}
unsigned char *seq;
seq = (unsigned char *)malloc(sizeof(unsigned char)*m);
m=0;
for(i=0;i<n;i++){
for(j=0;j<sseq_num[i];j++){
seq[m]=sseq[i];
m+=1;
}
}
n=m;
int n2;
n2 = atoi(argv[2]);
unsigned char *sseq2;
int *sseq_num2;
sseq2 = (unsigned char *)malloc(sizeof(unsigned char)*n2);
sseq_num2 = (int *)malloc(sizeof(int)*n2);
readfile(n2,argv[1],sseq2,sseq_num2);
int m2=0;
for(i=0;i<n2;i++){
m2 += sseq_num2[i];
}
unsigned char *seq2;
seq2 = (unsigned char *)malloc(sizeof(unsigned char)*m2);
m2=0;
for(i=0;i<n2;i++){
for(j=0;j<sseq_num2[i];j++){
seq2[m2] = sseq2[i];
m2 += 1;
}
}
n2 = m2;
printf("\n%d %d\n",n,n2);
char eq = 1;
for(i=0;i<n;i++){
if(seq[i]!=seq2[i]){
eq=0;
break;
}
}
if(eq==0){
printf("\nNot Equal!\n");
}
else{
printf("\nEqual.\n");
}
return 1;
}
|
C
|
/*****************************************************************************
FileName: fifo.c
License/Copyright:
Copyright (c) 2007, Jan Vidar Berger, Case Labs, Ltd. All rights reserved.
email:janvb@caselaboratories.com
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Case Labs, Ltd nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#include "fifo.h"
#include <stdio.h>
#include <stdlib.h>
/*****************************************************************************
Function: FIFOCreate
Description: Takes any buffer and creates a fifo from it using the buffer
head for fifo queue information.
Parameters: fifo Buffer to be created.
size Size of buffer in bytes.
*****************************************************************************/
void FIFOCreate(char *fifo, int size)
{
FIFO *f=(FIFO *)fifo;
f->first = 0;
f->last = 0;
f->size = size - (sizeof(int)*3);
}
/*****************************************************************************
Function: FIFOWrite
Description: Write butes into a fifo queue.
Parameters: fifo ptr to fifo.
buf ptr to bytes to be be writtem into the queue.
size Number of bytes to be written.
Return Value: Number of bytes written.
*****************************************************************************/
int FIFOWrite(char * fifo, char * buf, int size)
{
int c=0;
FIFO *f=(FIFO *)fifo;
int x;
int block = FIFOGetFreeBlockSize(f);
if(block >= size)
{
memcpy(&f->buf[f->first],buf,size);
x= f->first + size;
if(x > f->size)
x=0;
f->first = x;
return size;
}
else
{
for(c=0; c<size; c++)
{
f->buf[f->first]=buf[c];
x= f->first + 1;
if(x >= f->size)
x=0;
if(x==f->last)
return c-1; /* full queue */
f->first = x;
}
return c;
}
}
/*****************************************************************************
Function: FIFORead
Description: Read bytes from a FIFO queue.
Parameters: fifo ptr to fifo.
buf ptr at buffer receiving bytes.
size max number of bytes to be read.
Return value: Number of bytes read.
*****************************************************************************/
int FIFORead(char * fifo, char *buf, int size)
{
FIFO *f=(FIFO *)fifo;
int b;
int r;
int c=0;
int x;
if(f->last == f->first)
return 0; /* empty fifo */
/* first block transfer */
b = FIFOGetNextBlockSize(f);
if(b <= size)
{
memcpy(buf, &f->buf[f->last],b);
x = f->last + b;
if(x >= f->size)
x=0;
f->last=x;
c+=b;
}
/* 2nd optional block transfer */
if(c < size)
{
b = FIFOGetNextBlockSize(f);
if(b > 0)
{
r = min(b, size-c);
memcpy(&buf[c],&f->buf[f->last],r);
x = f->last + r;
if(x >= f->size)
x=0;
f->last=x;
c+=r;
}
}
return c;
}
/*****************************************************************************
Function: FIFOGetFreeBlockSize
Description: Returns the size of the next continiously free space.
Parameters: f ptr to FIFO struct.
Return Value Size of block in bytes.
*****************************************************************************/
int FIFOGetFreeBlockSize(FIFO *f)
{
if(f->first == f->last)
{
f->first=f->last=0;
return f->size-1;
}
else if(f->first >= f->last)
{
return f->size - f->first-1;
}
else
{
return f->last - f->first-1;
}
}
/*****************************************************************************
Function: FIFOGetNextBlockSize
Description: Return the number of continiously bytes in the queue.
Parameters: f ptr to FIFO struct
Return Value: number of continuous bytes in the queue.
*****************************************************************************/
int FIFOGetNextBlockSize(FIFO *f)
{
if(f->first == f->last)
{
return 0;
}
else if(f->first > f->last)
{
return f->first - f->last;
}
else
{
return f->size - f->last;
}
}
/*****************************************************************************
Function: FIFOReadByte
Description: Will read a single byte from the queue. Provides better
perfomance than FIFORead on single or small byte xfers.
Parameters: fifo ptr to fifo queue.
b ptr to address containing byte.
Return Value: Number of bytes read.
*****************************************************************************/
int FIFOReadByte(char *fifo, char *b)
{
FIFO *f=(FIFO *)fifo;
int x;
if(f->last == f->first)
return 0; /* empty fifo */
*b = f->buf[f->last];
x = f->last +1;
if(x >= f->size)
x=0;
f->last=x;
return 1;
}
/*****************************************************************************
Function: FIFOWriteByte
Description: Write a single byte to the FIFO. Provide better performance
on single or small block xfers than FIFOWrite.
Parameters: fifo ptr to fifo.
b ptr to address receiving byte.
Return Value: Number of bytes written.
*****************************************************************************/
int FIFOWriteByte(char *fifo, char *b)
{
FIFO *f=(FIFO *)fifo;
int x;
f->buf[f->first]= *b;
x= f->first +1;
if(x > f->size)
x=0;
if(x==f->last)
return 0;
f->first = x;
return 1;
}
/*****************************************************************************
Function: FIFOGetQueued
Description: Get bytes in fifo.
Parameters: fifo ptr to fifo.
Return Value: Bytes in fifo.
*****************************************************************************/
int FIFOGetQueued(char *fifo)
{
FIFO *f=(FIFO *)fifo;
if(f->last == f->first)
return 0;
else if (f->last < f->first)
return f->first - f->last;
else
return (f->size-f->last) + f->first;
}
|
C
|
/* Execution test for argument passing with SSE2 and local functions
Written by Paolo Bonzini, 25 January 2005 */
/* { dg-do run } */
/* { dg-options "-O2 -msse2 -mfpmath=sse" } */
/* { dg-require-effective-target sse2 } */
#include "sse2-check.h"
#include <assert.h>
static float xs (void)
{
return 3.14159265;
}
float ys (float a)
{
return xs () * a;
}
static double xd (void)
{
return 3.1415926535;
}
double yd (double a)
{
return xd () * a;
}
static void
sse2_test (void)
{
assert (ys (1) == xs ());
assert (ys (2) == xs () * 2);
assert (yd (1) == xd ());
assert (yd (2) == xd () * 2);
}
|
C
|
//
// Created by Jamie on 23/12/2017.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "../blackJackAPI/blackJack.h"
#include "../blackJackAPI/blackJackPlayer.h"
#include "../blackJackAPI/blackJackCard.h"
#include "../cardCount/probabilityCalculator.h"
#include "../../generalAPI/userInput.h"
#include "../../cardAPI/deckStack.h"
#include "../../cardAPI/player.h"
#include "../../cardAPI/simpleStack.h"
void playBlackJack() {
srand((unsigned int) time(NULL));
DeckStack deckStack;
initialiseFullDeckStack(&deckStack, DECKSUSED);
DeckStack usedDeckStack;
initialiseEmptyDeckStack(&usedDeckStack, DECKSUSED);
SimpleStack simpleDeckStack;
initialiseSimpleStackFromDeckStack(&simpleDeckStack, &deckStack);
// Simplify all 10 score cards into one slot
for (int i = JACK; i <= KING; i++) {
while (simpleDeckStack.cardsCountsInStack[i] > 0) {
simpleDeckStack.cardsCountsInStack[10]++;
simpleDeckStack.cardsCountsInStack[i]--;
}
}
BlackJackPlayer player;
initialiseBlackJackPlayer(&player, "Player");
BlackJackPlayer dealer;
initialiseBlackJackPlayer(&dealer, "Dealer");
int on = 1;
while (on) {
dealBlackJack(&deckStack, &simpleDeckStack, &player, 0);
dealBlackJack(&deckStack, &simpleDeckStack, &player, 0);
dealBlackJack(&deckStack, &simpleDeckStack, &dealer, 0);
int playerBust = 0;
int dealerBust = 0;
while (!playerBust && !doesPlayerHaveBlackJack(&player)) {
printf("You have a score of score of: %i ", player.score);
if (player.isScoreSoft) {
printf("or %i", player.score - 10);
}
printf("\n");
calculateProbabilities(&deckStack, &player, &dealer);
printf("Would you like to hit or stand? \n"
"\t1: Hit \n"
"\t2: Stand \n");
long option = getIntegerUserInput();
if (option == 1) {
dealBlackJack(&deckStack, &simpleDeckStack, &player, 0);
if (player.score > 21) {
playerBust = 1;
printf("\n \n \nPLAYER HAS GONE BUST \n");
}
} else if (option == 2) {
break;
} else {
printf("What was entered was not a valid option, please try again. \n");
}
}
if (!playerBust && !doesPlayerHaveBlackJack(&player)) {
while (dealer.score < 17) {
dealBlackJack(&deckStack, &simpleDeckStack, &dealer, 0);
}
if (dealer.score > 21) {
dealerBust = 1;
printf("\n \n \nDEALER HAS GONE BUST \n");
}
}
if (dealerBust) {
printf("PLAYER WIN \n \n \n");
} else if (playerBust) {
printf("DEALER WIN \n \n \n");
} else {
if (doesPlayerHaveBlackJack(&player) && doesPlayerHaveBlackJack(&dealer)) {
printf("\n \n \nDRAW \n \n \n");
} else if (doesPlayerHaveBlackJack(&player)) {
printf("\n \n \nPLAYER WIN \n \n \n");
} else if (doesPlayerHaveBlackJack(&dealer)) {
printf("\n \n \nDEALER WIN \n \n \n");
} else {
printf("Player has a score of: %i \n", player.score);
printf("Dealer has a score of: %i \n ", dealer.score);
if (player.score > dealer.score) {
printf("\n \n \nPLAYER WIN \n \n \n");
} else if (dealer.score > player.score) {
printf("\n \n \nDEALER WIN \n \n \n");
} else {
printf("\n \n \nDRAW \n \n \n");
}
}
}
for (int i = player.player.cardsInHand; i > 0; i--) {
addCardToDeckStack(&usedDeckStack, getCardFromPlayer(&player.player, 0));
removeCardFromBlackJackPlayersHand(&player, 0, 0);
}
for (int i = dealer.player.cardsInHand; i > 0; i--) {
addCardToDeckStack(&usedDeckStack, getCardFromPlayer(&dealer.player, 0));
removeCardFromBlackJackPlayersHand(&dealer, 0, 0);
}
updatePlayersScore(&player);
updatePlayersScore(&dealer);
while (1) {
printf("Would you like to play another hand? \n"
"\t1: Yes \n"
"\t2: No \n");
long option = getIntegerUserInput();
if (option == 1) {
break;
} else if (option == 2) {
on = 0;
break;
} else {
printf("What was entered was not a valid option, please try again. \n");
}
}
}
}
|
C
|
//
// Created by alan2 on 24/03/2020.
//
#include "utils/render_graph.h"
#include <stdlib.h>
render_node_t *create_node(draw_callback_c callback)
{
render_node_t *node = malloc(sizeof(render_node_t));
node->draw_callback = callback;
node->child = NULL;
node->next = NULL;
node->previous = NULL;
node->parent = NULL;
node->param = NULL;
node->node_id = -1;
node->require_redraw = true;
return node;
}
render_graph_t *create_new_graph(void)
{
render_graph_t *graph = malloc(sizeof(render_graph_t));
graph->entry_point = create_node(NULL);
graph->entry_point->node_id = 0;
return graph;
}
static void draw_render_graph_internal(render_node_t *node, bool forceRedraw)
{
if (node->draw_callback != NULL && (node->require_redraw || forceRedraw))
{
node->draw_callback(node->param);
}
if (node->child)
{
draw_render_graph_internal(node->child, node->require_redraw || forceRedraw);
}
if (node->next)
{
draw_render_graph_internal(node->next, false);
}
node->require_redraw = false;
}
void draw_render_graph(render_graph_t *render_graph)
{
draw_render_graph_internal(render_graph->entry_point, false);
}
static void delete_render_graph_internal(render_node_t *node)
{
if (node->next)
{
delete_render_graph_internal(node->next);
}
if (node->child)
{
delete_render_graph_internal(node->child);
}
free(node);
}
void delete_render_graph(render_graph_t *render_graph)
{
delete_render_graph_internal(render_graph->entry_point);
free(render_graph);
}
render_node_t *add_child(render_node_t *parent, draw_callback_c callback)
{
render_node_t *child = create_node(callback);
child->node_id = rand() + 1;
render_node_t *bro = parent->child;
if (bro != NULL)
{
while (bro->next) bro = bro->next;
bro->next = child;
child->previous = bro;
}
else
{
parent->child = child;
}
child->parent = parent;
return child;
}
render_node_t *add_next(render_node_t *previous, draw_callback_c callback)
{
render_node_t *next = create_node(callback);
next->node_id = rand() + 1;
next->next = previous->next;
previous->next = next;
next->previous = previous;
return next;
}
render_node_t *add_node_at_end(render_graph_t *render_graph, draw_callback_c callback)
{
render_node_t *node = render_graph->entry_point->child;
if (!node)
{
return add_child(render_graph->entry_point, callback);
}
while (node->next) node = node->next;
render_node_t *new_node = add_next(node, callback);
new_node->parent = render_graph->entry_point;
return new_node;
}
void delete_node(render_node_t *node)
{
if (node->parent->child == node)
{ // si tiene un padre, entonces debemos decirle al padre que ya no tiene hijos
node->parent->child = node->next;
}
if (node->child) // si tiene un hijo, entonces eliminamos a los hijos
{
delete_node(node->child);
}
if (node->previous)
{
node->previous->next = node->next; // solo vamos a eliminar este,
}
if (node->next)
{
node->next->previous = node->previous;
}
free(node);
}
void delete_last(render_graph_t *render_graph)
{
render_node_t *node = render_graph->entry_point->child;
if (!node->child)
{
return; // No hay hijos por lo tanto no hay nada que eliminar
}
while (node->next) node = node->next;
delete_node(node);
}
|
C
|
#include "constant.h"
#include "freq.h"
#include <stdio.h>
#include <stdlib.h>
#include <strings .h>
int countFrequency (char * filename , CharFreq * freq )
{
FILE * fptr = fopen ( filename , "r");
int count = 0;
if ( fptr == NULL )
{
return 0;
}
while (! feof ( fptr ))
{
int onechar = fgetc ( fptr );
if ( onechar != EOF )
{
count ++;
freq [ onechar ]. value = (char) onechar ;
freq [ onechar ]. freq ++;
}
}
fclose ( fptr );
return count ;
}
void printFrequency ( CharFreq * freq )
{
int ind ;
for ( ind = 0; ind < NUMLETTER ; ind ++)
{
printf ("%d %d\n", freq [ ind ]. value ,
freq [ ind ]. freq );
}
printf (" ------------------------\n");
}
static int compareFreq (const void * p1 , const void * p2)
{
const CharFreq * ip1 = (const CharFreq *) p1;
const CharFreq * ip2 = (const CharFreq *) p2;
const int iv1 = ip1 -> freq ;
const int iv2 = ip2 -> freq ;
return ( iv1 - iv2 );
}
void sortFrequency ( CharFreq * freq )
{
qsort (freq , NUMLETTER , sizeof ( CharFreq ), compareFreq );
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print_num.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mmastrel <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/24 15:23:27 by mmastrel #+# #+# */
/* Updated: 2017/04/19 00:15:41 by mmastrel ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_printf.h"
char *int_to_a(const char *format, va_list *ap, t_format flags, char *arg)
{
if (flags.l == 1 || *format == 'D')
arg = ft_itoa_base(va_arg(*ap, long int), 10, 0);
else if (flags.hh == 1)
arg = ft_itoa_base((signed char)(va_arg(*ap, int)), 10, 0);
else if (flags.h == 1)
arg = ft_itoa_base((short int)(va_arg(*ap, int)), 10, 0);
else if (flags.ll == 1)
arg = ft_itoa_base(va_arg(*ap, long long int), 10, 0);
else if (flags.j == 1)
arg = ft_itoa_base(va_arg(*ap, intmax_t), 10, 0);
else if (flags.z == 1)
arg = ft_itoa_base(va_arg(*ap, size_t), 10, 0);
else
arg = ft_itoa_base(va_arg(*ap, int), 10, 0);
return (arg);
}
char *uint_to_a(const char *format, va_list *ap, t_format flags, char *arg)
{
if (flags.l == 1 || *format == 'U')
arg = ft_uitoa_base(va_arg(*ap, unsigned long int), 10, 0);
else if (flags.hh == 1)
arg = ft_uitoa_base((unsigned char)(va_arg(*ap, int)), 10, 0);
else if (flags.h == 1)
arg = ft_uitoa_base((unsigned short int)(va_arg(*ap, int)), 10, 0);
else if (flags.ll == 1)
arg = ft_uitoa_base(va_arg(*ap, unsigned long long int), 10, 0);
else if (flags.j == 1)
arg = ft_uitoa_base(va_arg(*ap, uintmax_t), 10, 0);
else if (flags.z == 1)
arg = ft_uitoa_base(va_arg(*ap, size_t), 10, 0);
else
arg = ft_uitoa_base(va_arg(*ap, unsigned int), 10, 0);
return (arg);
}
|
C
|
#include "../include/aplex_tty.h"
int main(void)
{
struct aplex_tty aplex_tty1, aplex_tty2, aplex_tty3, aplex_tty4, aplex_tty5, aplex_tty6;
pid_t pid1, pid2, pid3, pid4, pid5, pid6;
char tty_node1[] = "/dev/ttyO1";
char tty_node2[] = "/dev/ttyO2";
char tty_node3[] = "/dev/ttyO3";
char tty_node4[] = "/dev/ttyO4";
char tty_node5[] = "/dev/ttyO5";
char tty_node6[] = "/dev/ttyUSB0";
int test_count = 5000;
unsigned int usleep_time = 100000;
char test_chr[32] = "abcd9876543210\0";
init_aplex_tty(&aplex_tty1, tty_node1, test_count, usleep_time, test_chr);
init_aplex_tty(&aplex_tty2, tty_node2, test_count, usleep_time, test_chr);
init_aplex_tty(&aplex_tty3, tty_node3, test_count, usleep_time, test_chr);
init_aplex_tty(&aplex_tty4, tty_node4, test_count, usleep_time, test_chr);
init_aplex_tty(&aplex_tty5, tty_node5, test_count, usleep_time, test_chr);
init_aplex_tty(&aplex_tty6, tty_node6, test_count, usleep_time, test_chr);
if ((pid1 = fork()) < 0)
{
perror("fork error1");
}
else if(pid1 == 0)
{
test_tty(&aplex_tty1);
exit(1);
}
if ((pid2 = fork()) < 0)
{
perror("fork error1");
}
else if(pid2 == 0)
{
test_tty(&aplex_tty2);
exit(1);
}
if ((pid3 = fork()) < 0)
{
perror("fork error1");
}
else if(pid3 == 0)
{
test_tty(&aplex_tty3);
exit(1);
}
if ((pid4 = fork()) < 0)
{
perror("fork error1");
}
else if(pid4 == 0)
{
test_tty(&aplex_tty4);
exit(1);
}
if ((pid5 = fork()) < 0)
{
perror("fork error1");
}
else if(pid5 == 0)
{
test_tty(&aplex_tty5);
exit(1);
}
if ((pid6 = fork()) < 0)
{
perror("fork error1");
}
else if(pid6 == 0)
{
test_tty(&aplex_tty6);
exit(1);
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <time.h>
#include "enum.h"
typedef struct karta {
tBarvaKarty barvaKarty;
tTypKarty typKarty;
char nazev[50];// "Lidsk nzev" karty pro vpisy, p.: "erven eso"
struct karta *dalsi;
} tKarta;
tKarta * vytvorKartu(tBarvaKarty barvaKarty, tTypKarty typKarty, char *nazev); // vrac adresu dynamick alokace karty, ukazatel dalsi se nastav na NULL
void vypisKartu(tKarta *karta); //vype kartu na obrazovku
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef int inteiro;// definindo um novo nome para o int. "inteiro";
typedef struct endereco{
char rua[50];
char bairro[50];
char cidade[30];
int numero;
} Endereco;
// Facilita a indentificação de tipos de dados
typedef struct pessoa{ // Definindo um novo nome para struct. No caso "Pessoa".
char nome[20];
int idade;
Endereco endereco;
} Pessoa;
void main1(){
Pessoa p1;
printf("Digite seu nome: \n");
scanf("%[^/n]s", &p1.nome);
printf("Digite sua idade: \n");
scanf("%d", &p1.idade);
printf("Digite sua cidade: \n");
scanf("%[^/n]s", &p1.endereco.cidade);
printf("Digite seu bairro: \n");
scanf("%[^/n]s", &p1.endereco.bairro);
printf("Digite sua rua: \n");
scanf("%[^/n]s", &p1.endereco.rua);
printf("Digite o numero da casa: \n");
scanf("%d", &p1.endereco.numero);
system("pause");
}
|
C
|
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
head = reverseList(head);
struct ListNode* current = head;
if (n == 1){
head = head->next;
} else {
int x = 1;
while (x<n-1){
current = current->next;
x++;
}
current->next = current->next->next;
}
head = reverseList(head);
return head;
}
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* current = head;
struct ListNode* prev = NULL;
struct ListNode* next;
while (current!=NULL){
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
return head;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <libmemcached/memcached.h>
int main() {
char* config = "--SERVER=127.0.0.1:11211";
memcached_st* mc = memcached(config, strlen(config));
if (mc == NULL) {
printf("Init failed\n");
}
char* key = "somekey";
char* value = "VALUE333";
time_t expire_time = time(NULL) + 1000;
memcached_return_t result = memcached_set(
mc, key, strlen(key),
value, strlen(value), expire_time, 0);
const char* err = memcached_last_error_message(mc);
printf("Error: %s\n", err);
memcached_free(mc);
printf("Done\n");
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<math.h>
int ceil2(float a)
{
printf("\nIn ceil (%f)..",a);
int b=a;
float res=b-a;
if(res==0)
return b;
else
return b+1;
}
int main()
{
char str[100]={};
int count[26]={};
scanf("%s",str);
for(int i=0;i<strlen(str);i++)
{
count[str[i]-'a']+=1;
}
printf("CEIL of 1.3=%f,1=%f",ceil(1.3) ,ceil(1.0));
int k=ceil2((float)strlen(str)/2);
printf("\nCeil of %f is %d",(float)strlen(str)/2,k);
for(int i=0;i<strlen(str);i++)
{
if(count[i]>k)
{
printf("\nNOT POSSIBLE\n");
return 0;
}
}
printf("\nPossible\n");
return 0;
}
|
C
|
/* This is assembler of an imaginary computer with 14 bit CPU.
* It has 256 cells of RAM and 8 registers. The CPU
* has 16 instructions. It can work with signed integer numbers and
* ASCII set of characters.
*/
#include <assert.h>
#include <ctype.h>
#include <malloc.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "assembler.h"
#include "data.h"
#include "label.h"
#include "parser.h"
#include "x4encode.h"
const char *RESERVED_KEYWORDS[] = {"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
"mov", "cmp", "add", "sub", "not", "clr", "lea", "inc",
"dec", "jmp", "bne", "red", "prn", "jsr", "rts", "stop",
"data", "entry", "extern", "string"};
const char *INSTRUCTIONS_LIST[] = {"mov", "cmp", "add", "sub", "not", "clr", "lea", "inc",
"dec", "jmp", "bne", "red", "prn", "jsr", "rts", "stop"};
const char *REGISTERS_LIST[] = {"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7"};
opcode opcodes[] = { /* array of all known instructions with code and type */
{"mov", MOV, TWOOPS}, {"cmp", CMP, TWOOPS}, {"add", ADD, TWOOPS}, {"sub", SUB, TWOOPS},
{"not", NOT, ONEOP}, {"clr", CLR, ONEOP}, {"lea", LEA, TWOOPS}, {"inc", INC, ONEOP},
{"dec", DEC, ONEOP}, {"jmp", JMP, ONEOP}, {"bne", BNE, ONEOP}, {"red", RED, ONEOP},
{"prn", PRN, ONEOP}, {"jsr", JSR,ONEOP}, {"rts", RTS, NOOPS}, {"stop", STOP, NOOPS}
};
reg registers[] = {
{"r0", R0}, {"r1", R1}, {"r2", R2}, {"r3", R3},
{"r4", R4}, {"r5", R5}, {"r6", R6}, {"r0", R7}
};
char *in_line_ptr; /* pointer to current position in input line as line is parsed*/
char *LINE; /* original input line */
int NLINES; /* number of lines */
int INP_LINE_POS; /* current char number in line for use in error messages */
int NINST; /* number of instructions */
int NREGS; /* number of registers */
int NRESERVED; /* number of reserved keywords */
char *SRC_F; /* assembly source file name */
char *OBJ_F; /* object file name */
char *ENT_F; /* entries file name */
char *EXT_F; /* external variables file name */
bool ENTRIES_DEF; /* boolean to check if external defined*/
label *SYMBOL_TABLE;
data *DATA_LIST; /* list of data words */
code *CODE_TABLE; /* list of code words */
code_seg *CODE_SEG_LIST; /* list of code memory segment words */
extern_ref *EXTERN_REF_LIST; /* list of external labels refernces */
status_flags status;
/*
* runs pass1 and pass 2 over each input file
*/
void assemble() {
void (*pass_one)() = &parse_in_line;
void (*pass_two)() = &parse_in_line_2;
char *line;
FILE *f;
line = malloc(sizeof(char) * MAX_LINE_SIZE);
if (!line) print_err(ERR_FATAL, "failed to allocate memory");
NINST = sizeof(INSTRUCTIONS_LIST) / sizeof(*INSTRUCTIONS_LIST);
NREGS = sizeof(REGISTERS_LIST) / sizeof(*REGISTERS_LIST);
NRESERVED = sizeof(RESERVED_KEYWORDS) / sizeof(*RESERVED_KEYWORDS);
SYMBOL_TABLE = NULL;
DATA_LIST = NULL;
CODE_TABLE = NULL;
CODE_SEG_LIST = NULL;
ENTRIES_DEF = FALSE; /* set entries to FALSE until encounter with one */
DC = 0;
init();
/*printf("src: %s\n", SRC_F);
* printf("obj: %s\n", OBJ_F);
* printf("ent: %s\n", ENT_F);
* printf("ext: %s\n", EXT_F);
*/
f = fopen(SRC_F, "r");
if (!f) {
print_err(ERR_SYS, "Could not open file `%s': %s", SRC_F, strerror(errno));
return;
}
printf("+++++++++++++ PASS 1 +++++++++++++: %s\n", SRC_F);
pass(f, pass_one, line);
if (status.ERR) {
fclose(f);
return;
}
update_labels(SYMBOL_TABLE);
update_data_seg(DATA_LIST);
rewind(f); /* rewind to beggining of file before pass 2 */
init(); /* and init global counters */
printf("+++++++++++++ PASS 2 +++++++++++++: %s\n", SRC_F);
pass(f, pass_two, line);
if (status.ERR) {
fclose(f);
return;
}
make_files(); /* generate all output files*/
/*printf("\n\nError flag: %d; DC: %d; IC: %d; Lines: %d\n", status.ERR, DC, IC, NLINES);
print_symbol_table(SYMBOL_TABLE);
print_xcode_table(CODE_SEG_LIST);
print_data_table(DATA_LIST);
print_extern_ref_list(EXTERN_REF_LIST);
print_entries(SYMBOL_TABLE);*/
fclose(f);
}
void init(){
status.ERR = 0;
status.LBL = 0;
status.WRN = 0;
IC = CODE_MEM_OFFSET;
NLINES = 0;
INP_LINE_POS = 1;
}
/*
* Runs pass 1/2 on given file
*/
void pass(FILE *f, void (*func)(), char *line) {
while ((line = get_line(f, line))) {
in_line_ptr = line;
LINE = line;
NLINES++;
skip_whitespaces();
if (*in_line_ptr != '\0') {
(func)();
}
INP_LINE_POS = 1;
status.LBL = 0; /* Clear label status for next line */
}
}
/*
* Generates all output files
*/
void make_files(){
/* TODO: add file close validations*/
FILE *obj = fopen(OBJ_F, "w");
fprint_xcode_table(obj, CODE_SEG_LIST);
fprint_data_table(obj, DATA_LIST);
if (fclose(obj) != 0) print_err(ERR_FATAL, "failed to save file: %s: %s", obj, strerror(errno));
if (ENTRIES_DEF) {
FILE *ent = fopen(ENT_F, "w");
fprint_entries(ent, SYMBOL_TABLE);
if (fclose(ent) != 0) print_err(ERR_FATAL, "failed to save file: %s: %s", ent, strerror(errno));
}
if (EXTERN_REF_LIST) {
FILE *ext = fopen(EXT_F, "w");
fprint_extern_ref_list(ext, EXTERN_REF_LIST);
if (fclose(ext) != 0) print_err(ERR_FATAL, "failed to save file: %s: %s", ext, strerror(errno));
}
}
/*
* Returns pointer to line from file
*/
char *get_line(FILE *f, char *line) {
int i=0;
char c;
while ((c= (char) fgetc(f)) != EOF && c != '\n') {
if (i < MAX_LINE_SIZE) {
if (c != ';') { /* grab everything that ios not comment */
line[i++] = c;
} else { /* otherwise fast forward till end of line*/
while ((c= (char) fgetc(f)) != '\n' && c != EOF);
break;
}
} else if (i == MAX_LINE_SIZE) {
/* if the line is longer than allowed
* and its not comment or whitespaces, set error
* */
while (c != '\n' && c != EOF) {
/* allow whites anywhere */
if (c == ' ' || c == '\t') {
c = (char) fgetc(f);
continue;
} else if (c == ';') { /* comments are allowed as well */
while ((c = (char) fgetc(f)) != '\n' && c != EOF) {}
line[i] = '\0';
return line;
} else {
status.ERR = 1;
NLINES++;
print_err(ERR_NONFATAL, "line is too long");
while ((c = (char) fgetc(f)) != '\n' && c != EOF) {}
break;
}
c = (char) fgetc(f);
}
/* skip to next line if over-sized line found */
if (status.ERR == 1) {
NLINES++;
i = 0;
/*continue;*/
}
}
}
if (c == EOF && i == 0) {
line = NULL;
return line;
}
line[i] = '\0';
return line;
}
/*
* updates labels address in pass 2
*/
void update_labels(label *s) {
label *tmp = s;
while (tmp) {
if (tmp->type == DATA_L) {
tmp->value += IC;
}
tmp = tmp->next;
}
}
/*
* updates data segment address in pass 2
*/
void update_data_seg(data *d) {
data *tmp = d;
while(tmp) {
tmp->addr += IC;
tmp = tmp->next;
}
}
/*
* uppdates operands values at given address with label addresses in pass 2
*/
void update_code_seg(char *l_name, int addr) {
label *l = SYMBOL_TABLE;
code_seg *c = CODE_SEG_LIST;
while (l) { /* find the label */
if (!(strcmp(l_name, l->name))) {
break;
}
l = l->next;
}
if (!l) {
print_err(ERR_NONFATAL, "undefined label: `%s'\n", l_name);
return;
}
while (c) { /* find requested operand and update its value and ARE */
if (c->addr == addr) {
c->word.o.val |= l->value;
if (l->type == EXTERNAL_L) {
c->word.o.are = EXT;
add_extern_ref(l->name, addr);
} else {
c->word.o.are = REL;
}
}
c = c->next;
}
}
/*
* adds external variables to a list
* to dump to output file later
*/
void add_extern_ref(char *name, int addr){
extern_ref *e;
e = (extern_ref *)malloc(sizeof(extern_ref));
e->name = name;
e->addr = addr;
e->next = NULL;
append_extern(&EXTERN_REF_LIST, e);
}
void append_extern(extern_ref **head, extern_ref *e){
extern_ref *tmp;
if (*head == NULL) {
*head = e;
return;
}
for (tmp = *head; tmp->next != NULL; tmp = tmp->next);
tmp->next = e;
}
/*
* gets and encodes instruction and operands of a given instruction
*/
int handle_ops0(instruction inst) { /* handle operands of category 1 (2 ops) instructions */
char *srcop, *dstop;
char c;
operand op1, op2;
/* should not reach this part if instruction is other then below */
assert(inst == MOV || inst == CMP || inst == ADD || inst == SUB || inst == LEA);
srcop = get_op0();
if (!srcop) {
c = *in_line_ptr;
if (c == ',') {
print_err(ERR_NONFATAL, "unexpected comma after instruction");
return 1;
} else if (c == '\0') {
print_err(ERR_NONFATAL, "operand is expected after instruction");
return 1;
}
}
c = *in_line_ptr;
if (c == '\0') {
print_err(ERR_NONFATAL, "two operands expected");
return 1;
} else if (c != ',') {
print_err(ERR_NONFATAL, "comma is expected after first operand");
return 1;
}
in_line_ptr++; /* eat the comma */
skip_whitespaces();
dstop = get_op0();
if (!dstop) {
print_err(ERR_NONFATAL, "operand is expected after comma");
}
if (is_junk()) return 1;
op1 = analyze_op(srcop, FALSE);
if (op1.name == NULL) return FALSE;
op2 = analyze_op(dstop, FALSE);
if (op2.name == NULL) return FALSE;
if (op2.name == NULL) return FALSE;
if (!validate_cat1_ops(op1, op2, inst)) {
return FALSE;
}
xencode_code_word(op1, op2, inst);
return 0;
}
/*
* encodes instruction and operands words of type 2 (one operand) in pass 1
*/
int handle_ops1(instruction inst){
char *dstop;
operand op, op_null = {0};
assert(inst == NOT || inst == CLR || inst == INC || inst == DEC || inst == JMP
|| inst == BNE || inst == RED || inst == PRN || inst == JSR);
dstop = get_op1();
if (!dstop) {
print_err(ERR_NONFATAL, "valid operand is expected after `%s' instruction", INSTRUCTIONS_LIST[inst]);
return 1;
}
skip_whitespaces();
if (is_junk()) return 1;
if (is_op_params(dstop)) {
char *param_op, *param1, *param2;
operand opparam1, opparam2;
param_op = get_op_p(dstop, &dstop);
param1 = get_param1(dstop, &dstop);
if (!param1) return 1;
param2 = get_param2(dstop, &dstop);
if (!param2) return 1;
op = analyze_op(param_op, TRUE);
opparam1 = analyze_p_op(param1);
opparam2 = analyze_p_op(param2);
xencode_param_code_word(op, opparam1, opparam2, inst);
} else {
op = analyze_op(dstop, FALSE);
xencode_code_word(op_null, op, inst);
}
return 0;
}
/*
* encodes instruction word of type 3 (no operands) in pass 1
*/
int handle_ops2(instruction inst){
operand op1_null = {0}, op2_null = {0};
skip_whitespaces();
if (is_junk()) return 1;
xencode_code_word(op1_null, op2_null, inst);
return 0;
}
/*
* gets operands of instructions of type 1 (two operands) in pass 2,
* check if its label and updates missing address in code segment
*/
int handle2_ops0(instruction inst) {
char *srcop, *dstop;
srcop = get_op0();
in_line_ptr++;
skip_whitespaces();
dstop = get_op0();
if (is_register(srcop) != -1 && is_register(dstop) != -1) {
IC++;
return 0;
} else {
IC++;
if (is_label(srcop)) {
update_code_seg(srcop, IC);
}
IC++;
if (is_label(dstop)) {
update_code_seg(dstop, IC);
}
}
return 0;
}
/*
* gets operands of instructions of type 2 (one operand) in pass 2,
* check if its label and updates missing address in code segment
*/
int handle2_ops1(instruction inst) {
char *dstop;
dstop = get_op1();
IC++;
if (is_op_params(dstop)) {
char *l1, *l2, *l3;
l1 = get_op_p(dstop, &dstop);
l2 = get_param1(dstop, &dstop);
l3 = get_param2(dstop, &dstop);
update_code_seg(l1, IC);
if (is_register(l2) != -1 && is_register(l3) != -1) {
IC++;
return 0;
} else {
IC++;
if (is_label(l2)) {
update_code_seg(l2, IC);
}
IC++;
if (is_label(l3)) {
update_code_seg(l3, IC);
}
}
} else if (is_label(dstop)) {
update_code_seg(dstop, IC);
}
return 0;
}
/*
* validates and encodes operand
*/
operand analyze_op(char *name, bool param) {
operand op = {0};
register_v r;
int val;
if ((r = is_register(name)) != -1) {
op.name = name;
op.value = r;
op.mode = REGDIRECT;
return op;
}
if (*name == '#') {
op.name = name;
name++;
if (!valid_int(name)){
op.name = NULL;
return op;
}
val = atoi(name);
op.value |= val;
op.mode = IMMEDIATE;
} else if (isalpha(*name)) {
if (!valid_label(name)) {
op.name = NULL;
return op;
}
op.name = name;
op.value = 0;
op.mode = (param) ? INDIRECT : DIRECT;
} else {
print_err(ERR_NONFATAL, "bad operand: `%s'\n", name);
op.name = NULL;
}
return op;
}
/*
* validate and encode parameter of mode 2 operands
*/
operand analyze_p_op(char *name) {
operand op = {0};
register_v r;
int val;
if ((r = is_register(name)) != -1) {
op.name = name;
op.value = r;
op.mode = REGDIRECT;
op.param = REGDIRECT;
return op;
}
if (*name == '#') {
op.name = name;
name++;
if (!valid_int(name)){
op.name = NULL;
return op;
}
val = atoi(name);
op.value |= val;
op.mode = IMMEDIATE;
op.param = IMMEDIATE;
} else if (isalpha(*name)) {
if (!valid_label(name)) {
op.name = NULL;
return op;
}
op.name = name;
op.value = 0;
op.mode = DIRECT;
op.param = DIRECT;
} else {
print_err(ERR_NONFATAL, "bad parameter: `%s'", name);
op.name = NULL;
}
return op;
}
/*
* check if is a legal register name and return its value,
* returns -1 otherwise
*/
register_v is_register(char *name) {
int i;
for (i = 0; i < NREGS; i++) {
if ((strcmp(name, registers[i].name)) == 0) {
return registers[i].r;
}
}
return -1;
}
/*
* ################################################################
*/
/*
* gets our imaginary machine encoded bit
*/
char getMbit(unsigned num, int bit){
if (num & (1<<bit))
return M_ONE;
else
return M_ZRO;
}
/*
* gets bit N of encoded word, for debugging purposes
*/
int getNthbit(unsigned num, int bit){
return (num & (1<<bit)) != 0;
}
/*
* Prints our imaginary machine encoded bits to file stream
*/
void fprint_bits(FILE *f, unsigned num) {
int i;
for (i=13; i>=0; i--){
fputc(getMbit(num, i), f);
}
}
/*
* prints bits of encoded words for debugging
*/
void print_bits(unsigned num) {
int i;
for (i=13; i>=0; i--){
printf("%d", getNthbit(num, i));
}
}
/*
* prints symbol table for debugging
*/
void print_symbol_table(label *l) {
label *tmp = l;
while(tmp) {
print_symbol(tmp);
tmp = tmp->next;
}
}
/*
* prints code table for debuigging
*/
void print_code_table(code *c){
code *tmp = c;
printf("+++++++++++++++CODE area++++++++++++++++\n");
while(tmp) {
print_code_word(tmp);
tmp = tmp->next;
}
}
/*
* prints our imaginary machine code to file
*/
void fprint_xcode_table(FILE *f, code_seg *s){
code_seg *tmp = s;
fprintf(f, "\t%4d\t%d\n", IC-CODE_MEM_OFFSET, DC);
while(tmp) {
fprint_xcode_word(f, tmp);
tmp = tmp->next;
}
}
void print_xcode_table(code_seg *s){
code_seg *tmp = s;
printf("+++++++++++++++CODE area++++++++++++++++\n");
while(tmp) {
print_xcode_word(tmp);
tmp = tmp->next;
}
}
void print_extern_ref(extern_ref *e){
printf("%s\t%d\n", e->name, e->addr);
}
void print_extern_ref_list(extern_ref *head){
extern_ref *e = head;
printf("############### External References ##############\n");
while(e) {
print_extern_ref(e);
e = e->next;
}
}
void fprint_extern_ref(FILE *f, extern_ref *e){
fprintf(f, "%s\t%d\n", e->name, e->addr);
}
void fprint_extern_ref_list(FILE *f, extern_ref *head){
extern_ref *e = head;
while(e) {
fprint_extern_ref(f, e);
e = e->next;
}
}
void print_symbol(label *l) {
printf("-------------------- Label %s --------------------\n", l->name);
printf("Type: %s\n", ltype2str(l->type));
printf("Label addr: %d\n", l->value);
printf("Entry: %d\n", l->entry);
}
void print_code_word(code *c) {
printf("%.4d\t", c->addr);
/*print_code_bits(c->word);*/
print_bits(*(unsigned*)&c->word);
printf("\n");
}
void fprint_xcode_word(FILE *f, code_seg *s) {
fprintf(f, "%.4d\t", s->addr);
fprint_bits(f, *(unsigned*)&s->word);
fprintf(f, "\n");
}
void print_xcode_word(code_seg *s) {
printf("%.4d\t", s->addr);
/*print_code_bits(c->word);*/
print_bits(*(unsigned*)&s->word);
if (s->name) printf("\t%s\t%s,%s", s->name, s->srcop, s->dstop);
printf("\n");
}
void print_data_word(data *d) {
printf("%.4d\t", d->addr);
/*print_data_bits(d->word);*/
print_bits(*(unsigned*)&d->word);
printf("\n");
}
void print_data_table(data *d) {
data *tmp = d;
printf("+++++++++++++++DATA area++++++++++++++++\n");
while(tmp) {
print_data_word(tmp);
tmp = tmp->next;
}
}
void fprint_data_word(FILE *f, data *d) {
fprintf(f, "%.4d\t", d->addr);
fprint_bits(f, *(unsigned*)&d->word);
fprintf(f, "\n");
}
void fprint_data_table(FILE *f, data *d) {
data *tmp = d;
while(tmp) {
fprint_data_word(f, tmp);
tmp = tmp->next;
}
}
void print_entries(label *head){
label *l = head;
while(l) {
if (l->entry) {
printf("%s\t%d\n", l->name, l->value);
}
l = l->next;
}
}
void fprint_entries(FILE *f, label *head){
label *l = head;
while(l) {
if (l->entry) {
fprintf(f, "%s\t%d\n", l->name, l->value);
}
l = l->next;
}
}
char *ltype2str(label_type t) {
switch(t){
case CODE_L: return "Code label";
case DATA_L: return "Data label";
case EXTERNAL_L: return "External label";
default: return "Unknown label type";
}
}
/*
* Initializes names of output files
*/
void init_fnames(const char *name){
size_t len = strlen(name);
SRC_F = malloc(sizeof(SRC_F_) * len);
if (!SRC_F) print_err(ERR_FATAL, "failed to allocate memory");
OBJ_F = malloc(sizeof(OBJ_F_) * len);
if (!OBJ_F) print_err(ERR_FATAL, "failed to allocate memory");
ENT_F = malloc(sizeof(ENT_F_) * len);
if (!ENT_F) print_err(ERR_FATAL, "failed to allocate memory");
EXT_F = malloc(sizeof(EXT_F_) * len);
if (!EXT_F) print_err(ERR_FATAL, "failed to allocate memory");
strcat(strcpy(SRC_F, name), SRC_F_);
strcat(strcpy(OBJ_F, name), OBJ_F_);
strcat(strcpy(ENT_F, name), ENT_F_);
strcat(strcpy(EXT_F, name), EXT_F_);
}
void print_code_bits(instruction_word c) {
int i;
for (i=13; i>=0; i--){
printf("%d", getNthbit(*(unsigned *) &c, i));
}
}
void print_data_bits(data_word d) {
int i;
for (i=13; i>=0; i--){
printf("%d", getNthbit(d.data, i));
}
}
|
C
|
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
void *connection_handler(void *);
int sockList[100] = {0};
int working = 0;
// gcc -o server.o server.c -lpthread
int main() {
struct sockaddr_in server, client;
unsigned int sock, csock, addressSiez;
char buf[256];
pthread_t sniffer_thread;
bzero(&server, sizeof(server));
server.sin_family = PF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(5675);
sock = socket(PF_INET, SOCK_STREAM, 0);
bind(sock, (struct sockaddr *)&server, sizeof(server));
listen(sock, 5);
while (csock = accept(sock, (struct sockaddr *)&client, &addressSiez)) {
working++;
// printf("Online connect: %d\n", working);
if (pthread_create(&sniffer_thread, 0, connection_handler,
(void *)&csock) != 0) {
perror("Thread creation");
} else {
pthread_detach(sniffer_thread);
}
if (csock < 0) {
perror("Csock");
}
}
close(sock);
printf("[Socket Close]\n");
return 0;
}
void *connection_handler(void *sock) {
int csock = *(int *)sock;
int readSize;
int number = working;
char buf[256];
if (working >= 4) {
sprintf(buf, "Server is full!");
write(csock, buf, sizeof(buf));
close(csock);
working--;
pthread_exit(0);
}
sockList[number] = csock;
char sendBuf[256];
sprintf(sendBuf, "Welcome user%d\n", number);
write(csock, sendBuf, sizeof(sendBuf));
while ((readSize = read(csock, buf, sizeof(buf))) != 0) {
// user1,user2:
// user1:
// 012345678901
char *s;
int sendTo1 = -1, sendTo2 = -1;
if (buf[5] == ',') {
sendTo1 = buf[4] - '0';
sendTo2 = buf[10] - '0';
s = buf + 12;
} else if (buf[5] == ':') {
sendTo1 = buf[4] - '0';
s = buf + 5;
}
printf("s1: %d ----- s2: %d\n", sendTo1, sendTo2);
sprintf(sendBuf, "%d%s", number + 1, s);
if (sendTo1 != -1) {
write(sockList[sendTo1], sendBuf, sizeof(sendBuf));
}
if (sendTo2 != -1) {
write(sockList[sendTo2], sendBuf, sizeof(sendBuf));
}
}
if (readSize == 0) {
printf("Client Disconnect!\n");
printf("CSock ID: %d\n", csock);
int delete;
working--;
for (int i = 0; i < 100; i++) {
if (sockList[i] == csock) {
delete = i;
}
}
for (int i = delete; i < 100; i++) {
sockList[i] = sockList[i + 1];
sockList[99] = 0;
}
}
close(csock);
printf("Client Close\n\n");
pthread_exit(0);
}
|
C
|
/******************************************************************************
* FILE: pi.c
* serial code
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
static long num_steps = 100000;
double step;
int main ()
{
int i;
double x, pi, sum = 0.0;
step = 1.0/(double) num_steps;
for (i=0; i< num_steps; i++)
{
x = (i+0.5)*step;
sum = sum + 4.0/(1.0+x*x);
}
pi = step * sum;
printf("Computed pi = %.16f\n",pi);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void encrypt(char *s)
{
while(*s) {
if(*s >= 'A' && *s <= 'Z') {
*s += 4;
if(*s > 'Z')
*s = (*s - 'Z' + 3) + 'A';
}
if(*s >= 'a' && *s <= 'z') {
*s += 4;
if(*s > 'z')
*s = (*s - 'z' + 3) + 'a';
}
++s;
}
}
int main()
{
char s[128];
gets(s);
encrypt(s);
printf("%s\n", s);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* display_debug_data_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: humanfou <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/13 19:01:52 by humanfou #+# #+# */
/* Updated: 2021/04/28 12:41:42 by humanfou ### ########.fr */
/* */
/* ************************************************************************** */
#include "display_bonus.h"
void display_debug_data(t_vars *vars, int count)
{
if (vars->options[VERBOSE] == ON)
display_stacks(*vars->stack_a, *vars->stack_b);
if (vars->options[COLOURS] == ON)
{
ft_putstr("\e[4mLast operation\e[0m: \e[1m\e[33m");
ft_putstr(vars->ops->action->label);
ft_putstr("\e[0m\n\n");
}
if (vars->options[ITERATE] == ON)
{
ft_putstr("\e[4mOperation count\e[0m: ");
ft_putnbr(count);
ft_putstr("\e[0m\n\n");
}
ft_putstr("\e[4mExec:\e[0m ");
}
|
C
|
#include <stdio.h>
int calculer_nb_sous_trame_req(int y)
{
return y;
}
main()
{
int x;
if ( x = calculer_nb_sous_trame_req(4) == 0) {
printf("inside if ( x = 3 == 4), x=%d\n", x);
}
printf("x=%d\n", x);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int perm(char *p, int i, int n)
{
int j;
char temp;
// char p[4];
// for(j = 0; j < 4; j++)
// {
// p[j] = a[j];
// }
if (i == n)
{
printf("\t%s\n", p);
}
else
{
for (j = i; j < n; j++)
{
if(i!=j)
{
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
perm(p, i+1, n);
if(i!=j)
{
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
}
int main()
{
char a[] = "abcde";
printf("output:\n");
perm(a, 0, sizeof(a)-1);
return 0;
}
|
C
|
#include "asm.h"
t_token *create_token(char *str_token, t_type_token type)
{
t_token *token;
// if ((token = (t_token *)malloc(sizeof(t_token))) == NULL)
// print_error_and_exit();
MFAIL((token = (t_token *)malloc(sizeof(t_token))));
token->str = str_token;
token->type_token = type;
token->next = NULL;
token->prev = NULL;
return (token);
}
void tokens_add_tokens(t_token_list *token_list, t_token *token)
{
if (token_list == NULL || token == NULL)
return ;
if (token_list->end == NULL)
{
token_list->begin = token;
token->prev = NULL;
while (token->next != NULL)
token = token->next;
token_list->end = token;
return ;
}
token_list->end->next = token;
token->prev = token_list->end;
while (token->next != NULL)
token = token->next;
token_list->end = token;
token->next = NULL;
}
|
C
|
#include <stdio.h>
#include <malloc.h>
#define null 0
struct Node
{
int value;
struct Node* next;
};
void addData(int data, struct Node* pHead)
{
struct Node* pTemp = (struct Node*) malloc(sizeof(struct Node));
struct Node* pLocTemp;
pTemp->value = data;
pTemp->next = null;
if (pHead == null)
{
pHead = pTemp;
}
else
{
pLocTemp = pHead;
while (pLocTemp->next)
{
pLocTemp = pLocTemp->next;
}
pLocTemp->next = pTemp;
}
}
void deleteData(struct Node* pHead, int delData)
{
struct Node* pLocTemp = pHead;
if(pHead == null)
{
printf("Nothing to delete");
return;
}
if (!pLocTemp->next)
{
if (pLocTemp->value == delData)
{
free(pLocTemp);
*pHead = null;
return;
}
}
else
{
while (pLocTemp->next)
{
if (pLocTemp->next->value == delData)
{
free(pLocTemp);
pLocTemp->next = null;
return;
}
pLocTemp = pLocTemp->next;
}
}
printf("Data not found");
return;
}
void print(struct Node* pHead)
{
while(pHead)
{
printf("%d ", pHead->value);
pHead = pHead->next;
}
}
int main()
{
struct Node* pHead = null;
int i;
for(i = 0; i < 10; ++i)
addData(pHead, i);
printf("\n");
print(pHead);
deleteData(pHead, 5);
deleteData(pHead, 10);
deleteData(pHead, 0);
print(pHead);
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
void quicksort(float * array, int first, int last)
{
if (first>last)
{
return;
}
float temp;
int i = first;
int j = last;
int mid = first + (last-first)/2;
float pivot = array[mid];
while (i < j)
{
while (array[i] > pivot)
{
i++;
}
while (array[j] < pivot)
{
j--;
}
if (i <= j)
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++; //using this prevents a "do while"
j--;
}
}
if (first < j)
quicksort(array, first, j);
if (i < last)
quicksort(array, i, last);
}
// Dont need to do error checks as existence is guaranteed ;)
int binary_search(float *array, int first, int last, float el)
{
int mid = first + (last-first)/2;
if (array[mid] == el)
{
return mid + 1;
}
if (el > array[mid])
{
return binary_search(array,first,mid-1,el);
}
else
{
return binary_search(array,mid+1,last,el);
}
}
int cmp(const void *a, const void *b) {
return -( *(int*)a - *(int*)b );
}
void compute_ranks(float *F, int N, int *R, float *avg, float *passing_avg, int *num_passed) {
int i;
*num_passed = 0;
*avg = 0.0;
*passing_avg = 0.0;
if (N <= 0) return;
// create temp array J for sorting
size_t sz = sizeof(float)*N;
float * J = malloc(sz);
memcpy(J, F, sz);
quicksort(J,0,N-1);
// compute ranks
for (i = 0; i < N; ++i) {
R[i] = binary_search(J,0,N-1,F[i]);
*avg += F[i];
if (F[i] >= 50.0) {
*passing_avg += F[i];
*num_passed += 1;
}
}
// check for div by 0
*avg /= N;
if (*num_passed) *passing_avg /= *num_passed;
free(J);
} // compute_ranks
|
C
|
#include <stdio.h>
int main() {
char Home_city[100] = " Chengdu";
int Gap, My_Age = 18, Brother_Age = 16;
float Pin_money = 7.5;//to declare 4 variables
Gap = My_Age - Brother_Age;//To calculate our gap
printf("Greetings!\tI am \\Yang Yuxin\\ who come from %s.My age is %d\n", Home_city, My_Age);//To introduce my origin and my age
printf("My brother is %d years younger than me.\n", Gap);//To introduce the year gap between me and my brother
printf("I have %.2f pounds of money each day.", Pin_money);/*The exact money I've got for each day.*/
printf("My house lies in central city.\n");//To explain the location of my house.
printf("In my family, we say\'wish you good luck\'a lot.\n");/*One custom of my family.*/
printf("Do you want to see my grades?Well let\'s see.\n\tWeek\tGrade\n\t1\t\"C+\"\n\t2\t\"B\"\n\t3\t\"A+\"");/*My grade of first three weeks*/
//Wait for a keypress
getchar();
}
|
C
|
#include "HexString.h"
static const uint8_t sucHex[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
static const uint8_t sucStr[]={0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0,0,10,11,12,13,14,15};
/**
* @brief Hex数据转换到String数据,比如0x31 对应就是 0x33 0x31
* @note 转出后的字母ABCDEF是大写的
* @param [in] pucHex 要转换的Hex数据块指针
* @param [in] usLength 要转换的Hex数据块大小
* @param [out] pcDesStr 要保存的String数据的位置
* @retval None
*/
void vNHexToString(uint8_t * pucHex,uint16_t usLength,char * pcDesStr){
uint16_t usI;
uint16_t usJ;
for(usI = 0;usI < usLength;usI++){
usJ = usI<<1;
pcDesStr[usJ] = sucHex[pucHex[usI]/16];
pcDesStr[usJ+1] = sucHex[pucHex[usI]%16];
}
// pcDesStr[usJ+2] = 0;
}
/**
* @brief String数据转换到Hex数据,比如0x33 0x31 对应就 0x31
* @note 传入的String字母ABCDEF必须大写
* @param [in] pcString 要转换的String数据块指针
* @param [in] usLength 要转换的String数据块大小
* @param [out] pucDesHex 要保存的Hex数据的位置
* @retval None
*/
void vStringToNHex(char * pcString,uint16_t usLength,uint8_t * pucDesHex){
uint16_t usI=0;
while(usI < usLength){
pucDesHex[usI>>1] = (sucStr[pcString[usI]-0x30]<<4) + sucStr[pcString[usI+1]-0x30];
usI +=2;
}
}
/**
* @brief Hex数据转换到String数据比如传入0x31返回0x33 0x31
* @note 转出后的字母ABCDEF是大写的;注意:返回的String数据末尾不会加\0
* @param [in] ucHex 要转换的Hex数据
* @param [in] pcString 返回转换后的String值,返回的String数据末尾不会加\0
* @retval None
*/
void vHexToString(uint8_t ucHex,uint8_t * pucString){
pucString[0] = sucHex[ucHex>>4];
pucString[1] = sucHex[ucHex&0x0f];
}
/**
* @brief String数据转换到Hex数据,比如传入"31"返回0x31
* @note 传入的String字母ABCDEF必须大写
* @param [in] pcString 要转换的String数据指针
* @retval 返回转换后的Hex值
*/
uint8_t ucStringToHex(char * pcString){
uint8_t ucHex=0;
ucHex = (sucStr[pcString[0]-0x30]<<4) + sucStr[pcString[1]-0x30];
return ucHex;
}
/**
* @brief Hex数据字符串形式转换到十进制数据比如传入0x31返回31(0x1f)
* @note
* @param [in] ucHex 要转换的Hex数据
* @param [in] pcString 返回转换后的String值,返回的String数据末尾不会加\0
* @retval 返回十进制值
*/
DE_Inline uint8_t vHexToDec(uint8_t ucHex,uint8_t * pucDecember){
*pucDecember = ((ucHex & 0xf0)>>4)*10 + (ucHex & 0x0f);
return *pucDecember;
}
uint8_t HexToDec[154] = {
0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x00,0x00,0x00,0x00,0x00,0x00,
0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,0x11,0x12,0x13,0x00,0x00,0x00,0x00,0x00,0x00,
0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x00,0x00,0x00,0x00,0x00,0x00,
0x1e,0x1f,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x00,0x00,0x00,0x00,0x00,0x00,
0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,0x30,0x31,0x00,0x00,0x00,0x00,0x00,0x00,
0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x00,0x00,0x00,0x00,0x00,0x00,
0x3c,0x3d,0x3e,0x3f,0x40,0x41,0x42,0x43,0x44,0x45,0x00,0x00,0x00,0x00,0x00,0x00,
0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x00,0x00,0x00,0x00,0x00,0x00,
0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x00,0x00,0x00,0x00,0x00,0x00,
0x5a,0x5b,0x5c,0x5d,0x5e,0x5f,0x60,0x61,0x62,0x63
};
/*-------------------(C) COPYRIGHT 2020 头条@单片机嵌入式爱好者 ----------------*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct student{
char name[30];
float marks;
};
int main(){
struct student *student_ptr;
struct student real_student;
char name[30];
float mark;
student_ptr = real_student;
scanf("%s", name); // already an address (&name)
scanf("%f", &mark);
sprintf(student_ptr->name, name);
student_ptr->marks = mark;
printf("Name is %s\n", real_student.name);
printf("Marks are %f\n", real_student.marks);
}
|
C
|
#include "stdio.h"
#include "datasizes.h"
#include "boundary.h"
#include "params.h"
#define bitsof(type) (sizeof(type) * 8)
static inline
boundary_t boundary_rotl(boundary_t boundary, int shift) {
boundary.bits =
(((boundary.bits << (shift * BITS)) & ((1ull << (boundary.size * BITS)) - 1)) |
(boundary.bits >> ((boundary.size - shift) * BITS)));
return boundary;
}
static inline
boundary_t boundary_rotr(boundary_t boundary, int shift) {
boundary.bits = (((boundary.bits >> (shift * BITS)) |
(boundary.bits << ((boundary.size - shift) * BITS))) & ((1ull << (boundary.size * BITS)) - 1));
return boundary;
}
#ifndef NDEBUG
#include <stdio.h>
#include <stdlib.h>
static
void boundary_check(boundary_t boundary) {
if(boundary.bits != 0 && bitsof(boundary_bits_t) - __builtin_clzll(boundary.bits) > boundary.size * BITS) {
printf("Boundary %lx is larger then size %i\n", boundary.bits, boundary.size);
exit(0);
}
}
#else
static
void boundary_check(boundary_t boundary) { }
#endif
static
boundary_t boundary_normalize(boundary_t boundary) {
boundary_t max = boundary;
for(int i = 0; i < boundary.size; i++) {
boundary = boundary_rotl(boundary, 1);
if(max.bits < boundary.bits) max = boundary;
}
return max;
}
static
void boundary_write(boundary_t boundary) {
printf("[%02i] ", boundary.size);
for(int i = 63; i >= 0; i--) {
if(i < boundary.size) {
printf("%i", (int)((boundary.bits >> i) & 1));
} else {
printf(" ");
}
}
}
static
boundary_t boundary_unfold(boundary_t boundary, int n) {
boundary_t result = boundary;
result.size = boundary.size * n;
for(int i = 1; i < n; i++) {
result.bits <<= boundary.size;
result.bits |= boundary.bits;
}
return result;
}
static
boundary_t boundary_insert(boundary_t boundary, int ngon) {
boundary_t result = {.bits = 0, .size = 0};
if((boundary.bits >> (BITS * (boundary.size - 1))) < VALENCE - 2) {
u32 s;
if(VALENCE != 4) {
s = __builtin_ctzll(~boundary.bits) / BITS;
} else {
s = __builtin_ctzll(~(boundary.bits | 0x5555555555555555)) / BITS;
}
if(s != boundary.size - 1) {
if(s <= ngon - 2) {
result.bits = boundary.bits + (1ull << ((boundary.size - 1) * BITS));
result.bits >>= s * BITS;
result.bits += 1ull;
result.bits <<= (ngon - 2 - s) * BITS;
result.size = boundary.size + ngon - 2 - 2 * s;
}
} else {
if((boundary.bits >> (BITS * (boundary.size - 1))) < VALENCE - 3) {
if(boundary.size + 1 <= ngon) {
result.bits = (boundary.bits >> (BITS * (boundary.size - 1))) + 2;
result.bits <<= (ngon - boundary.size - 1) * BITS;
result.size = ngon - boundary.size;
}
} else {
if(boundary.size + 3 <= ngon) {
result.bits = 1 << (ngon - boundary.size - 3) * BITS;
result.bits = ngon - boundary.size - 2;
}
}
}
}
return result;
}
static
boundary_t boundary_remove(boundary_t boundary, int ngon) {
boundary_t result = {.bits = 0, .size = 0};
if((boundary.bits >> (BITS * (boundary.size - 1))) != 0) {
u32 s = __builtin_ctzll(boundary.bits) / BITS;
if(s != boundary.size - 1) {
if(s <= ngon - 2) {
result.bits = boundary.bits - (1ull << ((boundary.size - 1) * BITS));
result.bits >>= s * BITS;
result.bits -= 1;
result.bits <<= (ngon - 2 - s) * BITS;
result.bits |= (((1 << (ngon - 2 - s) * BITS) - 1) / LAST_NODE_MASK) * (VALENCE - 2);
result.size = boundary.size + ngon - 2 - 2 * s;
}
} else { // Overlapping case
if((boundary.bits >> (BITS * (boundary.size - 1))) < VALENCE - 3) { // Overlapping with a single node
if(boundary.size + 1 <= ngon) {
result.bits = (boundary.bits >> (BITS * (boundary.size - 1))) - 2;
result.bits <<= (ngon - boundary.size - 1) * BITS;
result.bits |= ((1 << ((ngon - boundary.size - 1) * BITS)) - 1) / LAST_NODE_MASK * (VALENCE - 2);
result.size = ngon - boundary.size;
}
} else { // Overlapping with a single edge
if(boundary.size + 3 <= ngon) {
result.bits = (VALENCE - 3) << ((ngon - boundary.size - 3) * BITS);
result.bits |= (((1 << ((ngon - boundary.size - 3) * BITS)) - 1) / LAST_NODE_MASK) * (VALENCE - 2);
result.size = ngon - boundary.size - 2;
}
}
}
}
return result;
}
static
char boundary_is_mouse(boundary_t boundary) {
// A mouse boundary complex has odd length and the head has valence 1
if(boundary.size % 2 == 1 && (boundary.bits & LAST_NODE_MASK) == 0) {
boundary.bits >>= 1;
boundary_bits_t v = boundary.bits;
boundary_bits_t s = bitsof(boundary_bits_t); // bit size; must be power of 2
boundary_bits_t mask = ~0ull;
while ((s >>= 1ull) >= (1ull << (BITS - 1))) {
mask ^= (mask << s);
v = ((v >> s) & mask) | ((v << s) & ~mask);
}
v >>= bitsof(boundary_bits_t) / BITS - boundary.size + 1;
if(boundary.bits + v == (1 << (boundary.size - 1)) - 1) {
return 1;
}
}
return 0;
}
|
C
|
#ifndef MEASUREMENT_H__
#define MEASUREMENT_H__
enum measurement_datatype
{
MT_INT8,
MT_INT16,
MT_INT32,
MT_UINT8,
MT_UINT16,
MT_UINT32,
MT_FLOAT,
MT_STRING,
};
struct measurement
{
const char *name;
enum measurement_datatype type;
const void *data;
};
struct measure_callback
{
size_t num_measures;
int (*init_func)(void); //returns 0 on success
int (*measure_func)(struct measurement *measurements); //returns number of successfull measurements
};
#endif
|
C
|
/*
* populaton.c
*
* Created on: Apr 17, 2018
* Author: Zeeshan
*
*
* Population
In a population, the birth rate is the percentage increase of the population due to births,
and the death rate is the percentage decrease of the population due to deaths.
Write a program that displays the size of a population for any number of years.
*/
#include <stdio.h>
#include <stdlib.h>
double calculatePopulationYear(int P, double B, double D){
double newPopulation = (P + B*P - D*P);
return newPopulation;
}
int main(){
int originalSize, numOfYears;
double birthRate,deathRate;
//
printf("Please enter the starting size of population\n");
scanf("%d", &originalSize);
if(originalSize < 2){
printf("Error, incorrect input for population: ");
exit(1);
}
printf("Enter the annual birth rate: ");
scanf("%f",&birthRate);
if(birthRate < 0)
{
printf("Error, incorrect input for annual birth rate: ");
}
printf("Enter the annual death rate: ");
scanf("%f", &deathRate);
if(deathRate < 0)
{
printf("Error, incorrect input for death rate");
}
printf("Enter the numbers of years to display: ");
scanf("%d",&numOfYears);
if(numOfYears< 2){
printf("Error, incorrect input for number of years ");
}
else{
//calculate and print population for number of numOfYears
double population = (double)calculatePopulationYear(originalSize,birthRate,deathRate);
printf("Year 1: %.0f\n",population);
for(int i = 0; i< numOfYears-1; i++){
population = calculatePopulationYear(population,birthRate,deathRate);
printf("Year %d: %.0f\n",i+2,population);
}
}
return 0;
}
|
C
|
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#ifndef __DEBUG__
#define __DEBUG__ 1
#endif
#define LOWER_BOUND 0
#define UPPER_BOUND 999
#define STR_BUFFER_SIZE 80
#define NUMSTR_CONJ_AND "AND"
#define NUMSTR_HUNDRED "HUNDRED"
#define NUMSTR_ZERO "ZERO"
#define NUMSTR_ONE "ONE"
#define NUMSTR_TWO "TWO"
#define NUMSTR_THREE "THREE"
#define NUMSTR_FOUR "FOUR"
#define NUMSTR_FIVE "FIVE"
#define NUMSTR_SIX "SIX"
#define NUMSTR_SEVEN "SEVEN"
#define NUMSTR_EIGHT "EIGHT"
#define NUMSTR_NINE "NINE"
#define NUMSTR_TEN "TEN"
#define NUMSTR_ELEVEN "ELEVEN"
#define NUMSTR_TWELVE "TWELVE"
#define NUMSTR_THIRTEEN "THIRTEEN"
#define NUMSTR_FOURTEEN "FOURTEEN"
#define NUMSTR_FIFTEEN "FIFTEEN"
#define NUMSTR_SIXTEEN "SIXTEEN"
#define NUMSTR_SEVENTEEN "SEVENTEEN"
#define NUMSTR_EIGHTEEN "EIGHTEEN"
#define NUMSTR_NINETEEN "NINETEEN"
#define NUMSTR_TWENTY "TWENTY"
#define NUMSTR_THIRTY "THIRTY"
#define NUMSTR_FOURTY "FOURTY"
#define NUMSTR_FIFTY "FIFTY"
#define NUMSTR_SIXTY "SIXTY"
#define NUMSTR_SEVENTY "SEVENTY"
#define NUMSTR_EIGHTY "EIGHTY"
#define NUMSTR_NINETY "NINETY"
#define NULL_STR "\0"
typedef struct ThreeDigitInteger {
int32_t hundredthDigit;
int32_t tenthDigit;
int32_t unitsDigit;
} ThreeDigitInteger_t;
static char str[STR_BUFFER_SIZE];
int32_t askForTargetNumber(void);
void clearInputBuffer(void);
const char* verbalize(int32_t n);
ThreeDigitInteger_t digitize(int32_t n);
const char* convertDigitToString(int32_t n);
const char* convertTenToNineteenToString(int32_t n);
const char* convertTwentyToNinetyNineToString(int32_t n);
const char* convertTensWithinOneHundredToString(int32_t n);
const char* convertTwoDigitNumbersAboveTwentyNotTensToString(int32_t n);
bool isNumberBetween(int32_t n, int32_t lowerBound, int32_t upperBound);
bool isMultipleOfTen(int32_t n);
#if __DEBUG__ == 1
void testNumberCorrespondsToString(int32_t n, const char* s);
#endif
int32_t main(void) {
int32_t targetNumber = askForTargetNumber();
const char* targetNumberToString = verbalize(targetNumber);
printf("%i => %s\n", targetNumber, targetNumberToString);
#if __DEBUG__ == 1
testNumberCorrespondsToString(0, "ZERO");
testNumberCorrespondsToString(1, "ONE");
testNumberCorrespondsToString(2, "TWO");
testNumberCorrespondsToString(3, "THREE");
testNumberCorrespondsToString(4, "FOUR");
testNumberCorrespondsToString(5, "FIVE");
testNumberCorrespondsToString(6, "SIX");
testNumberCorrespondsToString(7, "SEVEN");
testNumberCorrespondsToString(8, "EIGHT");
testNumberCorrespondsToString(9, "NINE");
testNumberCorrespondsToString(10, "TEN");
testNumberCorrespondsToString(11, "ELEVEN");
testNumberCorrespondsToString(12, "TWELVE");
testNumberCorrespondsToString(13, "THIRTEEN");
testNumberCorrespondsToString(14, "FOURTEEN");
testNumberCorrespondsToString(15, "FIFTEEN");
testNumberCorrespondsToString(16, "SIXTEEN");
testNumberCorrespondsToString(17, "SEVENTEEN");
testNumberCorrespondsToString(18, "EIGHTEEN");
testNumberCorrespondsToString(19, "NINETEEN");
testNumberCorrespondsToString(20, "TWENTY");
testNumberCorrespondsToString(21, "TWENTY ONE");
testNumberCorrespondsToString(30, "THIRTY");
testNumberCorrespondsToString(99, "NINETY NINE");
testNumberCorrespondsToString(100, "ONE HUNDRED");
testNumberCorrespondsToString(101, "ONE HUNDRED AND ONE");
testNumberCorrespondsToString(110, "ONE HUNDRED AND TEN");
testNumberCorrespondsToString(111, "ONE HUNDRED AND ELEVEN");
testNumberCorrespondsToString(120, "ONE HUNDRED AND TWENTY");
testNumberCorrespondsToString(121, "ONE HUNDRED AND TWENTY ONE");
testNumberCorrespondsToString(200, "TWO HUNDRED");
testNumberCorrespondsToString(201, "TWO HUNDRED AND ONE");
testNumberCorrespondsToString(210, "TWO HUNDRED AND TEN");
testNumberCorrespondsToString(211, "TWO HUNDRED AND ELEVEN");
testNumberCorrespondsToString(220, "TWO HUNDRED AND TWENTY");
testNumberCorrespondsToString(221, "TWO HUNDRED AND TWENTY ONE");
testNumberCorrespondsToString(999, "NINE HUNDRED AND NINETY NINE");
#endif
return 0;
}
int32_t askForTargetNumber(void) {
int32_t _targetNumber = 0;
printf("Please enter the number to convert to string [0-999]:\n");
scanf("%i", &_targetNumber);
assert(_targetNumber >= LOWER_BOUND && _targetNumber <= UPPER_BOUND);
clearInputBuffer();
return _targetNumber;
}
void clearInputBuffer(void) {
char ch;
while ((ch = getchar()) != '\n' && ch != EOF);
}
/**
* There are several possible cases for converting a three digit number n to its
* string representation S:
* - Given conversion to string function str(m) where m is an integer;
* - Given that the number n = 100 * X + 10 * Y + 1 * Z, where:
* - X is the hundredth digit,
* - Y is the tenth digit, and
* - Z is the units digit.
* - Possible representation combinations include:
* S ::== <X HUNDRED> AND <str(10*Y)> <str(Z)> [CASE 1.0]
* | <X HUNDRED> AND <str(10*Y)> [CASE 1.1]
* | <X HUNDRED> AND <str(Z)> [CASE 1.2]
* | <X HUNDRED> [CASE 1.3]
* | <str(10*Y)> <str(Z)> [CSAE 2.0]
* | <str(10*Y)> [CASE 2.1]
* | <str(Z)> [CASE 3]
* - Note that there is a special case for 11-19.
*/
const char* verbalize(int32_t targetNumber) {
assert(targetNumber >= 0 && targetNumber <= 999);
ThreeDigitInteger_t n = digitize(targetNumber);
if (n.hundredthDigit >= 1 && n.hundredthDigit <= 9) { // CASE 1.n
const char* hundredthDigitString = convertDigitToString(n.hundredthDigit);
if (n.tenthDigit == 0 && n.unitsDigit == 0) { // CASE 1.3
snprintf(str, STR_BUFFER_SIZE, "%s %s", hundredthDigitString, NUMSTR_HUNDRED);
return str;
} else if (n.tenthDigit == 0 && n.unitsDigit != 0) { // CASE 1.2
const char* unitsDigitString = convertDigitToString(n.unitsDigit);
snprintf(str, STR_BUFFER_SIZE, "%s %s %s %s",
hundredthDigitString, NUMSTR_HUNDRED, NUMSTR_CONJ_AND, unitsDigitString);
return str;
} else if (n.tenthDigit != 0 && n.unitsDigit == 0) { // CASE 1.1
const char* tenthDigitString = convertTensWithinOneHundredToString(n.tenthDigit*10);
snprintf(str, STR_BUFFER_SIZE, "%s %s %s %s",
hundredthDigitString, NUMSTR_HUNDRED, NUMSTR_CONJ_AND, tenthDigitString);
return str;
} else if (n.tenthDigit == 1 && n.unitsDigit != 0) { // Special case X11-X19
const char* numberString = convertTenToNineteenToString(n.tenthDigit*10 + n.unitsDigit);
snprintf(str, STR_BUFFER_SIZE, "%s %s %s %s",
hundredthDigitString, NUMSTR_HUNDRED, NUMSTR_CONJ_AND, numberString);
return str;
} else { // CASE 1.0
const char* tenthDigitString = convertTensWithinOneHundredToString(n.tenthDigit*10);
const char* unitsDigitString = convertDigitToString(n.unitsDigit);
snprintf(str, STR_BUFFER_SIZE, "%s %s %s %s %s",
hundredthDigitString, NUMSTR_HUNDRED, NUMSTR_CONJ_AND, tenthDigitString, unitsDigitString);
return str;
}
} else if (n.hundredthDigit == 0 && n.tenthDigit >= 1 && n.tenthDigit <= 9) { // CASE 2.n
if (n.tenthDigit == 1 && n.unitsDigit != 0) { // Handle 11-19 special case
const char* numberString = convertTenToNineteenToString(n.tenthDigit*10 + n.unitsDigit);
snprintf(str, STR_BUFFER_SIZE, "%s", numberString);
return str;
} else if (n.unitsDigit == 0) { // CASE 2.1
const char* tenthString = convertTensWithinOneHundredToString(n.tenthDigit*10);
snprintf(str, STR_BUFFER_SIZE, "%s", tenthString);
return str;
} else { // CASE 2.0
const char* tenthString = convertTensWithinOneHundredToString(n.tenthDigit*10);
const char* unitsString = convertDigitToString(n.unitsDigit);
snprintf(str, STR_BUFFER_SIZE, "%s %s", tenthString, unitsString);
return str;
}
} else { // CASE 3
return convertDigitToString(n.unitsDigit);
}
return NULL_STR;
}
ThreeDigitInteger_t digitize(int32_t targetNumber) {
int32_t hundredthDigit = targetNumber / 100;
int32_t twoDigitRemainder = targetNumber % 100;
int32_t tenthDigit = twoDigitRemainder / 10;
int32_t unitsDigit = twoDigitRemainder % 10;
ThreeDigitInteger_t n = {
.hundredthDigit = hundredthDigit,
.tenthDigit = tenthDigit,
.unitsDigit = unitsDigit
};
return n;
}
const char* convertDigitToString(int32_t n) {
switch (n) {
case 0:
return NUMSTR_ZERO;
case 1:
return NUMSTR_ONE;
case 2:
return NUMSTR_TWO;
case 3:
return NUMSTR_THREE;
case 4:
return NUMSTR_FOUR;
case 5:
return NUMSTR_FIVE;
case 6:
return NUMSTR_SIX;
case 7:
return NUMSTR_SEVEN;
case 8:
return NUMSTR_EIGHT;
case 9:
return NUMSTR_NINE;
default:
return NULL_STR;
}
}
const char* convertTenToNineteenToString(int32_t n) {
switch (n) {
case 10:
return NUMSTR_TEN;
case 11:
return NUMSTR_ELEVEN;
case 12:
return NUMSTR_TWELVE;
case 13:
return NUMSTR_THIRTEEN;
case 14:
return NUMSTR_FOURTEEN;
case 15:
return NUMSTR_FIFTEEN;
case 16:
return NUMSTR_SIXTEEN;
case 17:
return NUMSTR_SEVENTEEN;
case 18:
return NUMSTR_EIGHTEEN;
case 19:
return NUMSTR_NINETEEN;
default:
return NULL_STR;
}
}
const char* convertTensWithinOneHundredToString(int32_t n) {
switch (n) {
case 10:
return NUMSTR_TEN;
case 20:
return NUMSTR_TWENTY;
case 30:
return NUMSTR_THIRTY;
case 40:
return NUMSTR_FOURTY;
case 50:
return NUMSTR_FIFTY;
case 60:
return NUMSTR_SIXTY;
case 70:
return NUMSTR_SEVENTY;
case 80:
return NUMSTR_EIGHTY;
case 90:
return NUMSTR_NINETY;
default:
return NULL_STR;
}
}
#if __DEBUG__ == 1
static int testNumber = 0;
void testNumberCorrespondsToString(int32_t n, const char* s) {
const char* expectedString = s;
const char* actualString = verbalize(n);
printf("%s: %i\n", __FILE__, __LINE__);
printf("Test Number: %i\n", testNumber);
assert(strcmp(expectedString, actualString) == 0);
testNumber++;
}
#endif
|
C
|
/*
* @Author: cyang
* @Date: 2018-08-02 14:36:52
* @Last Modified by: cyang
* @Last Modified time: 2018-08-02 14:40:11
*/
#include <stdio.h>
#include <stdint.h>
int hammingDistance(int x, int y) {
int ret = 0;
for (int i = 0; i < 32; ++i)
{
/* code */
int a = x & 0x01;
int b = y & 0x01;
if(a != b)
ret++;
x >>= 1;
y >>= 1;
}
return ret;
}
int main(int argc, char const *argv[])
{
/* code */
int x = 2;
int y = 8;
printf("%d\n", hammingDistance(x,y));
return 0;
}
|
C
|
/*
* File: main.c
* Author: mquilles
*
* Created on 28 de Agosto de 2017, 20:10
*/
#include <stdio.h>
#include <stdlib.h>
int main() {
int a[5], b[5], c[10], i, contador = 0;
for (i = 0; i < 5; i++) {
printf("Informe o %d número para o vetor A: ",i);
scanf("%d", &a[i]);
}
for (i = 0; i < 5; i++) {
printf("Informe o %d número para o vetor B: ",i);
scanf("%d", &b[i]);
}
for (i = 0; i < 10; i++) {
if (i % 2 == 0) {
c[i] = a[i - contador];
contador++;
} else {
c[i] = b[i / 2];
}
}
printf("\nVetor C: ");
for (i = 0; i < 10; i++) {
printf("\n%d", c[i]);
}
return (EXIT_SUCCESS);
}
|
C
|
#include "sf2d.h"
#include "sf2d_private.h"
#include <math.h>
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif
void sf2d_draw_line(float x0, float y0, float x1, float y1, float width, u32 color)
{
sf2d_vertex_pos_col *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_col), 8);
if (!vertices) return;
float dx = x1 - x0;
float dy = y1 - y0;
float nx = -dy;
float ny = dx;
float len = sqrt(nx * nx + ny * ny);
if (len > 0 ){
nx /= len;
ny /= len;
}
nx *= width*0.5f;
ny *= width*0.5f;
vertices[0].position = (sf2d_vector_3f){x0+nx, y0+ny, SF2D_DEFAULT_DEPTH};
vertices[1].position = (sf2d_vector_3f){x0-nx, y0-ny, SF2D_DEFAULT_DEPTH};
vertices[2].position = (sf2d_vector_3f){x1+nx, y1+ny, SF2D_DEFAULT_DEPTH};
vertices[3].position = (sf2d_vector_3f){x1-nx, y1-ny, SF2D_DEFAULT_DEPTH};
vertices[0].color = color;
vertices[1].color = vertices[0].color;
vertices[2].color = vertices[0].color;
vertices[3].color = vertices[0].color;
GPU_SetTexEnv(
0,
GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR),
GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR),
GPU_TEVOPERANDS(0, 0, 0),
GPU_TEVOPERANDS(0, 0, 0),
GPU_REPLACE, GPU_REPLACE,
0xFFFFFFFF
);
GPU_SetAttributeBuffers(
2, // number of attributes
(u32*)osConvertVirtToPhys(vertices),
GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 4, GPU_UNSIGNED_BYTE),
0xFFFC, //0b1100
0x10,
1, //number of buffers
(u32[]){0x0}, // buffer offsets (placeholders)
(u64[]){0x10}, // attribute permutations for each buffer
(u8[]){2} // number of attributes for each buffer
);
GPU_DrawArray(GPU_TRIANGLE_STRIP, 0, 4);
}
void sf2d_draw_rectangle(int x, int y, int w, int h, u32 color)
{
sf2d_vertex_pos_col *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_col), 8);
if (!vertices) return;
vertices[0].position = (sf2d_vector_3f){(float)x, (float)y, SF2D_DEFAULT_DEPTH};
vertices[1].position = (sf2d_vector_3f){(float)x+w, (float)y, SF2D_DEFAULT_DEPTH};
vertices[2].position = (sf2d_vector_3f){(float)x, (float)y+h, SF2D_DEFAULT_DEPTH};
vertices[3].position = (sf2d_vector_3f){(float)x+w, (float)y+h, SF2D_DEFAULT_DEPTH};
vertices[0].color = color;
vertices[1].color = vertices[0].color;
vertices[2].color = vertices[0].color;
vertices[3].color = vertices[0].color;
GPU_SetTexEnv(
0,
GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR),
GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR),
GPU_TEVOPERANDS(0, 0, 0),
GPU_TEVOPERANDS(0, 0, 0),
GPU_REPLACE, GPU_REPLACE,
0xFFFFFFFF
);
GPU_SetAttributeBuffers(
2, // number of attributes
(u32*)osConvertVirtToPhys(vertices),
GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 4, GPU_UNSIGNED_BYTE),
0xFFFC, //0b1100
0x10,
1, //number of buffers
(u32[]){0x0}, // buffer offsets (placeholders)
(u64[]){0x10}, // attribute permutations for each buffer
(u8[]){2} // number of attributes for each buffer
);
GPU_DrawArray(GPU_TRIANGLE_STRIP, 0, 4);
}
void sf2d_draw_rectangle_rotate(int x, int y, int w, int h, u32 color, float rad)
{
sf2d_vertex_pos_col *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_col), 8);
if (!vertices) return;
int w2 = w/2.0f;
int h2 = h/2.0f;
vertices[0].position = (sf2d_vector_3f){(float)-w2, (float)-h2, SF2D_DEFAULT_DEPTH};
vertices[1].position = (sf2d_vector_3f){(float) w2, (float)-h2, SF2D_DEFAULT_DEPTH};
vertices[2].position = (sf2d_vector_3f){(float)-w2, (float) h2, SF2D_DEFAULT_DEPTH};
vertices[3].position = (sf2d_vector_3f){(float) w2, (float) h2, SF2D_DEFAULT_DEPTH};
vertices[0].color = color;
vertices[1].color = vertices[0].color;
vertices[2].color = vertices[0].color;
vertices[3].color = vertices[0].color;
float m[4*4];
matrix_set_z_rotation(m, rad);
sf2d_vector_3f rot[4];
int i;
for (i = 0; i < 4; i++) {
vector_mult_matrix4x4(m, &vertices[i].position, &rot[i]);
vertices[i].position = (sf2d_vector_3f){rot[i].x + x + w2, rot[i].y + y + h2, rot[i].z};
}
GPU_SetTexEnv(
0,
GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR),
GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR),
GPU_TEVOPERANDS(0, 0, 0),
GPU_TEVOPERANDS(0, 0, 0),
GPU_REPLACE, GPU_REPLACE,
0xFFFFFFFF
);
GPU_SetAttributeBuffers(
2, // number of attributes
(u32*)osConvertVirtToPhys(vertices),
GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 4, GPU_UNSIGNED_BYTE),
0xFFFC, //0b1100
0x10,
1, //number of buffers
(u32[]){0x0}, // buffer offsets (placeholders)
(u64[]){0x10}, // attribute permutations for each buffer
(u8[]){2} // number of attributes for each buffer
);
GPU_DrawArray(GPU_TRIANGLE_STRIP, 0, 4);
}
void sf2d_draw_fill_circle(int x, int y, int radius, u32 color)
{
static const int num_segments = 100;
sf2d_vertex_pos_col *vertices = sf2d_pool_memalign((num_segments + 2) * sizeof(sf2d_vertex_pos_col), 8);
if (!vertices) return;
vertices[0].position = (sf2d_vector_3f){(float)x, (float)y, SF2D_DEFAULT_DEPTH};
vertices[0].color = color;
float theta = 2 * M_PI / (float)num_segments;
float c = cosf(theta);
float s = sinf(theta);
float t;
float xx = radius;
float yy = 0;
int i;
for (i = 1; i <= num_segments; i++) {
vertices[i].position = (sf2d_vector_3f){(float)(x + xx), (float)(y + yy), SF2D_DEFAULT_DEPTH};
vertices[i].color = vertices[0].color;
t = xx;
xx = c * xx - s * yy;
yy = s * t + c * yy;
}
vertices[num_segments + 1].position = vertices[1].position;
vertices[num_segments + 1].color = vertices[1].color;
GPU_SetTexEnv(
0,
GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR),
GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR),
GPU_TEVOPERANDS(0, 0, 0),
GPU_TEVOPERANDS(0, 0, 0),
GPU_REPLACE, GPU_REPLACE,
0xFFFFFFFF
);
GPU_SetAttributeBuffers(
2, // number of attributes
(u32*)osConvertVirtToPhys(vertices),
GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 4, GPU_UNSIGNED_BYTE),
0xFFFC, //0b1100
0x10,
1, //number of buffers
(u32[]){0x0}, // buffer offsets (placeholders)
(u64[]){0x10}, // attribute permutations for each buffer
(u8[]){2} // number of attributes for each buffer
);
GPU_DrawArray(GPU_TRIANGLE_FAN, 0, num_segments + 2);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DIR_LEFT 0
#define DIR_RIGHT 1
#define DIR_TOP 2
#define DIR_BOTTOM 3
typedef struct {
int x;
int y;
} POSITION;
typedef int DIRECTION;
typedef struct _KEY_CHAIN {
POSITION pos;
DIRECTION dir;
struct _KEY_CHAIN *next;
} KEY_CHAIN;
typedef char MAP;
|
C
|
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int n=coins.size();
// dp[i]: 能够拼凑为 i 元,所需要的最少的硬币数量。
int dp[amount+1];
dp[0]=0;
for(int i=1;i<=amount;i++){
dp[i]=INT_MAX;
for(int j=0;j<n;j++){
if(coins[j]<=i&&dp[i-coins[j]]!=INT_MAX && dp[i-coins[j]]+1<dp[i]){
dp[i]=dp[i-coins[j]]+1;
}
}
}
return dp[amount]==INT_MAX?-1:dp[amount];
}
};
|
C
|
//este archivo es el fichero fuente que al compilarse produce el ejecutable HIJO
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> /* for fork */
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/wait.h>
#include <string.h>
char status[3] ="";
typedef struct
{
long tipo;
int pid;
char status[3];
}Mensaje_struct;
void defensa(){
printf("\033[0;32m\t\t\t\t\t\t\tEl hijo \033[1;32m%5d\033[0;32m ha repelido un ataque\033[0m\n", getpid());
fflush(stdout);
strcpy(status,"OK");
}
void indefenso(){
fflush(stdout);
printf("\033[0;31mEl hijo \033[1;31m%5d\033[0;31m ha sido emboscado mientras realizaba un ataque\033[0m\n", getpid());
strcpy(status,"KO");
}
// metodo que añade un pid a la lista siempre que exista un hueco , respetando el semaforo
void add_pid( int pid, int number, int id_semaforo, int lista[], struct sembuf Operacion) {
int i;
//espera al semaforo
Operacion.sem_op = -1;
semop (id_semaforo, &Operacion, 1);
for( i = 0; i < number; ++ i ) {
if(lista[i] == 0) {
lista[i] = pid;
break;
}
}
//libera al semaforo
Operacion.sem_op = 1;
semop (id_semaforo, &Operacion, 1);
}
// metodo que cuenta el numero de pids que no son 0
int children_alive(int number, int id_semaforo, int lista[], struct sembuf Operacion) {
int i;
int count=0;
//espera al semaforo
Operacion.sem_op = -1;
semop (id_semaforo, &Operacion, 1);
for( i = 0; i < number; ++ i ) {
if(lista[i] != 0) {
count++;
}
}
//libera al semaforo
Operacion.sem_op = 1;
semop (id_semaforo, &Operacion, 1);
return count;
}
int coge_pid(int pids_vivos, int id_semaforo, int lista[], struct sembuf Operacion){
int pid=0;
while(pid==0){
int id_ataque = rand()%pids_vivos;
//espera al semaforo
Operacion.sem_op = -1;
semop (id_semaforo, &Operacion, 1);
//coge el pid
if(lista[id_ataque]==getpid()){
//si el pid es igual al del proceso lo ignora
//libera al semaforo
Operacion.sem_op = 1;
semop (id_semaforo, &Operacion, 1);
continue;
}
pid = lista[id_ataque];
//libera al semaforo
Operacion.sem_op = 1;
semop (id_semaforo, &Operacion, 1);
}
return pid;
}
int main(int argc, char ** argv)
{
setbuf(stdout, NULL);
/* Intializes random number generator */
srand(getpid());
//crea variables
key_t key;
int id_cola_mensajes, id_semaforo,id_mem_compartida; //variables del ipc
FILE* fifo_image;
int number = atoi(argv[4]);
//cogemos los identificadores de la tuberia sin nombre
int num1 = atoi(argv[2]);
int num2 = atoi(argv[3]);
//recreamos la tuberia en un array
int barrera[] = {num1, num2};
int pids_vivos;
Mensaje_struct mensaje;
int tamano_mensaje=sizeof(mensaje)-sizeof(mensaje.tipo);
struct sembuf Operacion;
Operacion.sem_num = 0;
Operacion.sem_flg = 0;
//crea la key
char *path = argv[1];
int id = 'X';
key = ftok(path, id);
//reabre los ipc
//creo la cola de mensajes con la key
id_cola_mensajes = msgget (key, 0777 | IPC_CREAT);
//creo el array y la memoria compartida
id_mem_compartida = shmget (key, number*sizeof(int), 0777 | IPC_CREAT);
int *lista = (int *) shmat(id_mem_compartida, 0, 0);
//creo el semaforo
id_semaforo = semget (key, 1, 0700 | IPC_CREAT);
//añade el pid a la lista de pids
int pid = getpid();
add_pid ( pid, number, id_semaforo, lista, Operacion);
// cierra el descriptor de escribir
close(barrera[1]);
char val;
//-----------------------------------------ronda de ataques---------------------------------
while(1)
{
//espera la barrera
read(barrera[0],&val,1);
//coge los pid vivos
pids_vivos = children_alive(number, id_semaforo, lista, Operacion);
//defiende
if(rand()%2==0){
signal(SIGUSR1,defensa);
usleep(200000);
}
//ataca
else{
signal(SIGUSR1,indefenso);
usleep(100000);
int pid_ataque = coge_pid( pids_vivos, id_semaforo, lista, Operacion);
printf("\t\t\t\033[1;33m%5d \033[0;33mAtacando al proceso \033[1;33m%5d\033[0m\n", getpid(), pid_ataque);
kill(pid_ataque,SIGUSR1);
usleep(100000);
}
//se envia el mensaje con el resultado del ataque al padre
mensaje.tipo= 1;
mensaje.pid = pid;
strcpy(mensaje.status,status);
msgsnd(id_cola_mensajes, (struct msgbuf *) &mensaje,tamano_mensaje,0);
}
}
|
C
|
#include <bgbccc.h>
bool BGBCC_FrBC_TypeSmallIntP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypeArrayP(ctx, ty))
return(false);
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_I)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UI)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_SB)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UB)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_SS)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_US)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeSmallLongP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypeArrayP(ctx, ty))
return(false);
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_L)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UL)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_I)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UI)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_NL)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UNL)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_SB)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UB)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_SS)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_US)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeUnsignedP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypeArrayP(ctx, ty))
return(false);
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UL)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UI)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_US)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UB)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UNL)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeIntP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypeArrayP(ctx, ty))
return(false);
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_I)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeLongP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_L)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeUnsignedIntP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypeArrayP(ctx, ty))
return(false);
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UI)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeUnsignedLongP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypeArrayP(ctx, ty))
return(false);
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UL)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeFloatP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypeArrayP(ctx, ty))
return(false);
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_F)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeDoubleP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypeArrayP(ctx, ty))
return(false);
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_D)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeBaseILFD_P(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypeArrayP(ctx, ty))
return(false);
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_I)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_L)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_F)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_D)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UL)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UI)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_NL)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UNL)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_SB)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UB)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_SS)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_US)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeBaseSmallILFD_P(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypeArrayP(ctx, ty))
return(false);
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_I)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_L)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_F)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_D)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UL)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UI)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_NL)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UNL)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_SB)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UB)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_SS)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_US)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeBaseSmallILFDP_P(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypeArrayP(ctx, ty))
return(false);
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(true);
return(BGBCC_FrBC_TypeBaseSmallILFD_P(ctx, ty));
}
bool BGBCC_FrBC_TypeBaseSmallIL_P(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypeArrayP(ctx, ty))
return(false);
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_I)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_L)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UL)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UI)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_NL)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UNL)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_SB)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UB)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_SS)
return(true);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_US)
return(true);
return(false);
}
bool BGBCC_FrBC_TypePointerP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if((ty.val&FR2C_TY_TYTY_MASK)==FR2C_TY_TYTY_BASIC)
{
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_P)
return(true);
if(ty.val&FR2C_TY_PTRMASK)
return(true);
}
return(false);
}
bool BGBCC_FrBC_TypeArrayP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if((ty.val&FR2C_TY_TYTY_MASK)==FR2C_TY_TYTY_BASIC)
{
if(ty.val&FR2C_TY_ARRMASK)
return(true);
}
return(false);
}
bool BGBCC_FrBC_TypeSignedByteP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_SB)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeUnsignedByteP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UB)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeSignedShortP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_SS)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeUnsignedShortP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_US)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeVoidP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_V)
return(true);
return(false);
}
bool BGBCC_FrBC_TypeEqualP(
BGBCC_FrCC_State *ctx,
frbc_type dty, frbc_type sty)
{
return(dty.val==sty.val);
}
bool BGBCC_FrBC_TypeBaseEqualP(
BGBCC_FrCC_State *ctx,
frbc_type dty, frbc_type sty)
{
if(BGBCC_FrBC_TypeIntP(ctx, dty) && BGBCC_FrBC_TypeIntP(ctx, sty))
return(true);
if(BGBCC_FrBC_TypeLongP(ctx, dty) && BGBCC_FrBC_TypeLongP(ctx, sty))
return(true);
if(BGBCC_FrBC_TypeFloatP(ctx, dty) && BGBCC_FrBC_TypeFloatP(ctx, sty))
return(true);
if(BGBCC_FrBC_TypeDoubleP(ctx, dty) && BGBCC_FrBC_TypeDoubleP(ctx, sty))
return(true);
if(BGBCC_FrBC_TypePointerP(ctx, dty) &&
BGBCC_FrBC_TypePointerP(ctx, sty))
return(true);
return(false);
}
bool BGBCC_FrBC_TypeOprBasicP(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(true);
if((ty.val&FR2C_TY_BASEMASK)>=16)
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_S)
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_V)
return(false);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UNDEF_I)
return(false);
return(true);
}
int BGBCC_FrBC_TypeAsOprBasic(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
if(BGBCC_FrBC_TypePointerP(ctx, ty))
return(FR2C_TY_P);
if((ty.val&FR2C_TY_BASEMASK)>=16)
return(-1);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_S)
return(-1);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_V)
return(-1);
if((ty.val&FR2C_TY_BASEMASK)==FR2C_TY_UNDEF_I)
return(-1);
return(ty.val&FR2C_TY_BASEMASK);
}
frbc_status BGBCC_FrBC_TypeDerefType(
BGBCC_FrCC_State *ctx,
frbc_type sty, frbc_type *rdty)
{
frbc_type tty;
// if(!BGBCC_FrBC_TypePointerP(ctx, ty))
if(BGBCC_FrBC_TypeArrayP(ctx, sty))
{
tty.val=sty.val&(FR2C_TY_BASEMASK|FR2C_TY_PTRMASK);
*rdty=tty;
return(FR2C_STATUS_YES);
}
if(!(sty.val&FR2C_TY_PTRMASK))
{
*rdty=sty;
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
}
tty.val=sty.val-FR2C_TY_PTRIDX1;
*rdty=tty;
return(FR2C_STATUS_YES);
}
frbc_status BGBCC_FrBC_TypePointerType(
BGBCC_FrCC_State *ctx,
frbc_type sty, frbc_type *rdty)
{
frbc_type tty;
if(BGBCC_FrBC_TypeArrayP(ctx, sty))
{
tty.val=sty.val&(FR2C_TY_BASEMASK|FR2C_TY_PTRMASK);
tty.val=tty.val+FR2C_TY_PTRIDX1;
*rdty=tty;
return(FR2C_STATUS_YES);
}
// if(!BGBCC_FrBC_TypePointerP(ctx, ty))
// if(!(sty.val&FR2C_TY_PTRMASK))
// return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
tty.val=sty.val+FR2C_TY_PTRIDX1;
*rdty=tty;
return(FR2C_STATUS_YES);
}
frbc_status BGBCC_FrBC_TypeAutoPromoteType(
BGBCC_FrCC_State *ctx,
frbc_type sty, frbc_type *rdty)
{
frbc_type tty;
if(BGBCC_FrBC_TypeSmallIntP(ctx, sty) &&
!BGBCC_FrBC_TypeIntP(ctx, sty))
{
tty=BGBCC_FrBC_TypeWrapBasicType(FR2C_TY_I);
if(rdty)*rdty=tty;
return(FR2C_STATUS_YES);
}
#if 0
if(BGBCC_FrBC_TypeSmallLongP(ctx, sty) &&
!BGBCC_FrBC_TypeLongP(ctx, sty))
{
tty=BGBCC_FrBC_TypeWrapBasicType(FR2C_TY_L);
*rdty=ty;
return(FR2C_STATUS_YES);
}
#endif
if(rdty)*rdty=sty;
return(FR2C_STATUS_NO);
}
frbc_status BGBCC_FrBC_TypeFromSig(
BGBCC_FrCC_State *ctx,
frbc_type *rty, char *sig)
{
int asz[16];
BGBCC_FrCC_LiteralInfo *st;
frbc_type tty;
char *s;
int an, pn, bty;
int i, j, k;
s=sig; an=0; pn=0; bty=-1;
if((*s=='A') && (s[1]>='0') && (s[1]<='9'))
{
s++; i=0;
while(*s)
{
if(*s==';')
{
asz[an++]=i;
s++; break;
}
if(*s==',')
{
asz[an++]=i;
i=0; s++;
continue;
}
if((*s>='0') && (*s<='9'))
{
i=(i*10)+((*s++)-'0');
continue;
}
asz[an++]=i;
break;
}
}
while(*s=='P')
{ pn++; s++; }
switch(*s)
{
case 'a': bty=FR2C_TY_SB; break;
case 'b': bty=FR2C_TY_SB; break;
case 'c': bty=FR2C_TY_SB; break;
case 'd': bty=FR2C_TY_D; break;
case 'e': bty=FR2C_TY_D; break;
case 'f': bty=FR2C_TY_F; break;
case 'g': bty=FR2C_TY_F128; break;
case 'h': bty=FR2C_TY_UB; break;
case 'i': bty=FR2C_TY_I; break;
case 'j': bty=FR2C_TY_UI; break;
case 'k': bty=FR2C_TY_F16; break;
case 'l': bty=FR2C_TY_NL; break;
case 'm': bty=FR2C_TY_UNL; break;
case 'n': bty=FR2C_TY_I128; break;
case 'o': bty=FR2C_TY_UI128; break;
case 'p': bty=-1; break;
case 'q': bty=-1; break;
case 'r': bty=FR2C_TY_VARIANT; break;
case 's': bty=FR2C_TY_SS; break;
case 't': bty=FR2C_TY_US; break;
case 'u': bty=-1; break;
case 'v': bty=FR2C_TY_V; break;
case 'w': bty=FR2C_TY_US; break;
case 'x': bty=FR2C_TY_L; break;
case 'y': bty=FR2C_TY_UL; break;
case 'z': bty=FR2C_TY_VARARGS; break;
case 'X':
st=BGBCC_FrBC_LookupStructureForSig(ctx, s);
bty=st->litid+256;
break;
default: bty=-1; break;
}
if((bty>=0) && (an==0))
{
tty.val=bty|(pn<<FR2C_TY_PTRSHL)|
FR2C_TY_TYTY_BASIC;
*rty=tty;
return(FR2C_STATUS_YES);
}
if((bty>=0) && (an==1) && (asz[0]<FR2C_TY_BASEARRMAX))
{
tty.val=bty|(pn<<FR2C_TY_PTRSHL)|
(asz[0]<<FR2C_TY_ARRSHL)|
FR2C_TY_TYTY_BASIC;
*rty=tty;
return(FR2C_STATUS_YES);
}
return(FR2C_STATUS_NO);
}
char *BGBCC_FrBC_TypeGetSig(
BGBCC_FrCC_State *ctx, frbc_type ty)
{
char tb[256];
BGBCC_FrCC_LiteralInfo *st;
char *s, *t;
int pn, asz, bt;
int i;
if((ty.val&FR2C_TY_TYTY_MASK)==FR2C_TY_TYTY_BASIC)
{
pn=(ty.val&FR2C_TY_PTRMASK)>>FR2C_TY_PTRSHL;
asz=(ty.val&FR2C_TY_ARRMASK)>>FR2C_TY_ARRSHL;
bt=ty.val&FR2C_TY_BASEMASK;
t=tb;
if(asz)
{
sprintf(t, "A%d;", asz);
t+=strlen(t);
}
if(pn)
{
i=pn;
while(i--)*t++='P';
*t=0;
}
if(bt<256)
{
switch(bt)
{
case FR2C_TY_I: *t++='i'; break;
case FR2C_TY_L: *t++='x'; break;
case FR2C_TY_F: *t++='f'; break;
case FR2C_TY_D: *t++='d'; break;
case FR2C_TY_P:
*t++='P'; *t++='v'; break;
case FR2C_TY_V: *t++='v'; break;
case FR2C_TY_NL: *t++='l'; break;
case FR2C_TY_SB: *t++='c'; break;
case FR2C_TY_UB: *t++='h'; break;
case FR2C_TY_SS: *t++='s'; break;
case FR2C_TY_US: *t++='t'; break;
case FR2C_TY_UI: *t++='j'; break;
case FR2C_TY_UL: *t++='y'; break;
case FR2C_TY_UNL: *t++='m'; break;
case FR2C_TY_S: *t++='i'; break;
default:
break;
}
*t++=0;
}else
{
// st=ctx->literals[bt-256];
sprintf(t, "X%d", bt);
}
}
return(bgbcc_strdup(tb));
}
frbc_type BGBCC_FrBC_TypeWrapBasicType(int ty)
{
frbc_type tty;
tty.val=ty;
return(tty);
}
int BGBCC_FrBC_GetTypeConvMode(
BGBCC_FrCC_State *ctx,
frbc_type dty, frbc_type sty)
{
if(BGBCC_FrBC_TypeIntP(ctx, sty))
{
if(BGBCC_FrBC_TypeLongP(ctx, dty))
{ return(FR2C_OPCONV_I2L); }
if(BGBCC_FrBC_TypeFloatP(ctx, dty))
{ return(FR2C_OPCONV_I2F); }
if(BGBCC_FrBC_TypeDoubleP(ctx, dty))
{ return(FR2C_OPCONV_I2D); }
if(BGBCC_FrBC_TypePointerP(ctx, dty))
{ return(FR2C_OPCONV_I2P); }
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
}
if(BGBCC_FrBC_TypeLongP(ctx, sty))
{
if(BGBCC_FrBC_TypeIntP(ctx, dty))
{ return(FR2C_OPCONV_L2I); }
if(BGBCC_FrBC_TypeFloatP(ctx, dty))
{ return(FR2C_OPCONV_L2F); }
if(BGBCC_FrBC_TypeDoubleP(ctx, dty))
{ return(FR2C_OPCONV_L2D); }
if(BGBCC_FrBC_TypePointerP(ctx, dty))
{ return(FR2C_OPCONV_L2P); }
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
}
if(BGBCC_FrBC_TypeFloatP(ctx, sty))
{
if(BGBCC_FrBC_TypeIntP(ctx, dty))
{ return(FR2C_OPCONV_F2I); }
if(BGBCC_FrBC_TypeLongP(ctx, dty))
{ return(FR2C_OPCONV_F2L); }
if(BGBCC_FrBC_TypeDoubleP(ctx, dty))
{ return(FR2C_OPCONV_F2D); }
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
}
if(BGBCC_FrBC_TypeDoubleP(ctx, sty))
{
if(BGBCC_FrBC_TypeIntP(ctx, dty))
{ return(FR2C_OPCONV_D2I); }
if(BGBCC_FrBC_TypeLongP(ctx, dty))
{ return(FR2C_OPCONV_D2L); }
if(BGBCC_FrBC_TypeFloatP(ctx, dty))
{ return(FR2C_OPCONV_D2F); }
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
}
if(BGBCC_FrBC_TypePointerP(ctx, sty))
{
if(BGBCC_FrBC_TypeIntP(ctx, dty))
{ return(FR2C_OPCONV_P2I); }
if(BGBCC_FrBC_TypeLongP(ctx, dty))
{ return(FR2C_OPCONV_P2L); }
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
}
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
}
int BGBCC_FrBC_GetTypeConvIMode(
BGBCC_FrCC_State *ctx,
frbc_type dty, frbc_type sty)
{
int dt, st;
if(!BGBCC_FrBC_TypeSmallIntP(ctx, dty))
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
if(!BGBCC_FrBC_TypeSmallIntP(ctx, sty))
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
return(BGBCC_FrBC_GetTypeConvILMode(ctx, dty, sty));
}
int BGBCC_FrBC_GetTypeConvLMode(
BGBCC_FrCC_State *ctx,
frbc_type dty, frbc_type sty)
{
int dt, st;
if(!BGBCC_FrBC_TypeSmallLongP(ctx, dty))
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
if(!BGBCC_FrBC_TypeSmallLongP(ctx, sty))
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
return(BGBCC_FrBC_GetTypeConvILMode(ctx, dty, sty));
}
int BGBCC_FrBC_GetTypeConvILMode(
BGBCC_FrCC_State *ctx,
frbc_type dty, frbc_type sty)
{
int dt, st;
// if(!BGBCC_FrBC_TypeSmallIntP(ctx, dty))
// return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
// if(!BGBCC_FrBC_TypeSmallIntP(ctx, sty))
// return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
dt=dty.val; st=sty.val;
if(dt==FR2C_TY_I)
{
if(st==FR2C_TY_SB)
{ return(FR2C_OPCONV2_SXB); }
if(st==FR2C_TY_UB)
{ return(FR2C_OPCONV2_ZXB); }
if(st==FR2C_TY_SS)
{ return(FR2C_OPCONV2_SXS); }
if(st==FR2C_TY_US)
{ return(FR2C_OPCONV2_ZXS); }
if(st==FR2C_TY_I)
{ return(FR2C_OPCONV2_SXI); }
if(st==FR2C_TY_UI)
{ return(FR2C_OPCONV2_ZXI); }
}
if(dt==FR2C_TY_UI)
{
if(st==FR2C_TY_SB)
{ return(FR2C_OPCONV2_ZXB); }
if(st==FR2C_TY_SS)
{ return(FR2C_OPCONV2_ZXS); }
if(st==FR2C_TY_I)
{ return(FR2C_OPCONV2_ZXI); }
if(st==FR2C_TY_UB)
{ return(FR2C_OPCONV2_ZXB); }
if(st==FR2C_TY_US)
{ return(FR2C_OPCONV2_ZXS); }
if(st==FR2C_TY_UI)
{ return(FR2C_OPCONV2_ZXI); }
}
if((dt==FR2C_TY_L) || (dt==FR2C_TY_NL))
{
if(st==FR2C_TY_SB)
{ return(FR2C_OPCONV2_SXB); }
if(st==FR2C_TY_UB)
{ return(FR2C_OPCONV2_ZXB); }
if(st==FR2C_TY_SS)
{ return(FR2C_OPCONV2_SXS); }
if(st==FR2C_TY_US)
{ return(FR2C_OPCONV2_ZXS); }
if(st==FR2C_TY_I)
{ return(FR2C_OPCONV2_SXI); }
if(st==FR2C_TY_UI)
{ return(FR2C_OPCONV2_ZXI); }
}
if(dt==FR2C_TY_SB)
{ return(FR2C_OPCONV2_SXB); }
if(dt==FR2C_TY_UB)
{ return(FR2C_OPCONV2_ZXB); }
if(dt==FR2C_TY_SS)
{
if(st==FR2C_TY_SB)
{ return(FR2C_OPCONV2_SXB); }
if(st==FR2C_TY_UB)
{ return(FR2C_OPCONV2_ZXB); }
return(FR2C_OPCONV2_SXS);
}
if(dt==FR2C_TY_US)
{
if(st==FR2C_TY_SB)
{ return(FR2C_OPCONV2_ZXS); }
if(st==FR2C_TY_UB)
{ return(FR2C_OPCONV2_ZXB); }
return(FR2C_OPCONV2_ZXS);
}
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
}
bool BGBCC_FrBC_TypeSupportsOperatorP(
BGBCC_FrCC_State *ctx, frbc_type ty, int opr)
{
if(BGBCC_FrBC_TypeSmallIntP(ctx, ty))
{
return(true);
}
if(BGBCC_FrBC_TypeLongP(ctx, ty))
{
return(true);
}
if(BGBCC_FrBC_TypeFloatP(ctx, ty))
{
if(opr==FR2C_BINOP_ADD)
return(true);
if(opr==FR2C_BINOP_SUB)
return(true);
if(opr==FR2C_BINOP_MUL)
return(true);
if(opr==FR2C_BINOP_DIV)
return(true);
return(false);
}
if(BGBCC_FrBC_TypeDoubleP(ctx, ty))
{
if(opr==FR2C_BINOP_ADD)
return(true);
if(opr==FR2C_BINOP_SUB)
return(true);
if(opr==FR2C_BINOP_MUL)
return(true);
if(opr==FR2C_BINOP_DIV)
return(true);
return(false);
}
if(BGBCC_FrBC_TypePointerP(ctx, ty))
{
if(opr==FR2C_BINOP_ADD)
return(true);
if(opr==FR2C_BINOP_SUB)
return(true);
return(false);
}
return(false);
}
frbc_status BGBCC_FrBC_GetTypeBinaryDest(
BGBCC_FrCC_State *ctx, int opr,
frbc_type lty, frbc_type rty,
frbc_type *rdty)
{
int ltyb, rtyb, dtyb;
if(BGBCC_FrBC_TypeSmallIntP(ctx, lty) &&
BGBCC_FrBC_TypeSmallIntP(ctx, rty))
{
ltyb=lty.val&FR2C_TY_BASEMASK;
rtyb=rty.val&FR2C_TY_BASEMASK;
dtyb=FR2C_TY_I;
switch(ltyb)
{
case FR2C_TY_I:
switch(rtyb)
{
case FR2C_TY_I: dtyb=FR2C_TY_I; break;
case FR2C_TY_UI: dtyb=FR2C_TY_UI; break;
default: dtyb=FR2C_TY_I; break;
}
break;
case FR2C_TY_UI:
dtyb=FR2C_TY_UI; break;
case FR2C_TY_SB:
switch(rtyb)
{
case FR2C_TY_SB: dtyb=FR2C_TY_SB; break;
case FR2C_TY_UB: dtyb=FR2C_TY_UB; break;
case FR2C_TY_SS: dtyb=FR2C_TY_SS; break;
case FR2C_TY_US: dtyb=FR2C_TY_US; break;
case FR2C_TY_I: dtyb=FR2C_TY_I; break;
case FR2C_TY_UI: dtyb=FR2C_TY_UI; break;
default: dtyb=FR2C_TY_I; break;
}
break;
case FR2C_TY_UB:
switch(rtyb)
{
case FR2C_TY_SB: case FR2C_TY_UB:
dtyb=FR2C_TY_UB; break;
case FR2C_TY_SS: dtyb=FR2C_TY_SS; break;
case FR2C_TY_US: dtyb=FR2C_TY_US; break;
case FR2C_TY_I: dtyb=FR2C_TY_I; break;
case FR2C_TY_UI: dtyb=FR2C_TY_UI; break;
default: dtyb=FR2C_TY_I; break;
}
break;
case FR2C_TY_SS:
switch(rtyb)
{
case FR2C_TY_SB: case FR2C_TY_UB:
case FR2C_TY_SS:
dtyb=FR2C_TY_SS; break;
case FR2C_TY_US: dtyb=FR2C_TY_US; break;
case FR2C_TY_I: dtyb=FR2C_TY_I; break;
case FR2C_TY_UI: dtyb=FR2C_TY_UI; break;
default: dtyb=FR2C_TY_I; break;
}
break;
case FR2C_TY_US:
switch(rtyb)
{
case FR2C_TY_SB: case FR2C_TY_UB:
case FR2C_TY_SS: case FR2C_TY_US:
dtyb=FR2C_TY_US; break;
case FR2C_TY_I: dtyb=FR2C_TY_I; break;
case FR2C_TY_UI: dtyb=FR2C_TY_UI; break;
default: dtyb=FR2C_TY_I; break;
}
break;
default: dtyb=FR2C_TY_I; break;
}
*rdty=BGBCC_FrBC_MakeTypeID(ctx, dtyb);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
}
if(BGBCC_FrBC_TypeSmallLongP(ctx, lty) &&
BGBCC_FrBC_TypeSmallLongP(ctx, rty))
{
if(BGBCC_FrBC_TypeSmallIntP(ctx, lty))
{
*rdty=rty;
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
}
if(BGBCC_FrBC_TypeSmallIntP(ctx, rty))
{
*rdty=lty;
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
}
if(BGBCC_FrBC_TypeUnsignedLongP(ctx, lty))
{
*rdty=lty;
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
}
if(BGBCC_FrBC_TypeUnsignedLongP(ctx, rty))
{
*rdty=rty;
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
}
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_L);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
}
if(BGBCC_FrBC_TypeSmallIntP(ctx, lty))
{
if(BGBCC_FrBC_TypeSmallIntP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_I);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
if(BGBCC_FrBC_TypeSmallLongP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_L);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
if(BGBCC_FrBC_TypeFloatP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_D);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
if(BGBCC_FrBC_TypeDoubleP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_D);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
// if(BGBCC_FrBC_TypePointerP(ctx, rty))
// {
// *rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_L);
// return(FR2C_STATUS_YES);
// }
BGBCC_FrBC_TagError(ctx,
FR2C_TERR_STATUS(FR2C_STATUS_ERR_UNHANDLEDTYPE));
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
}
if(BGBCC_FrBC_TypeSmallLongP(ctx, lty))
{
if(BGBCC_FrBC_TypeSmallIntP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_L);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
if(BGBCC_FrBC_TypeSmallLongP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_L);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
if(BGBCC_FrBC_TypeFloatP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_D);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
if(BGBCC_FrBC_TypeDoubleP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_D);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
// if(BGBCC_FrBC_TypePointerP(ctx, dty))
// { return(FR2C_OPCONV_L2P); }
BGBCC_FrBC_TagError(ctx,
FR2C_TERR_STATUS(FR2C_STATUS_ERR_UNHANDLEDTYPE));
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
}
if(BGBCC_FrBC_TypeFloatP(ctx, lty))
{
if(BGBCC_FrBC_TypeSmallIntP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_D);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
if(BGBCC_FrBC_TypeSmallLongP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_D);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
if(BGBCC_FrBC_TypeFloatP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_F);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
if(BGBCC_FrBC_TypeDoubleP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_D);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
BGBCC_FrBC_TagError(ctx,
FR2C_TERR_STATUS(FR2C_STATUS_ERR_UNHANDLEDTYPE));
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
}
if(BGBCC_FrBC_TypeDoubleP(ctx, lty))
{
if(BGBCC_FrBC_TypeSmallIntP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_D);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
if(BGBCC_FrBC_TypeSmallLongP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_D);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
if(BGBCC_FrBC_TypeFloatP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_D);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
if(BGBCC_FrBC_TypeDoubleP(ctx, rty))
{
*rdty=BGBCC_FrBC_MakeTypeID(ctx, FR2C_TY_D);
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
BGBCC_FrBC_TagError(ctx,
FR2C_TERR_STATUS(FR2C_STATUS_ERR_UNHANDLEDTYPE));
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
}
if(BGBCC_FrBC_TypePointerP(ctx, lty))
{
if(BGBCC_FrBC_TypeSmallIntP(ctx, rty))
{
*rdty=lty;
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
if(BGBCC_FrBC_TypeSmallLongP(ctx, rty))
{
*rdty=lty;
return(BGBCC_FrBC_TypeSupportsOperatorP(ctx, *rdty, opr)?
FR2C_STATUS_YES:FR2C_STATUS_NO);
// return(FR2C_STATUS_YES);
}
BGBCC_FrBC_TagError(ctx,
FR2C_TERR_STATUS(FR2C_STATUS_ERR_UNHANDLEDTYPE));
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
}
BGBCC_FrBC_TagError(ctx,
FR2C_TERR_STATUS(FR2C_STATUS_ERR_UNHANDLEDTYPE));
return(FR2C_STATUS_ERR_UNHANDLEDTYPE);
}
|
C
|
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER 64
#define NAME_SIZE 32
#define MAX_SIZE 100000
struct File;
struct Dir {
char id[NAME_SIZE];
struct Dir *parent;
struct Dir *children;
struct Dir *next;
struct File *files;
};
struct File {
size_t size;
char id[NAME_SIZE];
struct Dir *parent;
struct File *next;
};
size_t get_int(char *str, int *p) {
size_t i = 0;
while (('0' <= str[*p]) && (str[*p] <= '9')) {
i = i * 10 + str[*p] - '0';
*p += 1;
}
*p += 1; // To easily get next int in a CSV.
return i;
}
void add_dir(struct Dir *dir, char *name) {
struct Dir *new_dir = (struct Dir *)malloc(sizeof(struct Dir));
strncpy(new_dir->id, name, NAME_SIZE);
new_dir->parent = dir;
new_dir->children = NULL;
new_dir->next = NULL;
new_dir->files = NULL;
struct Dir *tmp = dir->children;
if (tmp == NULL) {
dir->children = new_dir;
} else {
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = new_dir;
}
}
void add_file(struct Dir *dir, char *info) {
struct File *new_file = (struct File *)malloc(sizeof(struct File));
int p = 0;
new_file->size = get_int(info, &p);
strncpy(new_file->id, info + p, NAME_SIZE);
new_file->parent = dir;
new_file->next = NULL;
struct File *tmp = dir->files;
if (tmp == NULL) {
dir->files = new_file;
} else {
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = new_file;
}
}
struct Dir *cd(struct Dir *dir, char *name) {
if ((name[0] == '.') && (name[1] == '.')) {
return dir->parent;
}
struct Dir *tmp = dir->children;
while (strcmp(tmp->id, name) != 0) {
tmp = tmp->next;
}
return tmp;
}
size_t read_dir(struct Dir *root, size_t *size) {
size_t sum = 0;
struct File *file = root->files;
while (file != NULL) {
sum += file->size;
file = file->next;
}
/* printf("\nRead dir %s, direct file size %li, ", root->id, sum); */
struct Dir *dir = root->children;
while (dir != NULL) {
sum += read_dir(dir, size);
dir = dir->next;
}
/* printf("\n and including %s 's child size %li\n", root->id, sum); */
if (sum <= MAX_SIZE) {
*size += sum;
}
return sum;
}
int main(int argc, char **argv) {
(void)argc;
FILE *fd = fopen(argv[1], "r");
char input[BUFFER];
fgets(input, BUFFER, fd);
struct Dir *root = (struct Dir *)malloc(sizeof(struct Dir));
strncpy(root->id, "/", NAME_SIZE);
root->parent = NULL;
root->children = NULL;
root->next = NULL;
root->files = NULL;
struct Dir *pwd = root;
while (fgets(input, BUFFER, fd) != NULL) {
if (input[0] == '$') {
if (input[2] == 'c') {
// Change dir.
pwd = cd(pwd, input + 5);
}
// If "ls", then do nothing and read next line.
} else if (input[0] == 'd') {
// Dir listed, add to structure.
add_dir(pwd, input + 4);
} else {
// Only remaining possibility is file, add that.
add_file(pwd, input);
}
}
size_t tot_size = 0;
read_dir(root, &tot_size);
printf("\nResult: %li\n", tot_size);
return 0;
}
|
C
|
/*
* Program to evaluate polynomial expressions
** Author Dept. Date Notes ***************************
* Scotty Bauer Comp. Sci April 3 2020 Initial Version
* Scotty Bauer Comp. Sci April 8 2020 Added the number array to evaluate polynomial in a loop
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "utils.h"
#include "poly.h"
int main (int argc, char *argv[]){
FILE *ptr;
char *text= malloc(50);
int x;
int coef;
ptr = fopen(argv[1], "r");
//loop to replace newline with end of string and call parse and addPolyTerm
while (fgets(text, 50, ptr) != NULL) {
if (text[strlen(text)-1] == '\n'){
text[strlen(text)-1] = '\0';
}
// pass by reference to parse in utils.c
parse(text, &x, &coef);
addPolyTerm(x,coef);
}
fclose(ptr);
displayPolynomial();
//for loop through array of required x values to evaluate
int numbers[5] = {-2, -1, 0,1,2};
for (int i = 0; i<5; i++){
int result = evaluatePolynomial(numbers[i]);
printf("for x=%d, y=%d \n", numbers[i],result);
}
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
int judgeYear(int n)//жĺ
{
if (n / 4 == 0 || n / 100 != 100 && n / 400 == 0)//ж
return 0;//Ƿ0
else
return 1;//귵1
}
//
int main3()
{
int year = 0;
scanf("%d", &year);//жݵĺ
if(0==judgeYear(year))//0ʱ
printf("%d", year);
if (1 == judgeYear(year))
printf("%d", year);//1ʱ
system("pause");
return 0;
}
|
C
|
#include "list.h"
#include <stdio.h>
#include <stdlib.h>
#include "item.h"
#include "utils.h"
struct list {
int size;
struct node *head;
};
struct node {
Item value;
struct node *next;
};
List newList() {
List lista = malloc(sizeof(struct list));
lista->head = NULL;
lista->size = 0;
return lista;
}
List addHead(List list, Item item) {
struct node *newNode = malloc(sizeof(struct node));
newNode->value = item;
newNode->next = list->head;
list->head = newNode;
list->size++;
}
Item removeHead(List list) {
if(isEmpty(list)) {
fprintf(stderr, "List already empty!\n");
return NULL;
} else {
struct node *tempNode = list->head;
list->head = list->head->next;
Item tempItem = tempNode->value;
free(tempNode);
list->size--;
return tempItem;
}
}
Item getFirst(List list) {
if(isEmpty(list))
return NULL;
else
return list->head->value;
}
int isEmpty(List list) {
return list->head == NULL ? 1 : 0;
}
void sortList(List list) {
if(isEmpty(list))
fprintf(stderr, "List empty!\n");
else {
struct node *i, *j;
for(i = list->head; i != NULL; i = i->next)
for(j = list->head; j->next != NULL;
j = j->next) // finisce quando j->next!=NULL perchè all'interno del for ci riferiamo anche a j->next:
// se fosse NULL darebbe errore.
if(comp_items(j->value, j->next->value) > 0) swap(&(j->value), &(j->next->value));
}
return;
}
void printList(List list) {
if(isEmpty(list))
fprintf(stderr, "List empty!\n");
else {
struct node *p;
for(p = list->head; p != NULL; p = p->next) out_item(p->value);
}
return;
}
List insertTail(List list, Item item) {
insertItem(list, item, list->size);
}
List insertItem(List list, Item item, int pos) {
if(!pos)
addHead(list, item);
else if(pos > list->size) {
fprintf(stderr, "\nERR: Position is greater then list size!\n");
return list;
} else {
struct node *p = list->head;
struct node *newNode = malloc(sizeof(struct node));
for(int i = 0; i < pos - 1; p = p->next, i++)
;
newNode->value = item;
newNode->next = p->next;
p->next = newNode;
list->size++;
return list;
}
}
List reverseList(List list) {
struct node *prev = list->head;
struct node *p = prev->next;
struct node *temp;
prev->next = NULL;
for(; p != NULL; prev = p, p = temp) {
temp = p->next;
p->next = prev;
}
list->head = prev;
return list;
}
List cloneList(List list) {
struct node *p = list->head;
List clone = newList();
struct node *q = malloc(sizeof(struct node));
for(; p != NULL; p = p->next, q = q->next) {
addHead(clone, p->value);
}
reverseList(clone);
return clone;
}
int searchItem(List list, Item item) {
int i;
struct node *p = list->head;
for(i = 0; p != NULL; p = p->next, i++)
if(!comp_items(p->value, item)) break;
return i == list->size ? -1 : i;
}
Item removeItemPos(List list, int pos) {
if(isEmpty(list)) {
fprintf(stderr, "List already empty!\n");
return NULL;
} else if(!pos)
removeHead(list);
else {
struct node *p = list->head;
for(int i = 0; i < pos - 1; i++, p = p->next)
;
Item tempItem = p->next->value;
struct node *tmp = p->next;
p->next = p->next->next;
free(tmp);
list->size--;
return tempItem;
}
}
Item removeItemElem(List list, Item item) {
if(isEmpty(list)) {
fprintf(stderr, "List already empty!\n");
return NULL;
} else {
int pos = searchItem(list, item);
if(pos == -1)
fprintf(stderr, "Can't find the item!\n");
else {
removeItemPos(list, pos);
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "queue.h"
queue *queue_create()
{
queue *q;
q = (queue*)malloc(sizeof(queue));
q->len = 2;
q->a = (void**)malloc( 2 * sizeof(void*) );
q->first = q->last = 0;
return q;
}
int queue_empty(queue *q)
{
return q->first == q->last;
}
void queue_push(queue *q, void *value)
{
void **tmp;
if ( q->last >= q->len ) {
tmp = (void**)malloc( 2 * (q->len) * sizeof(void*) );
memcpy(tmp, q->a, (q->len) * sizeof(void*) );
q->len *= 2;
free(q->a);
q->a = tmp;
}
q->a[q->last++] = value;
}
void *queue_pop(queue *q)
{
assert( !queue_empty(q) );
return q->a[q->first++];
}
void *queue_top(queue *q)
{
assert( !queue_empty(q) );
return q->a[q->first];
}
|
C
|
#include <util.h>
char *j_strdup(const char *str)
{
if (str == NULL)
return NULL;
else
return strdup(str);
}
char *j_strcat(char *dest, const char *txt)
{
if (!txt) return(dest);
while (*txt)
*dest++ = *txt++;
*dest = '\0';
return(dest);
}
int j_strcmp(const char *a, const char *b)
{
if (a == NULL || b == NULL)
return -1;
while (*a == *b && *a != '\0' && *b != '\0'){ a++; b++; }
if (*a == *b) return 0;
return -1;
}
int j_strcasecmp(const char *a, const char *b)
{
if (a == NULL || b == NULL)
return -1;
else
return strcasecmp(a, b);
}
int j_strncmp(const char *a, const char *b, int i)
{
if (a == NULL || b == NULL)
return -1;
else
return strncmp(a, b, i);
}
int j_strncasecmp(const char *a, const char *b, int i)
{
if (a == NULL || b == NULL)
return -1;
else
return strncasecmp(a, b, i);
}
int j_strlen(const char *a)
{
if (a == NULL)
return 0;
else
return strlen(a);
}
int j_atoi(const char *a, int def)
{
if (a == NULL)
return def;
else
return atoi(a);
}
char *j_attr(const char** atts, const char *attr)
{
int i = 0;
while (atts[i] != '\0')
{
if (j_strcmp(atts[i], attr) == 0) return (char*)atts[i + 1];
i += 2;
}
return NULL;
}
/** like strchr, but only searches n chars */
char *j_strnchr(const char *s, int c, int n) {
int count;
for (count = 0; count < n; count++)
if (s[count] == (char)c)
return &((char *)s)[count];
return NULL;
}
|
C
|
#include "ocr.h"
#include "preprocess.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include "preprocess.h"
#include "segment.h"
#include "system.h"
static const int RESIZED_CHAR_DIM = 40; // dimension of resized character image for feature extraction
static const int CHAR_ZONE_COUNT = 16;
static const char* TRAINING_SET_FILE =
#if LCDK == 0
"data/training/training_set.bin";
#else
"C:/ti/OMAPL138_StarterWare_1_10_04_01/build/c674x/cgt_ccs/omapl138/lcdkOMAPL138/usb_host_msc/training_set.bin";
#endif
/******************************************************
* PRIVATE functions
* reallocates new block for DataSet's Data member
* Data is an array of DataPoint pointers
*******************************************************/
void ReallocateDataSet(DataSet* ts) {
int size = ts->Size;
int allocated = ts->Allocated;
if (ts->Allocated == 0) {
ts->Allocated += TRAINING_SET_ALLOCATE_BLOCK;
ts->Data = MemAllocate(sizeof(DataPoint*) * TRAINING_SET_ALLOCATE_BLOCK);
}
else {
ts->Allocated += TRAINING_SET_ALLOCATE_BLOCK;
#if LCDK == 0
ts->Data = realloc(ts->Data, ts->Allocated * sizeof(DataPoint*));
#else // LCDK has no support for realloc
DataPoint** new_block = MemAllocate(sizeof(DataPoint*) * ts->Allocated);
int i;
for (i = 0; i < ts->Allocated; i++) {
new_block[i] = ts->Data[i];
}
FreeMemory(ts->Data);
ts->Data = new_block;
#endif
}
allocated = ts->Allocated;
}
DataSet* InitTrainingSet() {
DataSet* ts = MemAllocate(sizeof(DataSet));
ts->Allocated = 0;
ts->Size = 0;
FILE* fp;
fp = fopen(TRAINING_SET_FILE, "rb");
if (fp) { // parse file if it exists
while (!feof(fp)) { // parse until end of file
// parse the file and obtain the feature vectors and class labels for each data point
// everything is stored contiguously and bytewise (no buffers, newlines, etc)
double* feature_vector = MemAllocate(sizeof(double) * FEATURE_VECTOR_LENGTH);
fread(feature_vector, sizeof(double), FEATURE_VECTOR_LENGTH, fp);
char class_label = (char)fgetc(fp);
DataPoint* dp = NewDataPoint(class_label, feature_vector);
if (class_label != EOF)
AddTrainingData(ts, dp);
}
fclose(fp);
}
return ts;
}
// assumes all DataPoint objects stored in ds are DYNAMICALLY allocated
// and thus stored on the heap
void FreeDataSet(DataSet* ds) {
if (!ds) return;
int i;
for (i = 0; i < ds->Size; i++) { // free each individual DataPoint object
if (ds->Data[i]->FeatureVector) FreeMemory(ds->Data[i]->FeatureVector);
if (ds->Data[i]) FreeMemory(ds->Data[i]);
}
FreeMemory(ds); // free the entire DataSet at the very end
}
// allocates and returns an empty DataSet object
DataSet* EmptyDataSet() {
DataSet* ds = (DataSet*)MemAllocate(sizeof(DataSet));
ds->Allocated = 0;
ds->Size = 0;
return ds;
}
// allocates and returns a DataPoint object
// feature_vector: array of features that must exist on the heap before passed
DataPoint* NewDataPoint(char class_label, double* feature_vector) {
DataPoint* td = MemAllocate(sizeof(DataPoint));
td->ClassLabel = class_label;
td->FeatureVector = feature_vector;
return td;
}
void AddTrainingData(DataSet* ts, DataPoint* td) {
int size = ts->Size;
if (ts->Size == ts->Allocated) { // if size has reached allocated limit, reallocate
ReallocateDataSet(ts);
}
ts->Data[ts->Size] = td;
ts->Size++;
size =ts->Size;
}
// trains the training set referenced by ts using the input Binary Document and class labels
void TrainTrainingSet(DataSet* ts, BinaryDocument* bd, char* class_labels, int num_labels) {
SegmentText(ts, bd, class_labels, num_labels);
}
// writes training set to a text file
void WriteTrainingSet(DataSet* ts) {
FILE* fp;
fp = fopen(TRAINING_SET_FILE, "wb");
int i, j;
for (i = 0; i < ts->Size; i++) {
fwrite(ts->Data[i]->FeatureVector, sizeof(double), FEATURE_VECTOR_LENGTH, fp);
fwrite(&(ts->Data[i]->ClassLabel), sizeof(char), 1, fp);
}
fclose(fp);
}
/**********************************************************************************
* Classifies a test set using data from training set "train" using K-nearest neighbors
* The test set will contain points with both null and non-null labels.
* This algorithm will only use the points with null labels for Classification. The rest
* of the points will have their class label automatically output
*
* train: training set
* test: test set
**********************************************************************************/
char* ClassifyTestSet(DataSet* train, DataSet* test, int k) {
int test_size = test->Size;
char* output = MemAllocate(sizeof(char) * (test_size + 1)); // leave room for null terminator
output[test_size] = '\0';
int i;
for (i = 0; i < test_size; i++) {
DataPoint* test_point = test->Data[i];
char output_char;
if (test_point->ClassLabel == '\0') { // only classify test poinnts with null labels
output_char = ClassifyDataPoint(train, test_point, k);
}
else {
output_char = test_point->ClassLabel;
}
output[i] = output_char;
test_point->ClassLabel = output_char;
}
return output;
}
/*****************************************************************************
* Neighbor struct and accompanying functions are only used for the purposes
* of function ClassifyDataPoint()
*****************************************************************************/
typedef struct {
double DistSquared;
char ClassLabel;
} Neighbor; // struct containing a neighbor's distance squared and class label
int CompareNeighbor(Neighbor* a, Neighbor* b) { // for qsort (increasing order)
if (a->DistSquared < b->DistSquared) {
return -1;
}
else if (a->DistSquared > b->DistSquared) {
return 1;
}
else return 0;
}
/******************************************************************************
* classifies data point using the K-nearest neighbors algorithm and
* returns the label of the resulting class
*
* ts: pointer to the training set to classify from
* dp: pointer to data point object
* k: parameter for K-nearest neighbors classification
*******************************************************************************/
char ClassifyDataPoint(DataSet* ts, DataPoint* dp, int k) {
if (!ts || ! dp || ts->Size == 0 || k <= 0) return '\0';
int i;
Neighbor* neighbor_vector; // vector of neighbor structs for ALL datapoints in ts
neighbor_vector = MemAllocate(sizeof(Neighbor) * ts->Size);
for (i = 0; i < ts->Size; i++) { // iterate through all datapoints in training set
DataPoint* train_point = ts->Data[i];
double dist_squared = 0;
int j;
for (j = 0; j < FEATURE_VECTOR_LENGTH; j++) {
dist_squared += pow(dp->FeatureVector[j] - train_point->FeatureVector[j], 2.0);
}
Neighbor neighbor;
neighbor.ClassLabel = train_point->ClassLabel;
neighbor.DistSquared = dist_squared;
neighbor_vector[i] = neighbor;
}
// sort neighbor vector in order of increasing distance squared
qsort(neighbor_vector, ts->Size, sizeof(Neighbor), CompareNeighbor);
// find the most frequent class of the K-nearest ones
int votes[255]; // contains vote count for the class of the K-nearest neighbors
for (i = 0; i < 255; i++) {
votes[i] = 0;
}
for (i = 0; i < k; i++) {
char class_label = neighbor_vector[i].ClassLabel;
votes[(int)class_label]++;
}
int max = votes[0];
char max_char = neighbor_vector[0].ClassLabel; // most frequent class in K-nearest neighbors
for (i = 0; i < k; i++) { // get character with the most frequent votes
char class_label = neighbor_vector[i].ClassLabel;
int votes_i = votes[(int)class_label];
if (votes_i > max) {
max = votes_i;
max_char = class_label;
}
}
FreeMemory(neighbor_vector);
return max_char;
}
/* takes in a GRAYSCALE (8 bpp) image of a character and computes the feature vector
* feature vector is determined by dividing the resized image into 16 zones
* and computing the average pixel value in those zones
*/
double* GetFeatureVector(unsigned char* char_pixels, int height, int width, int doc_width) {
if (height == 0 || width == 0) return;
unsigned char* resized_image = ResizeCharacter(char_pixels, height, width, RESIZED_CHAR_DIM, RESIZED_CHAR_DIM, doc_width);
//WriteToFile("data/resized_char.txt", resized_image, 40, 40);
double* feature_vector = (double*)MemAllocate(sizeof(double) * CHAR_ZONE_COUNT);
int i;
for (i = 0; i < CHAR_ZONE_COUNT; i++) {
feature_vector[i] = 0.0;
}
// divide resized character image into zones
int zone_count_width = (int)sqrt(CHAR_ZONE_COUNT); // number of zones along width
int zone_length = RESIZED_CHAR_DIM / zone_count_width; // length of zone (in pixels) along one dimension in
int zone_pixel_count = zone_length * zone_length; // number of pixels in each zone
int x, y;
for (y = 0; y < RESIZED_CHAR_DIM; y++) {
for (x = 0; x < RESIZED_CHAR_DIM; x++) {
int normalized_pix = resized_image[x + y * RESIZED_CHAR_DIM];
int zone_index = (x / zone_length) + (y / zone_length) * zone_count_width;
if (normalized_pix == 0) {
feature_vector[zone_index] += 1.0 / zone_pixel_count; // add the density contribution of a single dark pixel
}
}
}
// free allocated memory
FreeMemory(resized_image);
return feature_vector;
}
// interpolates points from a 2-D grid (used to resize a character image to a standard size)
// qij: value of pixel at x_i, y_j
float BilinearInterpolation(float q11, float q12, float q21, float q22, float x1, float x2, float y1, float y2, float x, float y) {
float x2x1, y2y1, x2x, y2y, yy1, xx1;
x2x1 = x2 - x1;
y2y1 = y2 - y1;
x2x = x2 - x;
y2y = y2 - y;
yy1 = y - y1;
xx1 = x - x1;
return 1.0 / (x2x1 * y2y1) * (
q11 * x2x * y2y +
q21 * xx1 * y2y +
q12 * x2x * yy1 +
q22 * xx1 * yy1
);
}
//resizes a character represented by a binary image to an arbitrary size
//output size is given by parameters output_height and output_width
unsigned char* ResizeCharacter(unsigned char* image, int height, int width, int out_height, int out_width, int doc_width) {
if (out_height == 0 || out_width == 0) return NULL;
unsigned char* output_image = MemAllocate(sizeof(unsigned char) * out_height * out_width);
int x, y;
for (y = 0; y < out_height; y++) {
for (x = 0; x < out_width; x++) {
// get the x and y coordinates of the interpolated point
float x_interp = ((float)x / out_width) * width;
float y_interp = ((float)y / out_height) * height;
int x_source = round(x_interp);
int y_source = round(y_interp);
if (x_source >= width) x_source = width - 1;
if (y_source >= height) y_source = height - 1;
// value of interpolated pixel
int interp_val = image[x_source + y_source * doc_width];
//if (interp_val < 0.5) {
// interp_val = 0;
//}
//else {
// interp_val = 1;
//}
output_image[x + y * out_width] = interp_val;
}
}
return output_image;
}
|
C
|
#include <stdio.h>
void divisione(int dividendo, int divisore, int* pquoz, int* presto) {
*pquoz = dividendo / divisore;
*presto = dividendo % divisore;
}
int main() {
int quoz, resto;
divisione(15, 7, &quoz, &resto);
printf("%d %d\n", quoz, resto);
}
|
C
|
/*
** EPITECH PROJECT, 2020
** hunter
** File description:
** main
*/
#include "include/my.h"
void set_texture(struct_t *hunter)
{
sfSprite_setTexture(hunter->sprite_background,
hunter->texture_background, sfTrue);
sfSprite_setTexture(hunter->sprite_backgroundig,
hunter->texture_backgroundig, sfTrue);
sfSprite_setTexture(hunter->sprite_enemy, hunter->texture_enemy, sfTrue);
sfSprite_setTexture(hunter->sprite_enemy2, hunter->texture_enemy2, sfTrue);
sfSprite_setTexture(hunter->sprite_enemy3, hunter->texture_enemy3, sfTrue);
sfSprite_setTexture(hunter->sprite_healthbar,
hunter->texture_healthbar, sfTrue);
sfSprite_setTexture(hunter->sprite_healthbar2,
hunter->texture_healthbar2, sfTrue);
sfSprite_setTexture(hunter->sprite_healthbar3,
hunter->texture_healthbar3, sfTrue);
sfSprite_setTexture(hunter->sprite_end, hunter->texture_end, sfTrue);
hunter->enemy_animation = (sfIntRect) {0, 0, 350, 260};
hunter->enemy_animation2 = (sfIntRect) {0, 0, 350, 260};
hunter->enemy_animation3 = (sfIntRect) {0, 0, 350, 260};
sfSprite_setTextureRect(hunter->sprite_enemy, hunter->enemy_animation);
sfSprite_setTextureRect(hunter->sprite_enemy2, hunter->enemy_animation2);
sfSprite_setTextureRect(hunter->sprite_enemy3, hunter->enemy_animation3);
}
void event(struct_t *hunter)
{
while (sfRenderWindow_pollEvent(hunter->window, &hunter->event)) {
if (hunter->event.type == sfEvtClosed)
sfRenderWindow_close(hunter->window);
hunter->posx_mouse = hunter->event.mouseButton.x;
hunter->posy_mouse = hunter->event.mouseButton.y;
if (sfKeyboard_isKeyPressed(sfKeyQ))
sfRenderWindow_close(hunter->window);
if (sfMouse_isButtonPressed(sfMouseLeft)) {
if (hunter->posx_mouse >= 789 && hunter->posx_mouse <= 1206 &&
hunter->posy_mouse >= 369 && hunter->posy_mouse <= 469)
hunter->menu = 1;
if (hunter->menu == 0)
if (hunter->posx_mouse >= 691 && hunter->posx_mouse <= 1323 &&
hunter->posy_mouse >= 580 && hunter->posy_mouse <= 946)
sfRenderWindow_close(hunter->window);
}
}
}
void display_menu(struct_t *hunter)
{
sfRenderWindow_display(hunter->window);
sfRenderWindow_drawSprite(hunter->window, hunter->sprite_background, NULL);
}
void call_display_game(struct_t *hunter)
{
sfRenderWindow_display(hunter->window);
sfRenderWindow_drawSprite(hunter->window,
hunter->sprite_backgroundig, NULL);
sfRenderWindow_drawSprite(hunter->window, hunter->sprite_enemy, NULL);
sfRenderWindow_drawSprite(hunter->window, hunter->sprite_enemy2, NULL);
sfRenderWindow_drawSprite(hunter->window, hunter->sprite_enemy3, NULL);
sfSprite_setPosition(hunter->sprite_enemy, hunter->pos_enemy);
sfSprite_setPosition(hunter->sprite_enemy2, hunter->pos_enemy2);
sfSprite_setPosition(hunter->sprite_enemy3, hunter->pos_enemy3);
sfSprite_setPosition(hunter->sprite_healthbar, hunter->pos_healthbar);
sfSprite_setPosition(hunter->sprite_healthbar2, hunter->pos_healthbar2);
sfSprite_setPosition(hunter->sprite_healthbar3, hunter->pos_healthbar3);
if (hunter->vie == 3) {
sfRenderWindow_drawSprite(hunter->window,
hunter->sprite_healthbar, NULL);
sfRenderWindow_drawSprite(hunter->window,
hunter->sprite_healthbar2, NULL);
sfRenderWindow_drawSprite(hunter->window,
hunter->sprite_healthbar3, NULL);
}
}
void display_game(struct_t *hunter)
{
call_display_game(hunter);
if (hunter->vie == 2) {
sfRenderWindow_drawSprite(hunter->window,
hunter->sprite_healthbar, NULL);
sfRenderWindow_drawSprite(hunter->window,
hunter->sprite_healthbar2, NULL);
}
if (hunter->vie == 1) {
sfRenderWindow_drawSprite(hunter->window,
hunter->sprite_healthbar, NULL);
}
if (hunter->vie <= 0) {
sfMusic_stop(hunter->music_background);
hunter->menu = 2;
}
}
|
C
|
#include <stdio.h>
// Returns the month corresponding to its numerical value
// Ex: 1 returns January, 2 returns February, etc.
int main()
{
int monthSelected;
printf("Please enter a number corresponding to a month [1 - Jan, 2 - Feb, etc.]\n");
scanf("%d", &monthSelected);
while(monthSelected < 1 || monthSelected > 12)
{
printf("Please select a valid month number.\n");
scanf("%d", &monthSelected);
}
char* months[12] = {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
printf("You selected %s.\n", months[monthSelected - 1]);
return 0;
}
|
C
|
#ifndef TOYNIX_INC_THREADQ_H
#define TOYNIX_INC_THREADQ_H
#include <thread.h>
#include <setjmp.h>
#include <mmu.h>
#define THREAD_NUM_ONHALT 4
enum {
name_size = 32
};
enum {
stack_size = PGSIZE
};
struct thread_context {
thread_id_t tc_tid;
void *tc_stack_bottom;
char tc_name[name_size];
void (*tc_entry)(uint32_t tc_arg);
uint32_t tc_arg;
struct toynix_jmp_buf tc_jb;
volatile uint32_t *tc_wait_addr;
volatile char tc_wakeup;
void (*tc_onhalt[THREAD_NUM_ONHALT])(thread_id_t);
int tc_nonhalt;
struct thread_context *tc_queue_link;
};
struct thread_queue {
struct thread_context *tq_first;
struct thread_context *tq_last;
};
static inline void
threadq_init(struct thread_queue *tq)
{
tq->tq_first = NULL;
tq->tq_last = NULL;
}
static inline void
threadq_push(struct thread_queue *tq, struct thread_context *tc)
{
tc->tc_queue_link = NULL;
if (!tq->tq_first) {
/* list is empty */
tq->tq_first = tc;
tq->tq_last = tc;
} else {
/* add tail in list */
tq->tq_last->tc_queue_link = tc;
tq->tq_last = tc;
}
}
static inline struct thread_context *
threadq_pop(struct thread_queue *tq)
{
struct thread_context *tc = tq->tq_first;
if (!tc)
return NULL;
tq->tq_first = tc->tc_queue_link;
tc->tc_queue_link = NULL;
return tc;
}
#endif
|
C
|
/*=====[Module Name]===========================================================
* Copyright 2019 Gambarotta Martin Abel <magambarotta@mail.com>
* All rights reserved.
* License: license text or at least name and link
(example: BSD-3-Clause <https://opensource.org/licenses/BSD-3-Clause>)
*
* Version: 1.0.0
* Creation Date: 2019/04/22
*/
/*=====[Inclusion of own header]=============================================*/
#include "../../../cese_pdm/ejercicio6/inc/uartMenuMEF.h"
#include <sapi.h>
#include "../../../cese_pdm/ejercicio6/inc/motorMEF.h"
/*=====[Inclusions of private function dependencies]=========================*/
/*=====[Definition macros of private constants]==============================*/
/*=====[Private function-like macros]========================================*/
/*=====[Definitions of private data types]===================================*/
/*=====[Definitions of external public global variables]=====================*/
/*=====[Definitions of public global variables]==============================*/
/*=====[Definitions of private global variables]=============================*/
uartMenu_t menu;
uint8_t byteIngresadoMenu;
uint8_t byteIngresoVelocidad;
volatile uint16_t lectura_adc = 0;
/*=====[Prototypes (declarations) of private functions]======================*/
static void clearScreen(void);
static char* itoa(int, char*, int);
void showDateAndTime(rtc_t * rtc);
/*=====[Implementations of public functions]=================================*/
void uartMenuInit(void) {
menu = MENU_PRINCIPAL;
}
void uartMenuUpdate(motor_t * motor, rtc_t* rtc) {
static char uartBuff[5];
int num;
clearScreen();
switch (menu) {
case MENU_PRINCIPAL:
//Muestra Velocidad
uartWriteString(UART_USB, "Velocidad(rpm): ");
itoa(motor->velocidad, uartBuff, 10); /* 10 => BASE 10 Decimal */
uartWriteString(UART_USB, uartBuff);
uartWriteString(UART_USB, "/");
lectura_adc = adcRead(CH1);
itoa(lectura_adc, uartBuff, 10);
uartWriteString(UART_USB, uartBuff);
uartWriteString(UART_USB, "\r\n");
//Muestra Estado del Motor (ENCENDIDO-APAGADO)
uartWriteString(UART_USB, "Estado Motor: ");
if (motor->estado)
uartWriteString(UART_USB, "APAGADO\r\n");
else
uartWriteString(UART_USB, "ENCENDIDO\r\n");
//Muestra Fecha
uartWriteString(UART_USB, "Fecha: ");
rtcRead(rtc);
showDateAndTime(rtc);
uartWriteString(UART_USB, "\r\n");
uartWriteString(UART_USB, "Ingrese [1] para setear Velocidad\r\n");
uartWriteString(UART_USB, "Ingrese [2] para setear Fecha\r\n");
uartWriteString(UART_USB,
"Presione [TEC1] para Encender|Apagar Motor\r\n");
if (uartReadByte(UART_USB, &byteIngresadoMenu)) {
switch (byteIngresadoMenu) {
case '1':
menu = MENU_CONF_VELOCIDAD;
break;
case '2':
menu = MENU_CONF_FECHA;
break;
default:
uartWriteString(UART_USB,
"Ingreso una configuración de menu incorrecta.\r\n");
break;
}
}
break;
case MENU_CONF_VELOCIDAD:
uartWriteString(UART_USB, "[ESC] para volver al menu principal\r\n");
uartWriteString(UART_USB, "Velocidad(0-3000 rpm): ");
itoa(motor->velocidad, uartBuff, 10); /* 10 => BASE 10 Decimal */
uartWriteString(UART_USB, uartBuff);
if (uartReadByte(UART_USB, &byteIngresadoMenu)) {
if (byteIngresadoMenu != 27 & byteIngresadoMenu != '\n') {
motor->velocidad = byteIngresadoMenu - 48;
}
if (byteIngresadoMenu == 27) {
menu = MENU_PRINCIPAL;
}
}
break;
case MENU_CONF_FECHA:
uartWriteString(UART_USB, "[ESC] para volver al menu principal\r\n");
uartWriteString(UART_USB, "Fecha: ");
rtcRead(rtc);
showDateAndTime(rtc);
if (uartReadByte(UART_USB, &byteIngresadoMenu)) {
if (byteIngresadoMenu == 27) {
menu = MENU_PRINCIPAL;
}
}
break;
default:
menu = MENU_PRINCIPAL;
}
}
/*=====[Implementations of interrupt functions]==============================*/
/*=====[Implementations of private functions]================================*/
static void clearScreen(void) {
uartWriteByte(UART_USB, 27);
uartWriteString(UART_USB, "[2J");
uartWriteByte(UART_USB, 27);
uartWriteString(UART_USB, "[H");
delay(1);
}
static char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) {
*result = '\0';
return result;
}
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ =
"zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz"[35
+ (tmp_value - value * base)];
} while (value);
// Apply negative sign
if (tmp_value < 0)
*ptr++ = '-';
*ptr-- = '\0';
while (ptr1 < ptr) {
tmp_char = *ptr;
*ptr-- = *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
/* Enviar fecha y hora en formato "DD/MM/YYYY, HH:MM:SS" */
void showDateAndTime(rtc_t * rtc) {
static char uartBuff[10];
/* Conversion de entero a ascii con base decimal */
itoa((int) (rtc->mday), (char*) uartBuff, 10); /* 10 significa decimal */
/* Envio el dia */
if ((rtc->mday) < 10)
uartWriteByte(UART_USB, '0');
uartWriteString(UART_USB, uartBuff);
uartWriteByte(UART_USB, '/');
/* Conversion de entero a ascii con base decimal */
itoa((int) (rtc->month), (char*) uartBuff, 10); /* 10 significa decimal */
/* Envio el mes */
if ((rtc->month) < 10)
uartWriteByte(UART_USB, '0');
uartWriteString(UART_USB, uartBuff);
uartWriteByte(UART_USB, '/');
/* Conversion de entero a ascii con base decimal */
itoa((int) (rtc->year), (char*) uartBuff, 10); /* 10 significa decimal */
/* Envio el año */
if ((rtc->year) < 10)
uartWriteByte(UART_USB, '0');
uartWriteString(UART_USB, uartBuff);
uartWriteString(UART_USB, ", ");
/* Conversion de entero a ascii con base decimal */
itoa((int) (rtc->hour), (char*) uartBuff, 10); /* 10 significa decimal */
/* Envio la hora */
if ((rtc->hour) < 10)
uartWriteByte(UART_USB, '0');
uartWriteString(UART_USB, uartBuff);
uartWriteByte(UART_USB, ':');
/* Conversion de entero a ascii con base decimal */
itoa((int) (rtc->min), (char*) uartBuff, 10); /* 10 significa decimal */
/* Envio los minutos */
// uartBuff[2] = 0; /* NULL */
if ((rtc->min) < 10)
uartWriteByte(UART_USB, '0');
uartWriteString(UART_USB, uartBuff);
uartWriteByte(UART_USB, ':');
/* Conversion de entero a ascii con base decimal */
itoa((int) (rtc->sec), (char*) uartBuff, 10); /* 10 significa decimal */
/* Envio los segundos */
if ((rtc->sec) < 10)
uartWriteByte(UART_USB, '0');
uartWriteString(UART_USB, uartBuff);
/* Envio un 'enter' */
uartWriteString(UART_USB, "\r\n");
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
bool hoanThien(unsigned int n)
{
if(n == 1)
return false;
unsigned int t = 1;
unsigned int moc = sqrt(n);
for (; moc > 1; moc--)
if (!(n % moc))
t += moc + n / moc;
return n == t;
}
int main()
{
unsigned int n;
printf("Nhap so : ");
scanf("%u", &n);
if (hoanThien(n))
printf("La so hoan thien");
else
printf("Khong phai la so khong hoan thien");
return 0;
}
|
C
|
#include "TM4C123GH6PM.h"
#include <stdint.h>
#include <stdio.h>
//Declare a function for millisecond delay
void delayMs(int n);
int main(void)
{
//declare an integer for storing the ADC value
volatile int ADC_VAL;
//declare a float for storing the converted ADC value in RPM
volatile float RPM;
//declare a constant float for storing RPM step size = 4095.0/2500
const float y = 4095.0/2500.0;
//Step 1. enable clock for GPIOD for the configuration of
//AIN6 (RCGCGPIO p340)
SYSCTL->RCGCGPIO |= 0x08;
//Step 2. enable the clock to ADC6(RCGCADC p352)
SYSCTL->RCGCADC |= 0x01; //generally used
/*initialise PD1 for AIN6 input*/
//step3. enable alternate function for GPIOD pin 0 (GPIOAFSEL p675)
GPIOD->AFSEL |= 0x02;
//step 4. disable digital function for GPIOD Pin 1 (GPIODEN p683)
GPIOD->DEN &= ~0x02;
//sep5. enable analog function for GPIOD pin1 (GPIOAMSEL p687)
GPIOD -> AMSEL |= 0x02;
//step6. disable SS3 during configuration (ADCACTSS p821)
//this is for sample sequencer 3 according to the question
ADC0->ACTSS &= ~0x08;
//step7. configure ADC for a software trigger
//or continuous sampling (ADCEMUX p833)
ADC0-> EMUX |= 0xF000;
//step8. get input from channel 6 (AIN6) PD1 (ADCSSMUX2 p875/p801)
//input is gotten from the input number on the table
ADC0-> SSMUX3 |= 0x6;
//step 9. take one sample at a time, set flag at ist sample (ADCSSCTL3 p876)
ADC0->SSCTL3 |= 0x6;
//step 10. enable ADC0 sequencer 3 (ADCACTSS p821)
ADC0->ACTSS |= 0x08;
while(1)
{
//step 11a. start a conversion sequence on SS3 (ADCPSSI p845)
ADC0->PSSI |= 0x08;
//step11b. wait for conversion complete by polling the correct
//bit 3 (SS3 interrupt bit) of ADCRIS register (p823)
while((ADC0->RIS & 8)==0);
//step 11c. read the conversion result and store (SSFIFO3 p828)
ADC_VAL = ADC0->SSFIFO3;
//step 11d. clear the ADC SS3 interrupt flag (ADCISC bit 3 p828)
ADC0->ISC = 0x00;
//step 11e. wait 1 second before starting loop again
//and taking another reading.
//delayMs(100);
RPM = ADC_VAL/y;
delayMs(500);
}
}
void delayMs(int n)
{
int i, j;
for (i=0; i<n; i++)
for (j=0;j<8300;j++)
{
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100
int Inverse(char str1[], char str2[][N]);
int main()
{
char str1[N],str2[N][N],ch;
int j,i;
printf("Input a sentence:");
gets(str1);
ch=str1[strlen(str1)-1];
str1[strlen(str1)-1]='\0';
j=Inverse(str1,str2);
for(i=j;i>0;i--)
{
printf("%s ",str2[i]);
}
printf("%s%c\n",str2[i],ch);
}
int Inverse(char str1[], char str2[][N])
{
int i=0,j=0,k=0;
while(str1[i]!=0)
{
k=0;
while(str1[i]!=' '&&str1[i]!='\0')
{
str2[j][k]=str1[i];
k++;
i++;
}
str2[j][k]='\0';
if(str1[i]=='\0')
break;
i++;
j++;
}
return j;
}
|
C
|
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int squirrels = get_int("How many squirrels do you have? ");
if (squirrels > 10)
{
printf("That's really too many squirrels.\n");
}
else if (squirrels < 0)
{
printf("That's too few squirrels.\n");
}
else
{
printf("That's a good number of squirrels!\n");
}
/*
How would we modify this program to tell us, more simply, whether we
have a good number of squirrels or not?
Conditional (or "Relational") operators:
Less than: <
Greater than: >
Equal to: =
Less than or equal to: <=
Greater than or equal to: >=
Logical operators:
And: && (Returns true if both of two conditions are true)
Or: || (Return true if one of two conditions are true)
Not: ! (Place in front of a condition to negate it, e.g. "!=" for not equal)
*/
squirrels = get_int("No really, how many squirrels do you have? ");
// Write your if statement and condition below!
}
|
C
|
int i;
static int j;
int k = 1;
static int l = 2;
int a[4];
static int b[4];
int c[4] = {1, 2, 3, 4};
static int d[4] = {5, 6, 7, 8};;
void tricky(int x, int y)
{
b[0] = j = i+a[0]+x;
d[0] = l = k+c[0]+y;
}
|
C
|
//floyd ˰
#include <stdio.h>
#include <limits.h>
#define TRUE 1
#define FALSE 0
#define VERTICES 7 /* */
#define INF 10000 /* Ѵ ( ) */
/* */
int weight[VERTICES][VERTICES]={
{ 0, 7, INF, 5, INF, INF, INF },
{ 7, 0, 8, 9, 7, INF, INF },
{ INF, 8, 0, INF, 5, INF, INF },
{ 5, 9, INF, 0, 15, 6, INF },
{ INF, 7, 5, 15, 0, 8, 9 },
{ INF, INF, INF, 6, 8, 0, 11 },
{ INF, INF, INF, INF, 9, 11, 0 }};
int A[VERTICES][VERTICES];
int B[VERTICES][VERTICES];
void printA(int n)
{ int i, j, k;
printf("===============================\n");
for(i=0; i<n; i++){
for(j=0; j<n; j++){
if( A[i][j] == INF )
printf("INF ");
else printf("%3d ", A[i][j]);
}
printf("\n");
}
printf("===============================\n");
}
void print_path(int (*P)[VERTICES], int q, int r){
if(P[q][r]!=-1){
print_path(P, q, P[q][r]);
printf("%c->", P[q][r]+65);
print_path(P, P[q][r], r);
}
}
void floyd(int n)
{ int i, j, k;
for(i=0; i<n ;i++){
for(j=0; j<n ;j++)
B[i][j]=-1;
}
for(i=0; i<n; i++)
for(j=0; j<n; j++)
A[i][j]=weight[i][j];
for(k=0; k<n; k++){
printA(n);
for(i=0; i<n; i++)
for(j=0; j<n; j++)
if (A[i][k]+A[k][j] < A[i][j]){
A[i][j] = A[i][k]+A[k][j];
B[i][j] = k;
printf("(%c, %c) %c->", i+65, j+65, i+65);
print_path(B, i, j);
printf("%c", j+65);
printf("\n");
}
}
}
main()
{
printf("\n <Floyd ˰> \n");
printf("\n ");
floyd(VERTICES);
}
|
C
|
#include "HD44780.h"
void WriteNibble(unsigned char nibbleToWrite)
{
LCD_PORT |= 1<<EN;
LCD_PORT = (LCD_PORT & 0xf0) | (nibbleToWrite & 0x0f);
LCD_PORT &= ~(1<<EN);
}
void WriteByte(unsigned char dataToWrite)
{
WriteNibble(dataToWrite >> 4);
WriteNibble(dataToWrite & 0x0f);
}
void LCD_Command(unsigned char cmd)
{
LCD_PORT &= ~(1<<RS);
WriteByte(cmd);
};
void LCD_Text(char * text)
{
LCD_PORT |= 1<<RS;
WriteByte(text);
};
void LCD_GoToXY(unsigned char x, unsigned char y)
{
};
void LCD_Clear()
{
LCD_Command(1);
};
void LCD_Home()
{
LCD_Command(2);
};
void LCD_Initalize()
{
_delay_ms(50);
int i;
for(i=0;i<3;i++)
{
WriteNibble(0x03);
_delay_ms(5);
}
_delay_ms(5);
WriteNibble(0x02); //set data size
_delay_ms(0x02);
LCD_Command(0x28); //display settings
_delay_ms(2);
LCD_Command(0x08);
_delay_ms(2);
LCD_Command(0x01);
_delay_ms(3);
LCD_Command(0x04);
_delay_ms(1);
LCD_Command(0x0f);
_delay_ms(1);
};
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<errno.h>
#include<string.h>
char ** get_args(int * length)
{
char ** args = calloc(100,sizeof(char *));
char * bigword = calloc(1000, 1);
int _low, EOFind;
args[0] = bigword;
*length = 1;
for(_low = 0; ((EOFind = getchar()) != '\n') && (EOFind != EOF); _low++)
{
bigword[_low] = EOFind;
if(bigword[_low] == ' ' && bigword[_low-1] == ' ')
_low--;
if(bigword[_low] == ' ' && bigword[_low-1] == '|')
_low--;
if(bigword[_low] == '|' && bigword[_low-1] == '|')
{
printf("You have | too times\n");
return 0;
}
}
for(int i = 0; i < _low+1; i++)
{
if (bigword[i] == '|')
{
bigword[i++] = '\0';
args[*length] = bigword+i;
*length = *length+1;
}
if (bigword[i] == '\n')
bigword[i] = '\0';
}
if(strcmp(args[0], "exit") == 0 && *length == 1)
exit(-1);
if(EOFind == EOF)
{
putchar('\n');
exit(-1);
}
return args;
}
void free_args(char ** args)
{
free(args[0]);
free(args);
}
int main()
{
while(1)
{
printf("@@@@####--$> ");
int length;
char ** args = get_args(&length);
if(args == NULL)
continue;
int fld[2], oldfld = -1;
for(int i = 0; i < length; i++)
{
pipe(fld);
int fk = fork();
if(fk == -1)
{
perror(strerror(errno));
return 0;
}
if(fk == 0)
{
close(fld[0]);
if (i != 0)
{
close(0);
dup(oldfld);
close(oldfld);
}
if (i != length-1)
{
close(1);
dup(fld[1]);
close(fld[1]);
}
int l = 1;
char ** new_args = calloc(100,sizeof(char *));
new_args[0] = args[i];
for(int j = 0; args[i][j] != '\0'; j++)
if (args[i][j] == ' ')
{
new_args[l++] = args[i]+j+1;
args[i][j++] = '\0';
}
execvp(new_args[0], new_args);
perror(strerror(errno));
return 0;
}
else
{
if(oldfld != -1)
close(oldfld);
oldfld = fld[0];
close(fld[1]);
}
}
for(int i = 0; i < length; i++)
wait(0);
free_args(args);
}
return 0;
}
|
C
|
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int get_system_entropy(void* buf, unsigned int length) {
// TODO: ideally we should use getentropy from sys/random.h if it's
// available.
int file = open("/dev/urandom", O_RDONLY);
int read_bytes = read(file, buf, length);
close(file);
if(read_bytes < length) return -1;
else return 0;
}
|
C
|
#include "ir.h"
#include "node.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#define DEBUG(x)
int var_total=0;
int temp_total=0;
int label_total=0;
int struct_error=0;
ListHead code;
void translate_compst(Node* node);
void translate_exp(Node* node,Operand* temp);
Operand new_op(){
Operand newop=malloc(sizeof(struct Operand_));
memset(newop,0,sizeof(struct Operand_));
return newop;
}
InterCode new_intercode(){
InterCode newinter=malloc(sizeof(struct InterCode_));
memset(newinter,0,sizeof(struct InterCode_));
return newinter;
}
void print_single_intercode(InterCode intercode,FILE* file)
{
DEBUG(printf("%s: %p %d\n",__FUNCTION__,intercode,intercode->kind);)
switch (intercode->kind){
case DEF_LABEL_I:{
fprintf(file,"LABEL %s :\n",intercode->u.one_op->name);
break;
}
case DEF_FUN_I:{
fprintf(file,"FUNCTION %s :\n",intercode->u.one_op->u.funname);
break;
}
case GOTO_I:{
fprintf(file,"GOTO %s\n",intercode->u.one_op->name);
break;
}
case RETURN_I:{
fprintf(file,"RETURN %s\n",intercode->u.one_op->name);
break;
}
case ARG_I:{
fprintf(file,"ARG %s\n",intercode->u.one_op->name);
break;
}
case PARAM_I:{
fprintf(file,"PARAM %s\n",intercode->u.one_op->name);
break;
}
case READ_I:{
fprintf(file,"READ %s\n",intercode->u.one_op->name);
break;
}
case WRITE_I:{
fprintf(file,"WRITE %s\n",intercode->u.one_op->name);
break;
}
case ASSIGN_I:{
fprintf(file,"%s := %s\n",intercode->u.two_op.op1->name,intercode->u.two_op.op2->name);
break;
}
case ASSIGN_ADDR_I:{
fprintf(file,"%s := &%s\n",intercode->u.two_op.op1->name,intercode->u.two_op.op2->name);
break;
}
case ASSIGN_MEM_I:{
fprintf(file,"%s := *%s\n",intercode->u.two_op.op1->name,intercode->u.two_op.op2->name);
break;
}
case MEM_ASSIGN_I:{
fprintf(file,"*%s := %s\n",intercode->u.two_op.op1->name,intercode->u.two_op.op2->name);
break;
}
case DEC_SIZE_I:{
fprintf(file,"DEC %s %s\n",intercode->u.two_op.op1->name,intercode->u.two_op.op2->name+1);
break;
}
case ASSIGN_CALL_I:{
fprintf(file,"%s := CALL %s\n",intercode->u.two_op.op1->name,intercode->u.two_op.op2->name);
break;
}
case PLUS_I:{
fprintf(file,"%s := %s + %s\n",intercode->u.three_op.op1->name,intercode->u.three_op.op2->name,intercode->u.three_op.op3->name);
break;
}
case MINUS_I:{
fprintf(file,"%s := %s - %s\n",intercode->u.three_op.op1->name,intercode->u.three_op.op2->name,intercode->u.three_op.op3->name);
break;
}
case STAR_I:{
fprintf(file,"%s := %s * %s\n",intercode->u.three_op.op1->name,intercode->u.three_op.op2->name,intercode->u.three_op.op3->name);
break;
}
case DIV_I:{
fprintf(file,"%s := %s / %s\n",intercode->u.three_op.op1->name,intercode->u.three_op.op2->name,intercode->u.three_op.op3->name);
break;
}
case COND_I:{
//fprintf(file,"IF %x GOTO ")
fprintf(file,"IF %s %s %s GOTO %s\n",intercode->u.if_op.op1->name,intercode->u.if_op.relop,intercode->u.if_op.op2->name,intercode->u.if_op.op3->name);
break;
}
default:{
break;
}
}
}
Operand con_oper(int kind,...){
Operand newop=new_op();
newop->kind=kind;
va_list arg;va_start(arg,kind);
if (kind<=1){
newop->u.int_value=va_arg(arg,int);
sprintf(newop->name,"#%d",newop->u.int_value);
}
else if (kind==FUNCTION){
char* temp=va_arg(arg,char*);
strcpy(newop->u.funname,temp);
strcpy(newop->name,temp);
}
else if (kind==LABEL){
newop->u.var_no=va_arg(arg,int);
strcpy(newop->name,"l");
sprintf(newop->name+1,"%d",newop->u.var_no);
}
else if (kind==ADDRESS){
newop->u.var_no=va_arg(arg,int);
strcpy(newop->name,"&");
strcpy(newop->name+1,"t");
sprintf(newop->name+2,"%d",newop->u.var_no);
}
else {
newop->u.var_no=va_arg(arg,int);
strcpy(newop->name,"t");
sprintf(newop->name+1,"%d",newop->u.var_no);
}
va_end(arg);
return newop;
}
InterCode con_inter(int kind,...)
{
InterCode newcode=new_intercode();
newcode->kind=kind;
va_list arg;va_start(arg,kind);
if (kind<=WRITE_I){
newcode->u.one_op=va_arg(arg,Operand);
}
else if (kind<=ASSIGN_I){
newcode->u.two_op.op1=va_arg(arg,Operand);
newcode->u.two_op.op2=va_arg(arg,Operand);
}
else if (kind<=DIV_I){
newcode->u.three_op.op1=va_arg(arg,Operand);
newcode->u.three_op.op2=va_arg(arg,Operand);
newcode->u.three_op.op3=va_arg(arg,Operand);
}
else {
newcode->u.if_op.op1=va_arg(arg,Operand);
newcode->u.if_op.op2=va_arg(arg,Operand);
newcode->u.if_op.op3=va_arg(arg,Operand);
char * temp=va_arg(arg,char*);
strcpy(newcode->u.if_op.relop,temp);
}
va_end(arg);
return newcode;
}
void print_intercode(FILE* file)
{
ListHead* p;
list_foreach(p,&code)
{
InterCode temp=list_entry(p,struct InterCode_,list);
print_single_intercode(temp,file);
}
}
Operand getvar(Node* node){
DEBUG(printf("%s:%s %d %d\n",__FUNCTION__,node->content,node->line,node->cnt);)
while (strncmp(node->content,"ID: ",4)!=0) node=node->next[0];
assert(node!=NULL);
FieldList field=returnvar(node->content+4);
char temp[31];memset(temp,0,sizeof(temp));
if (field->var_no==0)
field->var_no=++temp_total;
sprintf(temp,"%d",field->var_no);
Operand op=con_oper(VARIABLE,field->var_no);
return op;
}
void translate_cond(Node* node,Operand op1,Operand op2){
if (node->cnt==2){
if (strcmp(node->next[0]->content,"NOT")==0)
{
translate_cond(node->next[1],op2,op1);
return ;
}
}
else if (node->cnt==3&&strcmp(node->next[1]->content,"AND")==0){
Operand op_l= con_oper(LABEL,++label_total);
InterCode intercode = con_inter(DEF_LABEL_I,op_l);
translate_cond(node->next[0],op_l,op2);
list_add_before(&code,&intercode->list);
translate_cond(node->next[2],op1,op2);
}
else if (node->cnt==3&&strcmp(node->next[1]->content,"OR")==0){
Operand op_l= con_oper(LABEL,++label_total);
InterCode intercode = con_inter(DEF_LABEL_I,op_l);
translate_cond(node->next[0],op_l,op2);
list_add_before(&code,&intercode->list);
translate_cond(node->next[2],op1,op2);
}
else if (node->cnt==3&&strcmp(node->next[1]->content,"RELOP")==0){
Operand opn1=con_oper(TEMP,++temp_total);
Operand opn2=con_oper(TEMP,++temp_total);
translate_exp(node->next[0],&opn1);
translate_exp(node->next[2],&opn2);
InterCode intercode1=con_inter(COND_I,opn1,opn2,op1,node->next[1]->relop);
InterCode intercode2=con_inter(GOTO_I,op2);
list_add_before(&code,&intercode1->list);
list_add_before(&code,&intercode2->list);
}
else {
Operand temp=con_oper(TEMP,++temp_total);
translate_exp(node,&temp);
Operand zero=con_oper(CONSTANT,0);
InterCode code0=con_inter(COND_I,temp,op1,zero,"!=");
InterCode code1=con_inter(GOTO_I,op2);
list_add_before(&code,&code0->list);
list_add_before(&code,&code1->list);
}
}
void condition(Node* node,Operand op){
Operand op_l1=con_oper(LABEL,++label_total);
Operand op_l2=con_oper(LABEL,++label_total);
Operand zero=con_oper(CONSTANT,0);
Operand one=con_oper(CONSTANT,1);
InterCode code1=con_inter(ASSIGN_I,op,zero);
list_add_before(&code,&code1->list);
translate_cond(node,op_l1,op_l2);
InterCode code2=con_inter(DEF_LABEL_I,op_l1);
InterCode code3=con_inter(ASSIGN_I,op,one);
InterCode code4=con_inter(DEF_LABEL_I,op_l2);
list_add_before(&code,&code2->list);
list_add_before(&code,&code3->list);
list_add_before(&code,&code4->list);
}
int array_len(Node* node){
int array=4;
int depth=0;
while (node->cnt!=1)
{
depth++;node=node->next[0];
}
FieldList temp=returnvar(node->next[0]->content+4);
Type type=temp->type;
DEBUG(printf("depth %d\n",depth);)
while (depth){
depth--;
type=type->u.array.elem;
}
while (type->kind==ARRAY)
{
type=type->u.array.elem;
if (type->kind==ARRAY)
array=array*(temp->type->u.array.size);
}
return array;
}
void translate_array(Node* node,Operand op){
DEBUG(printf("%s:%s %d %d\n",__FUNCTION__,node->content,node->line,node->cnt);)
int len=array_len(node->next[0]);
DEBUG(printf("%s:%s %d\n",__FUNCTION__,"array_len",len);)
Operand lens=con_oper(CONSTANT,len);
Operand op1=con_oper(TEMP,++temp_total);
Operand offset=con_oper(TEMP,++temp_total);
translate_exp(node->next[2],&op1);
InterCode code1=con_inter(STAR_I,offset,op1,lens);
list_add_before(&code,&code1->list);
if (node->next[0]->cnt==1)
{
FieldList var=returnvar(node->next[0]->next[0]->content+4);
assert(var!=NULL);
if (var->isparam==0)
{
Operand addr=con_oper(ADDRESS,var->var_no);
InterCode intercode=con_inter(PLUS_I,op,addr,offset);
list_add_before(&code,&intercode->list);
}
else
{
Operand array=con_oper(VARIABLE,var->var_no);
InterCode intercode=con_inter(PLUS_I,op,array,offset);
list_add_before(&code,&intercode->list);
}
}
else
{
Operand op2=con_oper(TEMP,++temp_total);
translate_array(node->next[0],op2);
InterCode intercode=con_inter(PLUS_I,op,op2,offset);
list_add_before(&code,&intercode->list);
}
}
void translate_args(Node* node,ListHead* head){
assert(node!=NULL);
DEBUG(printf("%s:%s %d %d\n",__FUNCTION__,node->content,node->line,node->cnt);)
if (node->cnt==1)
{
Operand temp=con_oper(TEMP,++temp_total);
translate_exp(node->next[0],&temp);
if (node->next[0]->cnt==1)
{
if (node->next[0]->next[0]->number==0)
{
FieldList var=returnvar(node->next[0]->next[0]->content+4);
if (var->type->kind==ARRAY)
{
Operand addr=con_oper(ADDRESS,temp->u.int_value);
list_add_after(head,&addr->arg_list);
return ;
}
}
}
list_add_after(head,&temp->arg_list);
}
else
{
Operand temp=con_oper(TEMP,++temp_total);
translate_exp(node->next[0],&temp);
Node* tempnode=node->next[0];
if (tempnode->next[0]->cnt==1)
{
FieldList var=returnvar(tempnode->next[0]->next[0]->content+4);
if (var->type->kind==ARRAY)
{
Operand addr=con_oper(ADDRESS,temp->u.int_value);
list_add_after(head,&addr->arg_list);
return ;
}
}
list_add_after(head,&temp->arg_list);
translate_args(node->next[2],head);
}
}
void translate_exp(Node* node,Operand* temp){
DEBUG(printf("%s:%s %d %d\n",__FUNCTION__,node->content,node->line,node->cnt);)
Operand nowop=NULL;
if (temp!=NULL) nowop=*temp;
else nowop=con_oper(TEMP,++temp_total);
if (node->cnt==1){
if (node->next[0]->number==0)
{
Operand varop=getvar(node->next[0]);
*temp=varop;
}
else if (node->next[0]->number==1)
{
Operand con_var=con_oper(CONSTANT,node->next[0]->type_int);
*temp=con_var;
}
}
else if (node->cnt==2)
{
Operand op_tmp =con_oper(TEMP,++temp_total);
translate_exp(node->next[1],&op_tmp);
Operand zero = con_oper(CONSTANT,0);
InterCode minuscode = con_inter(MINUS_I,nowop,zero,op_tmp);
list_add_before(&code,&minuscode->list);
}
else if (node->cnt==3)
{
InterCode intercode=NULL;
if (strcmp(node->next[1]->content,"RELOP")==0
||strcmp(node->next[1]->content,"AND")==0
||strcmp(node->next[1]->content,"OR")==0)
{
condition(node,nowop);
}
else if (strcmp(node->next[1]->content,"ASSIGNOP")==0){
Operand op_temp=con_oper(TEMP,++temp_total);
translate_exp(node->next[2],&op_temp);
if (node->next[0]->cnt==1)
{
Operand var=getvar(node->next[0]);
InterCode code1=con_inter(ASSIGN_I,var,op_temp);
InterCode code2=con_inter(ASSIGN_I,nowop,var);
list_add_before(&code,&code1->list);
list_add_before(&code,&code2->list);
}
else {
Operand op1=con_oper(TEMP,++temp_total);
translate_array(node->next[0],op1);
InterCode code1=con_inter(MEM_ASSIGN_I,op1,op_temp);
InterCode code2=con_inter(ASSIGN_MEM_I,nowop,op1);
list_add_before(&code,&code1->list);
list_add_before(&code,&code2->list);
}
}
else if (strcmp(node->next[1]->content,"PLUS")==0){
Operand op1=con_oper(TEMP,++temp_total);
Operand op2=con_oper(TEMP,++temp_total);
translate_exp(node->next[0],&op1);
translate_exp(node->next[2],&op2);
intercode=con_inter(PLUS_I,nowop,op1,op2);
list_add_before(&code,&intercode->list);
}
else if (strcmp(node->next[1]->content,"MINUS")==0){
Operand op1=con_oper(TEMP,++temp_total);
Operand op2=con_oper(TEMP,++temp_total);
translate_exp(node->next[0],&op1);
translate_exp(node->next[2],&op2);
intercode=con_inter(MINUS_I,nowop,op1,op2);
list_add_before(&code,&intercode->list);
}
else if (strcmp(node->next[1]->content,"STAR")==0){
Operand op1=con_oper(TEMP,++temp_total);
Operand op2=con_oper(TEMP,++temp_total);
translate_exp(node->next[0],&op1);
translate_exp(node->next[2],&op2);
intercode=con_inter(STAR_I,nowop,op1,op2);
list_add_before(&code,&intercode->list);
}
else if (strcmp(node->next[1]->content,"DIV")==0){
Operand op1=con_oper(TEMP,++temp_total);
Operand op2=con_oper(TEMP,++temp_total);
translate_exp(node->next[0],&op1);
translate_exp(node->next[2],&op2);
intercode=con_inter(DIV_I,nowop,op1,op2);
list_add_before(&code,&intercode->list);
}
else if (strcmp(node->next[1]->content,"LP")==0){
if (strcmp(node->next[0]->content+4,"read")==0){
intercode=con_inter(READ_I,nowop);
}
else{
FuncList temp=returnfun(node->next[0]->content+4);
Operand fun=con_oper(FUNCTION,temp->name);
intercode=con_inter(ASSIGN_CALL_I,nowop,fun);
}
list_add_before(&code,&intercode->list);
}
else if (strcmp(node->next[1]->content,"DOT")==0){
//TODO Struct
struct_error=1;
printf("%s\n","Cannot translate: Code contains variables or parameters of structure type.");
exit(0);
}
else if (strcmp(node->next[0]->content,"LP")==0){
translate_exp(node->next[1],&nowop);
}
}
else if (node->cnt==4)
{
if (strcmp(node->next[1]->content,"LB")==0)
{
Operand addressop=con_oper(TEMP,++temp_total);
translate_array(node,addressop);
InterCode intercode=con_inter(ASSIGN_MEM_I,nowop,addressop);
list_add_before(&code,&intercode->list);
}
else if (strcmp(node->next[2]->content,"Args")==0)
{
FuncList temp=returnfun(node->next[0]->content+4);
ListHead arg_list;
list_init(&arg_list);
translate_args(node->next[2],&arg_list);
if (strcmp(temp->name,"write")==0)
{
InterCode intercode=con_inter(WRITE_I,list_entry(arg_list.next,struct Operand_,arg_list));
list_add_before(&code,&intercode->list);
}
else
{
ListHead* ptr;
list_foreach(ptr,&arg_list){
InterCode intercode=con_inter(ARG_I,list_entry(ptr,struct Operand_,arg_list));
list_add_before(&code,&intercode->list);
}
Operand func=con_oper(FUNCTION,temp->name);
InterCode intercode=con_inter(ASSIGN_CALL_I,nowop,func);
list_add_before(&code,&intercode->list);
}
}
}
}
void translate_stmt(Node* node){
assert(node!=NULL);
DEBUG(printf("%s:%s %d %d\n",__FUNCTION__,node->content,node->line,node->cnt);)
if (strcmp(node->next[0]->content,"CompSt")==0) //CompSt
{
translate_compst(node->next[0]);
}
else if (node->cnt>=2&&strcmp(node->next[1]->content,"SEMI")==0) //Exp SEMI
{
translate_exp(node->next[0],NULL);
}
else if (node->cnt>=3&&strcmp(node->next[0]->content,"RETURN")==0){ //RETURN Exp SEMI;
Operand temp=con_oper(TEMP,++temp_total);
translate_exp(node->next[1],&temp);
InterCode intercode=con_inter(RETURN_I,temp);
list_add_before(&code,&intercode->list);
}
else if (strcmp(node->next[0]->content,"WHILE")==0)//WHILE LP EXP RP Stmt
{
Operand op1=con_oper(LABEL,++label_total);
Operand op2=con_oper(LABEL,++label_total);
Operand op3=con_oper(LABEL,++label_total);
InterCode intercode1=con_inter(GOTO_I,op1);
InterCode intercode2=con_inter(DEF_LABEL_I,op1);
InterCode intercode3=con_inter(DEF_LABEL_I,op2);
InterCode intercode4=con_inter(DEF_LABEL_I,op3);
list_add_before(&code,&intercode2->list);
translate_cond(node->next[2],op2,op3);
list_add_before(&code,&intercode3->list);
translate_stmt(node->next[4]);
list_add_before(&code,&intercode1->list);
list_add_before(&code,&intercode4->list);
}
else if (node->cnt>=7){ //IF ELSE
Operand op1=con_oper(LABEL,++label_total);
Operand op2=con_oper(LABEL,++label_total);
Operand op3=con_oper(LABEL,++label_total);
InterCode code1=con_inter(GOTO_I,op3);
InterCode code2=con_inter(DEF_LABEL_I,op1);
InterCode code3=con_inter(DEF_LABEL_I,op2);
InterCode code4=con_inter(DEF_LABEL_I,op3);
translate_cond(node->next[2],op1,op2);
list_add_before(&code,&code2->list);
translate_stmt(node->next[4]);
list_add_before(&code,&code1->list);
list_add_before(&code,&code3->list);
translate_stmt(node->next[6]);
list_add_before(&code,&code4->list);
}
else { //Simple IF
Operand op1=con_oper(LABEL,++label_total);
Operand op2=con_oper(LABEL,++label_total);
InterCode code1=con_inter(DEF_LABEL_I,op1);
InterCode code2=con_inter(DEF_LABEL_I,op2);
translate_cond(node->next[2],op1,op2);
list_add_before(&code,&code1->list);
translate_stmt(node->next[4]);
list_add_before(&code,&code2->list);
}
}
Operand translate_vardec(Node* node){
DEBUG(printf("%s:%s %d\n",__FUNCTION__,node->content,node->cnt);)
if (node->cnt==1){
return getvar(node->next[0]);
}
else {
while (node->cnt==4){
node=node->next[0];
}
FieldList field=returnvar(node->next[0]->content+4);
puts(node->next[0]->content+4);
assert(field->var_no==0);
field->var_no=++temp_total;
int nowsize=4;
Type temp=field->type;
while (temp->kind==ARRAY){
nowsize*=temp->u.array.size;
temp=temp->u.array.elem;
}
Operand op_size=con_oper(SIZE,nowsize);
Operand op_var=con_oper(VARIABLE,field->var_no);
InterCode intercode=con_inter(DEC_SIZE_I,op_var,op_size);
list_add_before(&code,&intercode->list);
return op_var;
}
}
void translate_func(Node* node){
Node* fun = node->next[1];
char *func =fun->next[0]->content+4;
Operand op_fun = con_oper(FUNCTION,func);
InterCode funcode = con_inter(DEF_FUN_I,op_fun);
list_add_before(&code,&funcode->list);
if (strcmp(fun->next[2]->content,"VarList")==0)
{
Node* list=fun->next[2];
while (list!=NULL)
{
Node* temp=list->next[0];
Node* Dec=temp->next[1];
while (Dec){
if (Dec->cnt==1){
Node* ID=Dec->next[0];
FieldList field=returnvar(ID->content+4);
field->isparam=1;
Operand var=getvar(ID);
InterCode intercode= con_inter(PARAM_I,var);
list_add_before(&code,&intercode->list);
}
Dec=Dec->next[0];
}
list=list->next[2];
}
}
}
void translate_compst(Node* node)
{
Node* DefList=node->next[1];
Node* StmtList=node->next[2];
DEBUG(printf("%s:%d %s %s \n",__FUNCTION__,node->line,DefList->content,StmtList->content);)
while (DefList!=NULL&&strcmp(DefList->content,"DefList")==0)
{
Node* Def=DefList->next[0];
Node* DecList=Def->next[1];
while (DecList!=NULL&&DecList->cnt>0)
{
Node* Dec=DecList->next[0];
if (Dec->cnt==1){
translate_vardec(Dec->next[0]);
}
else {
Operand var=translate_vardec(Dec->next[0]);
Operand tmp=con_oper(TEMP,++temp_total);
translate_exp(Dec->next[2],&tmp);
InterCode intercode=con_inter(ASSIGN_I,var,tmp);
list_add_before(&code,&intercode->list);
}
DecList=DecList->next[2];
}
DefList=DefList->next[1];
}
while (StmtList!=NULL&&strcmp(StmtList->content,"StmtList")!=0)
StmtList=node->next[1];
while (StmtList!=NULL)
{
Node* Stmt=StmtList->next[0];
translate_stmt(Stmt);
StmtList=StmtList->next[1];
}
}
void translate(Node* node){
if (strcmp(node->content,"ExtDef")==0)
{
if (strcmp(node->next[1]->content,"ExtDecList")==0)
{
Node* temp=node->next[1];
while (temp!=NULL)
{
translate_vardec(temp->next[0]);
temp=temp->next[2];
}
}
else if (strcmp(node->next[1]->content,"FunDec")==0)
{
//func
translate_func(node);
translate_compst(node->next[2]);
}
}
else
{
int i;
for (i=0;i<node->cnt;i++)
translate(node->next[i]);
}
}
|
C
|
#include <stdio.h>
/*
Create a my_add function which takes 2 paramters (nbr1 and nbr2) and return a value. This value is the result of the addtion of nbr1 and nbr2 parameters.
*/
int my_add(int a, int b);
int main() {
int first_Number = 30;
int second_Number = 20;
int Result = my_add(first_Number, second_Number);
printf("The result of adding number 1 and number 2 are %i\n", Result);
return 0;
}
int my_add(int a, int b) {
int result_of_Addition;
result_of_Addition = a + b;
return result_of_Addition;
}
|
C
|
#include <stdio.h>
#include "q1_atividadeModulos.h"
#include "q1_atividadeModulos_Funcoes.c"
void main(void){
printf("Celsius: 10, Fah: %.2f\n", converte(10));
printf("Fatorial de 5: %i", fat(5));
printf("O comprimento de 'Igor Santos': %i", comprimento("Igor Santos"));
}
|
C
|
/* File: containeri_inl.h
* Date: 12 Sep 06
* Rev: 25 Sep 07
*
* Container class definitions - version 2
*/
/* use clean
* then touch container_inl.h
* make
*/
#include <stdlib.h>
#include "common.h"
#include "entry.h"
#include "container.h"
inline Container::Container()
/* initialize a Container object
* pre: none
* post: Container has been created and initialized to empty
* */
{
clear();
}
inline void Container::clear()
/* clear a Container object
* pre: Container has been created
* post: all entries have been removed; Container is empty
* */
{
count = 0;
}
inline Entry Container::get(Position P) const
/* return entry at position p
pre: Container has been created, and 0 <= p < n, where n is number
of Container entries
post: entry at position p has been returned as x, Container unchanged
error: if Container is shorter than p, nothing done an waring produced.
* */
{
if( Valid(P, count-1) )
return elements[P];
else
{
/*Warning("Not a valid position; returning a -1");*/
return -1;
}
}
inline void Container::replace(Entry x, Position p)
/* replace entry at position p with x
pre: Container has been created, and 0 <= p < n, where n is number
of Container entries
post: entry at position p has been replaced with x, other entries unchanged
error: if Container is shorter than p, nothing done an waring produced.
* */
{
if( Valid(p, count-1) )
elements[p] = x;
else
{
Warning("Not a valid position; nothing done");
return;
}
}
inline int Container::size() const
/* determines the size of a Container
pre: Container has been created
post: returns the number of entries in the Container
* */
{
return count;
}
inline bool Container::isempty() const
/* tests if a Container is empty
pre: Container has been created
post: returns true if Container is empty; false otherwise
* */
{
return(count == 0);
}
inline bool Container::isfull() const
/* tests if a Container is full
pre: Container has been created
post: returns true if Container is full; false otherwise
*/
{
return(count == MAXSIZE);
}
inline bool Container::Valid(Position p, int size) const
/* tests if given position is a valid position.
* if p is within 0 and size then the position is within
* the bounds of the current list of data entries
*/
{
return ( p >= 0 && p <= size );
}
inline bool Container::operator==(Container *b)
{
return Equal(b);
}
inline bool Container::operator!=(Container *b)
{
return NotEqual(b);
}
|
C
|
#include<stdio.h>
int main()
{
char i[10],j[10];
printf("Please enter value of i: ");
scanf("%s",&i);
printf("Please enter value of i: ");
scanf("%s",&j);
printf("Your full name is : %s %s",i,j);
}
|
C
|
//############################### CLIENTE ###################################
#pragma once
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h> // inet_aton
#include <pthread.h>
#include "simulador.h"
#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
#define TRUE 1
#define FALSE 0
// ########################## SIMULADOR #####################################
// Todos os valores serão inicializados na função inicia_sistemas.
// *
// *
// *
// Controle de Temperatura
// *
// temperatura == temperatura ajustada pelo usuário
// sensor_temperatura == leitura do sensor de temperatura
// m_temp == mutex da temperatura
// m_stemp == mutex do sensor_temperatura
// *
// Temperatura do ar condicionado varia entre 17 e 24 graus
// Como a temperatura com o ar ligado tem um intervalo fixo, não há
// necessidade de ter uma variável específica para salvar o estado da
// temperatura, como há no caso da iluminação.
// temperatura = 0 == ar condicionado desligado
// temperatura entre 17 e 24 == ar condicionado ligado
// temperatura = 0 indica que o usuário ainda não ajustou suas preferências.
// Valor padrão é temperatura = 0 (desligado, sem pref do user)
int temperatura;
// *
// para garantir a exclusão mútua
pthread_mutex_t m_temp = PTHREAD_MUTEX_INITIALIZER;
// *
// Para armazenar a leitura do sensor de temperatura
// Valor padrão é sensor_temperatura = aleatorio entre -5 e 45;
int sensor_temperatura;
// *
// para garantir a exclusão mútua
pthread_mutex_t m_stemp = PTHREAD_MUTEX_INITIALIZER;
// *
// *
// *
// Controle de Iluminação
// *
// luz == iluminação atual
// sensor_presenca == leitura do sensor de presenca
// m_luz == mutex de luz
// m_spresenca == mutex de sensor_presenca
// *
// A luz armazena o estado atual da iluminação. A iluminação pode tanto ter
// sido ajustada pelo usuário (valores positivos) quanto pelo programa
// (valores negativos). Os valores que indicam o estado são simétricos, para
// que através do cálculo do valor absoluto do estado, saiba-se qual é a
// iluminação, independente de quem (usuário ou programa) a ajustou. Saber quem
// ajustou a iluminação é necessário, por exemplo, caso o usuário desligue a luz.
// Mesmo que o sensor de presença indique alguém, a luz não deverá ser acesa.
// A luz pode estar ligada em 100% da intensidade, ligada em 50% da intensidade
// (meia luz) ou desligada.
// *
// luz = -2 == luz ligada pelo programa, 100% de intensidade
// luz = -1 == luz desligada pelo programa
// luz = 0 == luz desligada (padrão)
// luz = 1 == luz desligada pelo usuário
// luz = 2 == luz ligada pelo usuário, 100% de intensidade
// luz = 3 == luz ligada pelo usuário, 50% de intensidade
// O valor padrão é luz = 0
int luz;
// *
// para garantir a exclusão mútua
pthread_mutex_t m_luz = PTHREAD_MUTEX_INITIALIZER;
// *
// Para armazenar a leitura do sensor de presença.
// sensor_presenca = 0 == não há ninguém (FALSE)
// sensor_presenca = 1 == há alguém (TRUE)
// O valor padrão é sensor_presença = FALSE
int sensor_presenca;
// *
// para garantir a exclusão mútua
pthread_mutex_t m_spresenca = PTHREAD_MUTEX_INITIALIZER;
// *
// *
// *
// Controle de Biometria
// *
// A biometria será simulada como uma sequência numérica, para facilitar a
// implementação.
// biometria == valor salvo de biometria
// sensor_biometria == leitura do sensor de biometria
// m_bio == mutex biometria
// m_sbio == mutex sensor_biometria
// *
// Biometria é um unsigned int com um valor salvo para abrir a porta.
// Valor padrão é 1234
unsigned int biometria;
// *
// para garantir a exclusão mútua
pthread_mutex_t m_bio = PTHREAD_MUTEX_INITIALIZER;
// *
// Para armazenar a leitura do sensor de biometria.
// sensor_biometria = 0 == não há leitura
// sensor_biometria != 0 == o valor lido
unsigned int sensor_biometria;
// *
// para garantir a exclusão mútua
pthread_mutex_t m_sbio = PTHREAD_MUTEX_INITIALIZER;
// *
// *
// *
// Controle da Porta
// *
// porta == controla o estado da porta (aberta ou fechada)
// m_porta == mutex associado
// *
// A porta pode estar aberta ou fechada.
// porta = 0 == porta fechada
// porta = 1 == porta aberta
int porta;
// *
// para garantir a exclusão mútua
pthread_mutex_t m_porta = PTHREAD_MUTEX_INITIALIZER;
// *
// *
// *
// Controle da Janela
// *
// janela == controla o estado da janela (aberta ou fechada)
// m_janela == mutex associado
// *
// A janela pode estar aberta ou fechada.
// janela = 0 == janela fechada
// janela = 1 == janela aberta
int janela;
// *
// para garantir a exclusão mútua
pthread_mutex_t m_janela = PTHREAD_MUTEX_INITIALIZER;
// *
// *
// *
// Controle da Cortina (persiana)
// *
// cortina == controla o estado da cortina (aberta, fechada, ou entreaberta)
// m_cortina == mutex associado
// *
// A cortina pode estar aberta, fechada ou entreaberta.
// cortina = 0 == cortina fechada
// cortina = 1 == cortina aberta
// cortina = 2 == cortina entreaberta
int cortina;
// *
// para garantir a exclusão mútua
pthread_mutex_t m_cortina = PTHREAD_MUTEX_INITIALIZER;
// *
// ########################## ########## #####################################
// *
// Comando recebido do monitor
// *
PROTOCOLO comando;
pthread_mutex_t m_comm = PTHREAD_MUTEX_INITIALIZER;
// *
// Se o comando executou corretamente ou não -- Retornar para monitor
// *
char retorno[30] = "\0";
pthread_mutex_t m_ret = PTHREAD_MUTEX_INITIALIZER;
// *
// Espera ter comando para poder executar
// *
int flag_executar_comando = FALSE;
pthread_mutex_t exec = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_exec = PTHREAD_COND_INITIALIZER;
// *
// Espera precisar escrever para acordar escrita
// *
int flag_escrita_rede = FALSE;
pthread_mutex_t c = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_esc = PTHREAD_COND_INITIALIZER;
//#################################### REDE ###################################
int sockfd;
// *
// Threads responsáveis pela leitura e escrita na rede.
// A leitura roda indefinidamente, a escrita, por ser bloqueante,
// só acorda quando é necessário (via variáveis de condição).
// *
void *receber_do_monitor(void *arg) {
char buffer[30];
int n;
while (TRUE) {
bzero(buffer,sizeof(buffer));
//lendo o buffer
n = read(sockfd,buffer,sizeof(buffer));
if (n <= 0) {
if (n < 0){
printf("Erro lendo do socket!\n");
close(sockfd);
exit(1);
}
}
else {
pthread_mutex_lock(&exec);
gera_protocolo(buffer,&comando);
flag_executar_comando = TRUE;
pthread_cond_signal(&cond_exec);
pthread_mutex_unlock(&exec);
printf("\n\n\t Comando recebido:\n\n");
imprime_protocolo(&comando);
printf("\n\n");
if (strcmp(buffer,"sair\n") == 0) {
printf("\n\n\t Simulador OFF.\n\n");
close(sockfd);
exit(0);
}
}
}
}
void *enviar_para_monitor(void *arg){
char buffer[30];
int n;
while(TRUE){
bzero(buffer, sizeof(buffer));
pthread_mutex_lock(&c);
while(!flag_escrita_rede){ //ao contrário -> var cond
pthread_cond_wait(&cond_esc,&c);
}
strcpy(buffer, retorno);
flag_escrita_rede = FALSE;
pthread_mutex_unlock(&c);
n = write(sockfd, buffer, sizeof(buffer));
if (n < 0) {
printf("Erro escrevendo no socket!\n");
close(sockfd);
exit(1);
}
}
}
//######################## Comando Usuário ###############################
// *
// Thread que fica dormente até que seja recebido um comando válido.
// Quando isso acontece, ela acorda, tenta a execução do comando e
// dorme novamente (para não ocorrer espera ocupada). Se ela não con-
// seguir executar o comando, retorna FALSE, para poder enviar o
// retorno ao servidor.
// *
void *executar_comando_usuario(void *arg){
while(TRUE){
pthread_mutex_lock(&exec);
while(!flag_executar_comando){//ao contrário -> var cond
pthread_cond_wait(&cond_exec,&exec);
}
executar_comando();
printf("\n\t USER: %s \n\n", retorno);
//esperar novo comando
flag_executar_comando = FALSE;
pthread_mutex_unlock(&exec);
//ativar escrita na rede
pthread_mutex_lock(&c);
flag_escrita_rede = TRUE;
pthread_cond_signal(&cond_esc);
pthread_mutex_unlock(&c);
}
}
//################################# TIMER ################################
// *
// Timer responsável pelas tarefas periódicas.
// *
struct periodic_info{
int sig;
sigset_t alarm_sig;
};
static int make_periodic (int unsigned period, struct periodic_info *info){
static int next_sig;
int ret;
unsigned int ns;
unsigned int sec;
struct sigevent sigev;
timer_t timer_id;
struct itimerspec itval;
/* Initialise next_sig first time through. We can't use static
initialisation because SIGRTMIN is a function call, not a constant */
if (next_sig == 0)
next_sig = SIGRTMIN;
/* Check that we have not run out of signals */
if (next_sig > SIGRTMAX)
return -1;
info->sig = next_sig;
next_sig++;
/* Create the signal mask that will be used in wait_period */
sigemptyset (&(info->alarm_sig));
sigaddset (&(info->alarm_sig), info->sig);
/* Create a timer that will generate the signal we have chosen */
sigev.sigev_notify = SIGEV_SIGNAL;
sigev.sigev_signo = info->sig;
sigev.sigev_value.sival_ptr = (void *) &timer_id;
ret = timer_create (CLOCK_MONOTONIC, &sigev, &timer_id);
if (ret == -1)
return ret;
/* Make the timer periodic */
sec = period/1000000;
ns = (period - (sec * 1000000)) * 1000;
itval.it_interval.tv_sec = sec;
itval.it_interval.tv_nsec = ns;
itval.it_value.tv_sec = sec;
itval.it_value.tv_nsec = ns;
ret = timer_settime (timer_id, 0, &itval, NULL);
return ret;
}
static void wait_period (struct periodic_info *info){
int sig;
sigwait (&(info->alarm_sig), &sig);
}
// *
// As tarefas periódicas necessárias para a leitura dos sensores.
// Se a leitura feita diferir dos valores setados pelo usuário, será feito o ajuste
// necessário aqui mesmo.
// *
// Se há a biometria correta, abre a porta
static void *ler_biometria (void *arg){
struct periodic_info info;
//periodo = 1s
make_periodic (1000000, &info);
while (TRUE){
wait_period (&info);
ler_sensor_biometria();
printf("Leitura Sensor Biometria: %d \n", sensor_biometria);
// Se é a biometria do usuário
if (sensor_biometria == biometria && porta == 0){
abrir_porta();
printf("\n\t AUTO: Porta Aberta \n\n");
sleep(3);
fechar_porta();
printf("\n\t AUTO: Porta Fechada \n\n");
pthread_mutex_lock(&m_sbio);
sensor_biometria = 0;
pthread_mutex_unlock(&m_sbio);
}
else{
pthread_mutex_lock(&m_sbio);
sensor_biometria = 0;
pthread_mutex_unlock(&m_sbio);
}
}
return NULL;
}
// Se o sensor de presença captar alguem, acende a luz
static void *ler_presenca (void *arg){
struct periodic_info info;
//período = 1s
make_periodic (1000000, &info);
while (TRUE){
wait_period (&info);
ler_sensor_presenca();
printf("Leitura Sensor Presença: %d\n", sensor_presenca);
if (sensor_presenca == TRUE && luz == -1){
ligar_luz(PROG);
printf("\n\t AUTO: Luz Ligada \n\n");
}
else if (sensor_presenca == FALSE && luz == -2){
desligar_luz(PROG);
printf("\n\t AUTO: Luz Desligada \n\n");
}
}
return NULL;
}
// Mantém a temperatura
static void *ler_temperatura (void *arg){
struct periodic_info info;
//período = 5s
make_periodic (5000000, &info);
while (TRUE){
wait_period (&info);
ler_sensor_temperatura();
printf("Leitura Sensor Temperatura: %d \n", sensor_temperatura);
}
return NULL;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_getnextline.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: flpop <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/11/11 10:32:03 by flpop #+# #+# */
/* Updated: 2014/11/11 10:32:27 by flpop ### ########.fr */
/* */
/* ************************************************************************** */
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include "libft.h"
static int gnl_dried_file(t_str **read_buff, t_str **buff, t_str **line)
{
if ((*read_buff)->l == 0)
{
ft_t_strdel(read_buff);
if ((*buff)->l == 0)
return (0);
*line = ft_t_strdup(*buff);
ft_memdel(&((*buff)->s));
(*buff)->l = 0;
return (1);
}
ft_t_strdel(read_buff);
ft_t_strdel(buff);
return (-1);
}
static int gnl_filled_file(t_str **buff, t_str **read_buff)
{
t_str *swap;
if (*buff == NULL)
{
*buff = ft_t_strdup(*read_buff);
ft_t_strdel(read_buff);
if (*buff == NULL)
return (-1);
}
else
{
swap = ft_t_strjoin(*buff, *read_buff);
ft_t_strdel(buff);
ft_t_strdel(read_buff);
if ((*buff = swap) == NULL)
return (-1);
}
return (0);
}
int ft_getnextline(int const fd, t_str **line)
{
static t_str *buff = NULL;
t_str *read_buff;
if (line == NULL || 1 > BUFF_SIZE)
return (-1);
if ((read_buff = ft_t_strnew(NULL, 0)) == NULL)
return (-1);
while ((buff == NULL) || (*line = ft_t_strcutchr(buff, '\n')) == NULL)
{
read_buff = ft_t_strnew(NULL, BUFF_SIZE);
if ((read_buff->l = read(fd, read_buff->s, BUFF_SIZE)) <= 0)
return (gnl_dried_file(&read_buff, &buff, line));
if ((gnl_filled_file(&buff, &read_buff)) == -1)
return (-1);
}
return (1);
}
|
C
|
#include "SynADT.h"
struct stack_t avlStack(int *myStack, int hdPtr_avl, volatile int command, ptr_t pointer, int volatile operation){
struct stack_t output;
int rightMask = 0x80000000;
volatile int nodeData;
volatile int stackOut;
volatile int temp = 0;
volatile int temp_r = 100;
volatile int command_in = command;
if(command == WRITE_STACK){
if(operation == GOING_LEFT){
nodeData = pointer;
}else if(operation == GOING_RIGHT){
nodeData = pointer | rightMask;
}
//hdPtr_avl++;
temp = hdPtr_avl + 1;
if(temp != 0){
//hdPtr_avl = temp;
myStack[temp] = nodeData;
output.hdPtr_avl = temp;
}
}else{
//read
stackOut = myStack[hdPtr_avl];
//hdPtr_avl --;
temp_r = hdPtr_avl - 1;
if((stackOut & 0x80000000) == GOING_LEFT){
output.operation = GOING_LEFT;
}else{
output.operation = GOING_RIGHT;
}
output.pointer = (stackOut & 0x1FFFFFFF);
//delete
if(temp_r != 100){
output.hdPtr_avl = temp_r;
}
}
return output;
}
volatile struct stack_t AVL_STACK_WRITE(int *myStack, int hdStack, ptr_t pointer, int operation){
struct stack_t output;
int nodeData;
if(operation == GOING_LEFT){
nodeData = pointer;
}else if(operation == GOING_RIGHT){
nodeData = pointer | 0x80000000;
}
myStack[hdStack + 1] = nodeData;
output.hdPtr_avl = hdStack + 1;
return output;
}
volatile struct stack_t AVL_STACK_READ(int *myStack, int hdStack){
struct stack_t output;
int stackOut = myStack[hdStack];
if((stackOut & 0x80000000) == 0){
output.operation = GOING_LEFT;
}else{
output.operation = GOING_RIGHT;
}
output.pointer = (stackOut & 0x1FFFFFFF);
output.hdPtr_avl = hdStack - 1;
return output;
}
|
C
|
/*
* Arduino-serial
* --------------
*
* A simple command-line example program showing how a computer can
* communicate with an Arduino board. Works on any POSIX system (Mac/Unix/PC)
*
*
* Compile with something like:
* gcc -o arduino-serial arduino-serial.c
*
* Created 5 December 2006
* Copyleft (c) 2006, Tod E. Kurt, tod@todbot.com
* http://todbot.com/blog/
*
*
* Updated 8 December 2006:
* Justin McBride discoevered B14400 & B28800 aren't in Linux's termios.h.
* I've included his patch, but commented out for now. One really needs a
* real make system when doing cross-platform C and I wanted to avoid that
* for this little program. Those baudrates aren't used much anyway. :)
*
* Updated 26 December 2007:
* Added ability to specify a delay (so you can wait for Arduino Diecimila)
* Added ability to send a binary byte number
*
* Update 31 August 2008:
* Added patch to clean up odd baudrates from Andy at hexapodia.org
*
*/
#include "cubduino.h"
// Ruby 1.x compatibility
#ifndef RSTRING_PTR
#define RSTRING_PTR(s) (RSTRING(s)->ptr)
#endif
#ifndef RSTRING_LEN
#define RSTRING_LEN(s) (RSTRING(s)->len)
#endif
VALUE Cubduino;
VALUE sBaud, sDataBits, sStopBits, sParity; /* strings */
VALUE sRts, sDtr, sCts, sDsr, sDcd, sRi;
void Init_cubduino();
//VALUE method_cwrite(VALUE self);
void usage(void);
int serialport_init(const char* serialport, int baud);
int serialport_writebyte(int fd, uint8_t b);
int serialport_write(int fd, const char* str);
int serialport_read_until(int fd, char* buf, char until);
int main(int argc, char *argv[])
{
int rc,n;
int fd = 0;
int baudrate = B9600; // default
char serialport[256];
char buf[256];
/* parse options */
int option_index = 0, opt;
static struct option loptions[] = {
{"help", no_argument, 0, 'h'},
{"port", required_argument, 0, 'p'},
{"baud", required_argument, 0, 'b'},
{"send", required_argument, 0, 's'},
{"receive", no_argument, 0, 'r'},
{"num", required_argument, 0, 'n'},
{"delay", required_argument, 0, 'd'}
};
while(1) {
opt = getopt_long (argc, argv, "hp:b:s:rn:d:",
loptions, &option_index);
if (opt==-1) break;
switch (opt) {
case '0': break;
case 'd':
n = strtol(optarg,NULL,10);
usleep(n * 1000 ); // sleep milliseconds
break;
case 'h':
usage();
break;
case 'b':
baudrate = strtol(optarg,NULL,10);
break;
case 'p':
strcpy(serialport,optarg);
fd = serialport_init(optarg, baudrate);
if(fd==-1) return -1;
break;
case 'n':
n = strtol(optarg, NULL, 10); // convert string to number
rc = serialport_writebyte(fd, (uint8_t)n);
if(rc==-1) return -1;
break;
case 's':
strcpy(buf,optarg);
rc = serialport_write(fd, buf);
if(rc==-1) return -1;
break;
case 'r':
serialport_read_until(fd, buf, '\n');
printf("read: %s\n",buf);
break;
}
}
exit(EXIT_SUCCESS);
} // end main
int serialport_writebyte( int fd, uint8_t b)
{
int n = write(fd,&b,1);
if( n!=1)
return -1;
return 0;
}
int serialport_write(int fd, const char* str)
{
int len = strlen(str);
int n = write(fd, str, len);
if( n!=len )
return -1;
return 0;
}
int serialport_read_until(int fd, char* buf, char until)
{
char b[1];
int i=0;
do {
int n = read(fd, b, 1); // read a char at a time
if( n==-1) return -1; // couldn't read
if( n==0 ) {
usleep( 10 * 1000 ); // wait 10 msec try again
continue;
}
buf[i] = b[0]; i++;
} while( b[0] != until );
buf[i] = 0; // null terminate the string
return 0;
}
// takes the string name of the serial port (e.g. "/dev/tty.usbserial","COM1")
// and a baud rate (bps) and connects to that port at that speed and 8N1.
// opens the port in fully raw mode so you can send binary data.
// returns valid fd, or -1 on error
int serialport_init(const char* serialport, int baud)
{
struct termios toptions;
int fd;
//fprintf(stderr,"init_serialport: opening port %s @ %d bps\n",
// serialport,baud);
fd = open(serialport, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("init_serialport: Unable to open port ");
return -1;
}
if (tcgetattr(fd, &toptions) < 0) {
perror("init_serialport: Couldn't get term attributes");
return -1;
}
speed_t brate = baud; // let you override switch below if needed
switch(baud) {
case 4800: brate=B4800; break;
case 9600: brate=B9600; break;
#ifdef B14400
case 14400: brate=B14400; break;
#endif
case 19200: brate=B19200; break;
#ifdef B28800
case 28800: brate=B28800; break;
#endif
case 38400: brate=B38400; break;
case 57600: brate=B57600; break;
case 115200: brate=B115200; break;
}
cfsetispeed(&toptions, brate);
cfsetospeed(&toptions, brate);
// 8N1
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
// no flow control
toptions.c_cflag &= ~CRTSCTS;
toptions.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
toptions.c_oflag &= ~OPOST; // make raw
// see: http://unixwiz.net/techtips/termios-vmin-vtime.html
toptions.c_cc[VMIN] = 0;
toptions.c_cc[VTIME] = 20;
if( tcsetattr(fd, TCSANOW, &toptions) < 0) {
perror("init_serialport: Couldn't set term attributes");
return -1;
}
return fd;
}
static VALUE method_write(VALUE class, VALUE arg) {
printf("%s", RSTRING_PTR(arg));
return Qnil;
}
static VALUE method_read() {
int fd = 0;
int baudrate = 9600;
fd = serialport_init(optarg, baudrate);
char buf[256];
serialport_read_until(fd, buf, '\n');
return rb_str_new2(buf);
}
void Init_cubduino() {
Cubduino = rb_define_module("Cubduino");
rb_define_singleton_method(Cubduino, "read", method_write, 0);
rb_define_singleton_method(Cubduino, "write", method_write, 1);
}
|
C
|
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include "../../header/includes.h"
static int plan_compose(int plan_index, char **line_split, scene *my_scene)
{
if (ft_len_tab(line_split) == 3)
{
if (ft_strchrstr(line_split[0], "material") == 0)
plan_mat(plan_index, line_split[2], my_scene);
if (ft_strchrstr(line_split[0], "normal") == 0)
plan_normal(plan_index, line_split[2], my_scene);
if (ft_strchrstr(line_split[0], "offset") == 0)
plan_offset(plan_index, line_split[2], my_scene);
}
else if (line_split[0][0] != '}')
return (-1);
return (0);
}
int detect_plan(int fd, char *line, scene *my_scene)
{
static int plan_index = 0;
char **line_split;
line_split = NULL;
if (plan_index < my_scene->num_plan)
{
while (line[0] != '}')
{
get_next_line(fd, &line);
line_split = ft_strsplit(line, ' ');
if (plan_compose(plan_index, line_split, my_scene) == -1)
return (-1);
}
}
else
return (-1);
plan_index++;
return (0);
}
|
C
|
/*
** store_link.c for store_link in /home/bartel_r//svn/corewar_2013s/trunk/casm
**
** Made by remi bartel
** Login <bartel_r@epitech.net>
**
** Started on Thu Dec 9 21:58:44 2010 remi bartel
** Last update Fri Dec 10 01:37:21 2010 remi bartel
*/
#include "xfunctions.h"
#include "asm.h"
#include "op.h"
#include "commons.h"
t_label *add_label(t_label *list, char *label)
{
t_label *link;
link = xmalloc(sizeof(*link));
link->label = my_strdup(label);
link->l_inst = NULL;
link->next = list;
list = link;
free(label);
return (list);
}
void store_link(t_file *file, t_link *data)
{
if (data->label != NULL)
file->label_list = add_label(file->label_list, data->label);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include "puzzle2D.h"
//this file's function will solve the word puzzle and return the position and direction.
int *toprightbackwardstobottomleft(char puzzletable[][101], int word_length, unsigned long long int hashvalue);
int *bottomlefttotopright(char puzzletable[][101], int word_length, unsigned long long int hashvalue);
int *bottomrightbackwardstotopleft(char puzzletable[][101], int word_length, unsigned long long int hashvalue);
int *toplefttobottomright(char puzzletable[][101], int word_length, unsigned long long int hashvalue);
int *verticalup(char puzzletable[][101], int word_length, unsigned long long int hashvalue);
int *verticaldown(char puzzletable[][101], int word_length, unsigned long long int hashvalue);
int *horizontalleft(char puzzletable[][101], int word_length, unsigned long long int hashvalue);
int *horizontalright(char puzzletable[][101], int word_length, unsigned long long int hashvalue);
int RobinKarp(char string[], int word_length, unsigned long long int hashvalue);
//pass word one by one, each time call hash function in wordsearch2d.c, just try to solve one word in the entire puzzle. puzzle2d.c is search the word in different 8 directions one by one by comparing the hash value(using robin karp algorithm).
//if the word is found in puzzle, function will return a pointer points to an array contains position and direction; if not, return zero.
int hash(char puzzletable[][101], char word[], int word_length,FILE *fp3)
{
double prime=101;
int i;
unsigned long long int hashvalue=0;
int *ptr;
//calculate word's hash value
for(i=0;i<word_length;i++)
{
hashvalue += word[i]*(pow(prime, (double)(word_length-i-1)));
}
//search and compare hash value in 8 different directions
ptr = horizontalright(puzzletable, word_length, hashvalue);
if (ptr == NULL)
{
ptr = horizontalleft(puzzletable, word_length, hashvalue);
if(ptr == NULL)
{
ptr = verticaldown(puzzletable, word_length, hashvalue);
if (ptr==NULL)
{
ptr = verticalup(puzzletable, word_length, hashvalue);
if (ptr==NULL)
{
ptr = toplefttobottomright(puzzletable, word_length, hashvalue);
if (ptr==NULL)
{
ptr = bottomrightbackwardstotopleft(puzzletable, word_length, hashvalue);
if(ptr==NULL)
{
ptr=bottomlefttotopright(puzzletable, word_length, hashvalue);
if(ptr==NULL)
{
ptr = toprightbackwardstobottomleft(puzzletable, word_length, hashvalue);
if (ptr == NULL)
fprintf(fp3,"(0,0);0\n");
else
fprintf(fp3,"(%d,%d);%d\n",ptr[0],ptr[1],ptr[2]);
}
else
fprintf(fp3,"(%d,%d);%d\n",ptr[0],ptr[1],ptr[2]);
}
else
fprintf(fp3,"(%d,%d);%d\n",ptr[0],ptr[1],ptr[2]);
}
else
fprintf(fp3,"(%d,%d);%d\n",ptr[0],ptr[1],ptr[2]);
}
else
fprintf(fp3,"(%d,%d);%d\n",ptr[0],ptr[1],ptr[2]);
}
else
fprintf(fp3,"(%d,%d);%d\n",ptr[0],ptr[1],ptr[2]);
}
else
fprintf(fp3,"(%d,%d);%d\n",ptr[0],ptr[1],ptr[2]);
}
else
fprintf(fp3,"(%d,%d);%d\n",ptr[0],ptr[1],ptr[2]);
return 0 ;
}
int * horizontalright(char puzzletable[][101], int word_length, unsigned long long int hashvalue)
{
int col = -1;
int i;
for (i=0;i<strlen(puzzletable[0]);i++)
{
//call robinkarp function to calculate this line of puzzle 's hash value and compare with the word value
//puzzletable passes robinkarp function line by line
col = RobinKarp(puzzletable[i],word_length,hashvalue);
//if in this direction can find word:
if (col != -1)
{
int position[3] = {i,col,1};
int *pospointer = position;
return pospointer;
}
}
//if cannot find word in this direction, return null and the word pass into next direction
return NULL;
}
int * horizontalleft(char puzzletable[][101], int word_length, unsigned long long int hashvalue)
{
int col = -1;
int i;
int w=0,k=strlen(puzzletable[0])-1;
for (i=0;i<strlen(puzzletable[0]);i++)
{
//reverse horizontalright string
char reverse[strlen(puzzletable[0])+1];
for(w=0, k=strlen(puzzletable[0])-1; w<=strlen(puzzletable[0])-1 && k>= 0; w++,k--)
{
reverse[w] = puzzletable[i][k];
}
reverse[strlen(puzzletable[0])] = '\0';
col = RobinKarp(reverse,word_length,hashvalue);
if (col != -1)
{
int position[3] = {i,strlen(puzzletable[0])-col-1,2};
int *pospointer = position;
return pospointer;
}
}
return NULL;
}
int * verticaldown(char puzzletable[][101], int word_length, unsigned long long int hashvalue)
{
int row = -1;
int i;
int j;
int puzzlesize=0;
puzzlesize = strlen(puzzletable[0]);
char vertical[puzzlesize+1];
for(j=0;j<puzzlesize;j++)
{
for (i=0;i<puzzlesize;i++)
{
vertical[i] = puzzletable[i][j];
}
vertical[puzzlesize] = '\0';
row = RobinKarp(vertical,word_length,hashvalue);
if (row != -1)
{
int position[3] = {row,j,3};
int *pospointer = position;
return pospointer;
}
}
return NULL;
}
int * verticalup(char puzzletable[][101], int word_length, unsigned long long int hashvalue)
{
int row = -1;
int i;
int j;
int puzzlesize=0;
int w=0,k=strlen(puzzletable[0])-1;
puzzlesize = strlen(puzzletable[0]);
char vertical[puzzlesize+1];
for(j=0;j<puzzlesize;j++)
{
for (i=0;i<puzzlesize;i++)
{
vertical[i] = puzzletable[i][j];
}
vertical[puzzlesize] = '\0';
char reverse[puzzlesize+1];
for(w=0, k=strlen(puzzletable[0])-1; w<=strlen(puzzletable[0])-1 && k>= 0; w++,k--)
{
reverse[w] = vertical[k];
}
reverse[strlen(puzzletable[0])] = '\0';
row = RobinKarp(reverse,word_length,hashvalue);
if (row != -1)
{
int position[3] = {puzzlesize-row-1,j,4};
int *pospointer = position;
return pospointer;
}
}
return NULL;
}
//diagonal directions
int * toplefttobottomright(char puzzletable[][101], int word_length, unsigned long long int hashvalue)
{
int index = -1;
int i,k,j;
int puzzlesize = strlen(puzzletable[0]);
//the string above the longest diagoanl
for(i=0;i<puzzlesize;i++)
{
char string[word_length+1];
for (k=0;k<puzzlesize-i;k++)
{
string[k] = puzzletable[k][k+i];
}
string[puzzlesize-i] = '\0';
if (strlen(string)>=word_length)
{
index = RobinKarp(string,word_length,hashvalue);
if (index != -1)
{
int position[3] = {index,i+index,5};
int *pospointer = position;
return pospointer;
}
}
}
//the string below the longest diagoanl
for (j=0;j<puzzlesize;j++)
{
char string[word_length+1];
for(k=0;k<puzzlesize-j;k++)
{
string[k] = puzzletable[k+j][k];
}
string[puzzlesize-j]='\0';
if (strlen(string)>=word_length)
{
//printf("%s\n",string);
index = RobinKarp(string,word_length,hashvalue);
if (index != -1)
{
int position[3] = {j+index,index,5};
int *pospointer = position;
return pospointer;
}
}
}
return NULL;
}
int * bottomrightbackwardstotopleft(char puzzletable[][101], int word_length, unsigned long long int hashvalue)
{
int index = -1;
int w,i,k,j,l;
int puzzlesize = strlen(puzzletable[0]);
for(i=0;i<puzzlesize;i++)
{
char string[word_length+1];
for (k=0;k<puzzlesize-i;k++)
{
string[k] = puzzletable[k][k+i];
}
string[puzzlesize-i] = '\0';
//reverse toplefttobottomright string
char reverse[word_length+1];
for(w=0, l=puzzlesize-i-1; w<=puzzlesize-i-1 && l>= 0; w++,l--)
{
reverse[w] = string[l];
}
reverse[puzzlesize-i] = '\0';
if (strlen(reverse)>=word_length)
{
index = RobinKarp(reverse,word_length,hashvalue);
if (index != -1)
{
int position[3] = {puzzlesize-index-1-i,puzzlesize-1-index,6};
int *pospointer = position;
return pospointer;
}
}
}
for (j=0;j<puzzlesize;j++)
{
char string[word_length+1];
for(k=0;k<puzzlesize-j;k++)
{
string[k] = puzzletable[k+j][k];
}
string[puzzlesize-j]='\0';
char reverse[word_length+1];
for(w=0, l=puzzlesize-j-1; w<=puzzlesize-j-1 && l>= 0; w++,l--)
{
reverse[w] = string[l];
}
reverse[puzzlesize-j] = '\0';
if (strlen(reverse)>=word_length)
{
index = RobinKarp(string,word_length,hashvalue);
if (index != -1)
{
int position[3] = {puzzlesize-index-1,puzzlesize-index-j-1,6};
int *pospointer = position;
return pospointer;
}
}
}
return NULL;
}
int * bottomlefttotopright(char puzzletable[][101], int word_length, unsigned long long int hashvalue)
{
int index = -1;
int i,k,j;
int puzzlesize = strlen(puzzletable[0]);
for(i=0;i<puzzlesize;i++)
{
char string[word_length+1];
int l=0;
for (k=puzzlesize-i-1;k>=0;k--)
{
string[l] = puzzletable[k][l];
l++;
}
string[puzzlesize-i] = '\0';
if (strlen(string)>=word_length)
{
index = RobinKarp(string,word_length,hashvalue);
if (index != -1)
{
int position[3] = {puzzlesize-index-i-1,index,7};
int *pospointer = position;
return pospointer;
}
}
}
for (j=0;j<puzzlesize;j++)
{
char string[word_length+1];
int l=0;
for(k=puzzlesize-j-1;k>=0;k--)
{
string[l] = puzzletable[puzzlesize-1-l][puzzlesize-k-1];
l++;
}
string[puzzlesize-j]='\0';
if (strlen(string)>=word_length)
{
index = RobinKarp(string,word_length,hashvalue);
if (index != -1)
{
int position[3] = {puzzlesize-index-1,index+j,7};
int *pospointer = position;
return pospointer;
}
}
}
return NULL;
}
int * toprightbackwardstobottomleft(char puzzletable[][101], int word_length, unsigned long long int hashvalue)
{
int index = -1;
int i,k,j,w,p;
int puzzlesize = strlen(puzzletable[0]);
for(i=0;i<puzzlesize;i++)
{
char string[word_length+1];
int l=0;
for (k=puzzlesize-i-1;k>=0;k--)
{
string[l] = puzzletable[k][l];
l++;
}
string[puzzlesize-i] = '\0';
char reverse[word_length+1];
for(w=0, p=puzzlesize-i-1; w<=puzzlesize-i-1 && p>= 0; w++,p--)
{
reverse[w] = string[p];
}
reverse[puzzlesize-i] = '\0';
if (strlen(reverse)>=word_length)
{
index = RobinKarp(reverse,word_length,hashvalue);
if (index != -1)
{
int position[3] = {index,puzzlesize-index-i-1,8};
int *pospointer = position;
return pospointer;
}
}
}
for (j=0;j<puzzlesize;j++)
{
char string[word_length+1];
int l=0;
for(k=puzzlesize-j-1;k>=0;k--)
{
string[l] = puzzletable[puzzlesize-1-l][puzzlesize-k-1];
l++;
}
string[puzzlesize-j]='\0';
char reverse[word_length+1];
for(w=0, p=puzzlesize-j-1; w<=puzzlesize-p-1 && p>= 0; w++,p--)
{
reverse[w] = string[p];
}
reverse[puzzlesize-j] = '\0';
if (strlen(reverse)>=word_length)
{
index = RobinKarp(reverse,word_length,hashvalue);
if (index != -1)
{
int position[3] = {index+j,puzzlesize-index-1,8};
int *pospointer = position;
return pospointer;
}
}
}
return NULL;
}
//this function 's work is calculate the hash value of puzzle by robin karp algorithm and compare it with word's hashvalue, then can get the result whether the word is matched.
int RobinKarp(char string[], int word_length, unsigned long long int hashvalue)
{
double prime=101;
int i;
const int lenstr = strlen(string);
unsigned long long int value=0;
//calculate hash value of first wordlength string
for(i=0;i<word_length;i++)
{
value += string[i]*(pow(prime, (double)(word_length-i-1)));
}
//if match the word
if (hashvalue == value)
return 0;
else
{
//if not, move forward a character and calculate again
int i;
for(i=1;i<=(lenstr-word_length);i++)
{
value -= string[i-1]*(pow(prime,(double)(word_length-1)));
value = value*prime;
value += string[i+word_length-1];
if (value == hashvalue)
return i;
}
}
//if still not find, the word is not in this line
return -1;
}
|
C
|
#include<stdio.h>
int sum(int n)
{
int rem;
if(n==0)
{
return 0;
}
else
{
rem=n%10;
n=n/10;
rem=rem+sum(n);
return rem;
}
}
int main()
{
int n;
printf("Enter the number: ");
scanf("%d",&n);
printf("\nSum of digits is %d.\n",sum(n));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int* vec = NULL;
int* aux = NULL;
int i = 0, val = 0, cant = 0;
printf("ingrese numero\n");
scanf("%d", &val);
if(val != 0)
{
vec = (int*)malloc((cant + 1)*sizeof(int));
if(vec != NULL)
{
vec[cant] = val;
cant++;
while (val != 0)
{
printf("ingrese numero\n");
scanf("%d", &val);
if(val != 0)
{
aux = (int*)realloc(vec, (cant + 1)*sizeof(int));
if(aux != NULL)
{
aux[cant] = val;
cant++;
vec = aux;
}
}
else
{
printf("Se ingreso '0'\n");
}
}
}
}free(vec);
printf("\n");
for ( i = 0; i < cant; i++)
{
printf("%d\n", vec[i]);
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // include for strerror(3) function
#include <errno.h> // include to access errno
int checkFile(char *path);
int print_error(char *path, int errnum);
void checkError(char *path);
int main (int argc, char *argv[]){
switch (argc) {
case 1:
printf("Usage: file path \n");
exit(EXIT_FAILURE);
case 2:
exit(checkFile(argv[1]));
//default:
//printf("Too many arguments\n");
//exit(EXIT_FAILURE);
}
}
int checkFile(char *path){
// open file
FILE* f = fopen(path, "r");
// check IO error
checkError(path);
// get file size
fseek(f, 0, SEEK_END); // seek to end
int file_size = (int) ftell(f); // get file size
fseek(f, 0, SEEK_SET); // seek back to beginning
// check IO error
checkError(path);
// allocate file size
char *content = (char *) malloc(file_size);
// read file
fread(content, 1, file_size, f);
// check IO error
checkError(path);
// check if file is of type empty
if(file_size == 0){
// empty file
fprintf(stdout, "%s: empty\n", path);
}else{
// check if file is of type data
int bool = 0;
for(int i=0; i<file_size; i++){
if( !((7 <= (int)content[i]) && ((int)content[i] <= 13)) && !((int)content[i] == 27) && !((32 <= (int)content [i]) && ((int)content[i] <= 126))
){
bool = 1;
break;
}
}
// can we roll this into the loop?
if(bool == 1){
fprintf(stdout, "%s: data\n", path);
}else{
fprintf(stdout, "%s: ASCII text\n", path);
}
}
//exit protocol
// close file
fclose(f);
// check IO error
checkError(path);
// exit with exit_succes
exit(EXIT_SUCCESS);
}
int print_error(char *path, int errnum){
return fprintf(stdout, "%s: cannot determine (%s)\n", path, strerror(errnum));
}
void checkError(char *path){
if(errno != 0){
// if IO error, print error
print_error(path, errno);
exit(EXIT_SUCCESS);
}
}
|
C
|
/************************************************ file f6.c ****/
/* function prototype */
double eval(char *str, int length, double *vect, int genes);
double eval(char *str, int length, double *vect, int genes)
{
register int i;
double sum;
sum = 0.0;
for (i = 0; i < length; i++)
sum += (str[i] == '0');
return (sum);
}
/************************************************ end of file ****/
|
C
|
#include "sh.h"
#include <stdio.h>
static void terminate_child(char *command)
{
ft_putstr_fd("Execve failed to execute ", STDERR_FILENO);
ft_putstr_fd(command, STDERR_FILENO);
ft_putstr_fd("\nProcess returned code -1\n", STDERR_FILENO);
exit(-1);
}
static char **convert_env_array(t_env **ev)
{
char **tab;
t_env *curs;
int i;
i = 0;
curs = (*ev);
while (curs)
{
curs = curs->next;
i++;
}
if (MAX_ARG_STRINGS <= i)
{
handle_empty_error("env list is too long", "execve limit");
return NULL;
}
tab = ft_newdim(i + 1);
curs = (*ev);
i = 0;
while (curs)
{
if (curs->scope == 1) {
tab[i] = ft_strnew(ft_strlen(curs->name) + ft_strlen(curs->value) + 1);
ft_strclr(tab[i]);
tab[i] = ft_strcpy(tab[i], curs->name);
tab[i] = ft_strcat(tab[i], "=");
tab[i] = ft_strcat(tab[i], curs->value);
i++;
}
curs = curs->next;
}
return (tab);
}
int next_two(t_cmd * cmd)
{
while (cmd && (cmd->type == 8 || cmd->type == 9))
cmd = cmd->next;
if (cmd->type == 2)
return (1);
return (0);
}
void do_proc(int read, int fd, char *path, t_cmd *cmd, t_env **env)
{
pid_t pid;
char **environ;
if (!(environ = convert_env_array(env)))
return ;
if ((pid = fork()) == 0)
{
handle_all_signals(0);
if (read != 0)
{
dup2(read, 0);
close(read);
}
if (fd != 1 && (cmd->type == 2 || cmd->type == 6 || cmd->type == 7 || ((cmd->type == 8 || cmd->type == 9) && next_two(cmd))))
{
dup2(fd, 1);
close(fd);
}
if (execve(path, cmd->arr, environ) == -1)
terminate_child(path);
// ft_free_tab(&environ);
//// как-то завернуть процесс на выход
}
else
wait(&pid);
if (read != 0)
close(read);
if (fd != 1 && fd != 2)
close(fd);
handle_all_signals(1);
set_free_null(&cmd->target);
ft_free_tab(environ);
environ = NULL;
}
static int check_isbuiltin(char *com)
{
if (ft_strequ(com, "cd"))
return 1;
if (ft_strequ(com, "echo"))
return 2;
if (ft_strequ(com, "exit"))
return 3;
if (ft_strequ(com, "setenv"))
return 4;
if (ft_strequ(com, "unset"))
return 5;
if (ft_strequ(com, "ppid"))
return 6;
if (ft_strequ(com, "type"))
return 7;
if (ft_strequ(com, "pwd"))
return 8;
if (ft_strequ(com, "set"))
return 9;
if (ft_strequ(com, "export"))
return 10;
return 0;
}
int exec_builtin(char **com, t_env **env, int fd, int num)
{
if (num == 1)
return (sh_cd(com, env));
if (num == 2)
return (sh_echo(com, env, fd, 1));
if (num == 3)
return (sh_exit());
if (num == 4)
return (sh_setenv(com, env, 1));
if (num == 5)
return (sh_unset(com, env, fd));
if (num == 6)
return (display_id_kid_parent());
if (num == 7)
return (sh_type(com, env));
if (num == 8)
return (sh_pwd(com, env));
if (num == 9)
return (sh_set(com, env));
if (num == 10)
return (sh_export(com, env));
return (1);
}
int get_fd_write(t_cmd *cmd)
{
int fd;
t_cmd *cur;
fd = 0;
cur = cmd;
while ((cur->type == 6 || cur->type == 7 || cur->type == 8 || cur->type == 9) && cur->next)
{
if (cur->type == 7)
fd = open(cur->next->arr[0], O_CREAT | O_RDWR | O_APPEND,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (cur->type == 6)
fd = open(cur->next->arr[0], O_CREAT | O_RDWR | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (cur->type == 8 || cur->type == 9)
fd = open(cur->next->arr[0], O_RDONLY);
if (cur->next->type == 6 || cur->next->type == 7)
close(fd);
cur = cur->next;
}
return (fd);
}
static int get_cmd_type(t_cmd *cmd, int fd)
{
while (cmd && (cmd->type == 8 || cmd->type == 9))
cmd = cmd->next;
if (cmd->type == 2)
return (fd);
return (1);
}
void what_about_file(t_cmd *cmd)
{
t_cmd *cur;
struct stat buf;
int fd;
cur = cmd;
if (cur->type == 2)
{
while (cur->type == 2)
cur = cur->next;
}
if (cur->type == 6 || cur->type == 7)
{
while (cur->type == 6 || cur->type == 7)
cur = cur->next;
ft_putendl(cur->arr[0]);
if (stat(cur->arr[0], &buf) == -1)
{
ft_putendl(cur->arr[0]);
fd = open(cur->arr[0], O_CREAT | O_RDWR | O_APPEND,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
close(fd);
}
}
}
int execute(t_cmd *cmd, t_env **env, t_yank *buf)
{
int read;
int fd[2];
pid_t pid;
t_cmd *head;
int builtin;
int wfd;
fd[0] = 0;
fd[1] = 1;
int res;
wfd = 1;
res = 1;
head = cmd;
read = 0;
builtin = 0;
int ffd;
ffd = 1;
//create_file_is_it_doent_exist(cmd);
if (!cmd->arr || !cmd->arr[0])
return 1;
while (cmd)
{
if (cmd->type == 6 || cmd->type == 7 || cmd->type == 2)
what_about_file(cmd);
if (cmd->type == 6 || cmd->type == 7)
wfd = get_fd_write(cmd);
if ((builtin = check_isbuiltin(cmd->arr[0])) != 0)
{
if ((cmd->type == 6 || cmd->type == 7) && wfd != 1)
ffd = wfd;
if (cmd->type == 2)
{
pipe(fd);
ffd = fd[1];
close(fd[0]);
}
if (cmd->type != 2 && cmd->type != 7 && cmd->type != 6)
ffd = 1;
res = exec_builtin(cmd->arr, env, ffd, builtin);
}
else
{
cmd->target = get_path(cmd->arr[0], env);
if (cmd->target != NULL && cmd->type == 2)
{
pipe(fd);
do_proc(read, fd[1], cmd->target, cmd, env);
close(fd[1]);
}
if (cmd->target != NULL && (cmd->type == 1 || cmd->type == 0))
do_proc(read, wfd, cmd->target, cmd, env);
if (cmd->target != NULL && (cmd->type == 6 || cmd->type == 7))
{
pipe(fd);
dup2(wfd, fd[1]);
do_proc(read, wfd, cmd->target, cmd, env);
close(wfd);
}
if (cmd->target != NULL && (cmd->type == 8 || cmd->type == 9))
{
pipe(fd);
read = get_fd_write(cmd);
wfd = get_cmd_type(cmd, fd[1]);
//dup2(read, fd[0]);
do_proc(read, wfd, cmd->target, cmd, env);
///if (cmd->type == 9)
///remove(cmd->next->arr[0]);
}
}
if (cmd->type == 6 || cmd->type == 7 || cmd->type == 8 || cmd->type == 9)
{
while (cmd->next && (cmd->type == 6 || cmd->type == 7 || cmd->type == 8 || cmd->type == 9))
cmd = cmd->next;
}
///if (fd[1])
///close(fd[1]);
//close(fd[0]);
if (cmd->type == 2)
read = fd[0];
if (wfd != 1 && wfd != 2 && wfd != 0)
close(wfd);
cmd = cmd->next;
}
if (read != 0)
close(read);
if (wfd != 1 && wfd != 2)
close (wfd);
if (fd[0] != 0)
close(fd[0]);
if (fd[1] != 1)
close(fd[1]);
return (res);
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
int t,l,i,flag;
char s[100001];
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
l=strlen(s);
flag=0;
if(l==4)
{
if(s[0]==s[2] && s[1]==s[3] && s[0]!=s[1])
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
else if(l==2 || l==3)
{
if(s[0]!=s[1])
{
printf("YES\n");
}
else
printf("NO\n");
}
else
{
for(i=0;i<l-4;i++)
{
if(s[i]==s[i+2] && s[i+1]==s[i+3] && s[i]!=s[i+1])
{
flag=1;
}
else
{
flag=0;
}
}
if(flag==1)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
}
return 0;
}
|
C
|
/*-----------------------------------------------------------------------------
CMEMC.C -- C memory management routines for use with FORTRAN.
Pieter G. Buning 13 December 1988
FORTRAN entry points:
SUBROUTINE GETARR(LENGTH,ARRAY,INDEX)
__REAL ARRAY(*)
Return an index into ARRAY representing LENGTH words of available
memory. Calls Unix MALLOC(3C).
LENGTH - Number of words of memory requested.
ARRAY - Base address such that ARRAY(INDEX) represents the first
element of the new space.
INDEX - Returned index into ARRAY for the first element of the new
space. If space could not be allocated, zero is returned
for INDEX.
SUBROUTINE GETIAR(LENGTH,ARRAY,INDEX)
__INTEGER ARRAY(*)
Return an index into ARRAY representing LENGTH words of available
memory. Calls Unix MALLOC(3C).
LENGTH - Number of words of memory requested.
ARRAY - Base address such that ARRAY(INDEX) represents the first
element of the new space.
INDEX - Returned index into ARRAY for the first element of the new
space. If space could not be allocated, zero is returned
for INDEX.
SUBROUTINE FREARR(LENGTH,ARRAY,INDEX)
__REAL ARRAY(*)
Free space starting at ARRAY(INDEX), previously allocated by GETARR.
Calls Unix FREE(3C).
LENGTH - Number of words of memory to be freed.
ARRAY - Base address such that ARRAY(INDEX) represents the first
element of the space to be freed.
INDEX - Index into ARRAY for the first element of the space to be
freed.
SUBROUTINE FREIAR(LENGTH,ARRAY,INDEX)
__INTEGER ARRAY(*)
Free space starting at ARRAY(INDEX), previously allocated by GETARR.
Calls Unix FREE(3C).
LENGTH - Number of words of memory to be freed.
ARRAY - Base address such that ARRAY(INDEX) represents the first
element of the space to be freed.
INDEX - Index into ARRAY for the first element of the space to be
freed.
SUBROUTINE TYPCHK
Checks length of a C pointer (void *) with the corresponding FORTRAN
length __NCHPTR from forttype.h. Also checks C types __int and
__float with FORTRAN lengths __NCHPWD and __NCHINT, all defined in
forttype.h.
-----------------------------------------------------------------------------*/
#include <stdlib.h>
#include "forttype.h"
#include "fortcall.h"
/* GETARR - Return an index into REAL ARRAY representing LENGTH words of
available memory. */
#ifdef FORTCALL_TR_US
void getarr_(length, array, index)
#endif
#ifdef FORTCALL_UC
void GETARR(length, array, index)
#endif
#ifdef FORTCALL_LC
void getarr(length, array, index)
#endif
#ifdef FORTCALL_DECL_REVARG
fortran getarr(index, array, length)
#endif
__int *length;
void **index;
__float *array;
{
size_t len;
void *ptr, *malloc();
long int iaddr_unit;
__float test[2];
/* Byte-addressable, word-addressable, or what? */
iaddr_unit = (long int)&test[1] - (long int)&test[0];
/* Whatever the addressing unit, MALLOC should take len in bytes. */
len = (size_t)(*length * sizeof(__float));
/* Call MALLOC. */
ptr = malloc(len);
if (ptr == 0)
*index = 0;
else
*index = (void *)(((long int)ptr - (long int)array)/iaddr_unit + 1);
return;
}
/* GETIAR - Return an index into INTEGER ARRAY representing LENGTH words of
available memory. */
#ifdef FORTCALL_TR_US
void getiar_(length, array, index)
#endif
#ifdef FORTCALL_UC
void GETIAR(length, array, index)
#endif
#ifdef FORTCALL_LC
void getiar(length, array, index)
#endif
#ifdef FORTCALL_DECL_REVARG
fortran getiar(index, array, length)
#endif
__int *length;
void **index;
__int *array;
{
size_t len;
void *ptr, *malloc();
long int iaddr_unit;
__int test[2];
/* Byte-addressable, word-addressable, or what? */
iaddr_unit = (long int)&test[1] - (long int)&test[0];
/* Whatever the addressing unit, MALLOC should take len in bytes. */
len = (size_t)(*length * sizeof(__int));
/* Call MALLOC. */
ptr = malloc(len);
if (ptr == 0)
*index = 0;
else
*index = (void *)(((long int)ptr - (long int)array)/iaddr_unit + 1);
return;
}
/* FREARR - Free space starting at REAL ARRAY(INDEX), previously
allocated by GETARR. */
#ifdef FORTCALL_TR_US
void frearr_(length, array, index)
#endif
#ifdef FORTCALL_UC
void FREARR(length, array, index)
#endif
#ifdef FORTCALL_LC
void frearr(length, array, index)
#endif
#ifdef FORTCALL_DECL_REVARG
fortran frearr(index, array, length)
#endif
__int *length;
void **index;
__float *array;
{
void *ptr;
long int iaddr_unit;
__float test[2];
/* Byte-addressable, word-addressable, or what? */
iaddr_unit = (long int)&test[1] - (long int)&test[0];
ptr = (void *)(((long int)*index - 1)*iaddr_unit + (long int)array);
/* Call FREE. */
free(ptr);
return;
}
/* FREIAR - Free space starting at INTEGER ARRAY(INDEX), previously
allocated by GETARR. */
#ifdef FORTCALL_TR_US
void freiar_(length, array, index)
#endif
#ifdef FORTCALL_UC
void FREIAR(length, array, index)
#endif
#ifdef FORTCALL_LC
void freiar(length, array, index)
#endif
#ifdef FORTCALL_DECL_REVARG
fortran freiar(index, array, length)
#endif
__int *length;
void **index;
__int *array;
{
void *ptr;
long int iaddr_unit;
__int test[2];
/* Byte-addressable, word-addressable, or what? */
iaddr_unit = (long int)&test[1] - (long int)&test[0];
ptr = (void *)(((long int)*index - 1)*iaddr_unit + (long int)array);
/* Call FREE. */
free(ptr);
return;
}
/* TYPCHK - Check the length of a C pointer (void *) with the
corresponding FORTRAN length __NCHPTR from forttype.h. */
#ifdef FORTCALL_TR_US
void typchk_()
#endif
#ifdef FORTCALL_UC
void TYPCHK()
#endif
#ifdef FORTCALL_LC
void typchk()
#endif
#ifdef FORTCALL_DECL_REVARG
fortran typchk()
#endif
{
int exit_flag;
int c_pointer_length,fortran_pointer_length;
int c_int_length,fortran_int_length;
int c_float_length,fortran_float_length;
exit_flag = 0;
c_pointer_length = sizeof(void *);
fortran_pointer_length = __NCHPTR;
c_int_length = sizeof(__int);
fortran_int_length = __NCHINT;
c_float_length = sizeof(__float);
fortran_float_length = __NCHPWD;
/* Check the pointer lengths. */
if (c_pointer_length != fortran_pointer_length) {
printf("\n ** ERROR FROM CMEMC ROUTINE TYPCHK **\n");
printf( " FORTRAN AND C POINTER TYPES DO NOT MATCH\n");
printf("\n C POINTER LENGTH (sizeof(void *)) IS %d\n",
c_pointer_length);
printf("\n FORTRAN POINTER LENGTH (__NCHPTR, length of type ");
printf( "__POINTER from forttype.h) IS %d\n",
fortran_pointer_length);
exit_flag = 1;
}
/* Check the int lengths. */
if (c_int_length != fortran_int_length) {
printf("\n ** ERROR FROM CMEMC ROUTINE TYPCHK **\n");
printf( " FORTRAN AND C INTEGER TYPES DO NOT MATCH\n");
printf("\n C INTEGER LENGTH (sizeof(__int)) IS %d\n",
c_int_length);
printf("\n FORTRAN INTEGER LENGTH (__NCHINT, length of type ");
printf( "__INTEGER from forttype.h) IS %d\n",
fortran_int_length);
exit_flag = 1;
}
/* Check the float lengths. */
if (c_float_length != fortran_float_length) {
printf("\n ** ERROR FROM CMEMC ROUTINE TYPCHK **\n");
printf( " FORTRAN AND C FLOAT TYPES DO NOT MATCH\n");
printf("\n C FLOAT LENGTH (sizeof(__float)) IS %d\n",
c_float_length);
printf("\n FORTRAN REAL LENGTH (__NCHPWD, length of type ");
printf( "__REAL from forttype.h) IS %d\n",
fortran_float_length);
exit_flag = 1;
}
/* If things do not match, we have to quit. */
if (exit_flag != 0) exit(exit_flag);
return;
}
|
C
|
#include <stdio.h>
#include <string.h>
main()
{ char c[50],*str;
strcpy(c,"How are you?");
str="Fine,thank you!";
puts(c);
puts(str);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void output(const char *pszInput)
{
char szBuffer[1024];
if (pszInput)
strcpy(szBuffer, pszInput);
printf("Your parmeter is \"%s\"\r\n", szBuffer);
}
void foo(const char *pszInput)
{
char *p = malloc(strlen(pszInput));
//we don't want to print a null string.
//output(p);
output(pszInput);
}
int main(int argc, char *argv[])
{
if (argc > 1)
//foo in a non-returned function.
// return foo(argv[1]);
foo(argv[1]);
return 0;
}
|
C
|
/*
* File: main.c
* Author: Oscar
*
* Created on 21 de Dezembro de 2017, 14:19
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
int num;
printf("Introduza o seu numero: ");
scanf("%d", &num);
if (num %2 == 0){
printf("Numero %d Par",num);
}else {
printf("Numero %d Impar",num);
}
return (EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
char *string_concat(char *, char *);
int main()
{
char concat[32] = "Holberton ";
char *s;
s = string_concat(concat, "School!");
printf("%s\n", s);
return (0);
}
|
C
|
#include "binary_trees.h"
/**
* create_alv_node - create a node for a binary tree
* @n: value to insert in the node
* Return: a node on succes
*/
avl_t *create_alv_node(int n)
{
avl_t *new_node = NULL;
new_node = malloc(sizeof(avl_t));
if (!new_node)
return (NULL);
new_node->n = n;
new_node->parent = NULL;
new_node->left = NULL;
new_node->right = NULL;
return (new_node);
}
/**
* make_binary_tree - make the avl binary tree
* @array: list of number to convert to b_tree
* @first: index of the first num in the list
* @last: index of the last num in the list
* @parent: pointer with the parent address
* @or: n--neutro, l--left, r--right position
* Return: a pointer head of the tree in succes, NULL otherwise
*/
avl_t *make_binary_tree(int *array, size_t first, size_t last,
avl_t *parent, char or)
{
avl_t *new_node = NULL, *last_node = NULL;
if (last - first > 1)
{
new_node = create_alv_node(array[(int)((last + first) / 2) - 1]);
new_node->parent = parent;
if (or == 'l')
parent->left = new_node;
else if (or == 'r')
parent->right = new_node;
make_binary_tree(array, first, (int)((last + first) / 2) - 1, new_node, 'l');
make_binary_tree(array, (int)((last + first) / 2) + 1, last, new_node, 'r');
}
else if (last - first == 1)
{
new_node = create_alv_node(array[last - 1]);
last_node = create_alv_node(array[first - 1]);
if (or == 'l')
{
parent->left = last_node, last_node->parent = parent;
new_node->parent = last_node, last_node->right = new_node;
}
else if (or == 'r')
{
parent->right = last_node, last_node->parent = parent;
new_node->parent = last_node, last_node->right = new_node;
}
}
else
{
new_node = create_alv_node(array[last - 1]);
new_node->parent = parent;
if (or == 'l')
parent->left = new_node;
else if (or == 'r')
parent->right = new_node;
}
return (new_node);
}
/**
* sorted_array_to_avl - convert a sorted array to an avl b_tree
* @array: sorted list of numbers
* @size: size of the array
* Return: a pointer head of the tree in succes, NULL otherwise
*/
avl_t *sorted_array_to_avl(int *array, size_t size)
{
avl_t *new_node = NULL, *last_node = NULL;
if (!array || size == 0)
return (NULL);
if (size == 1)
{
new_node = create_alv_node(array[0]);
return (new_node);
}
if (size == 2)
{
new_node = create_alv_node(array[1]);
last_node = create_alv_node(array[0]);
last_node->right = new_node, new_node->parent = last_node;
return (last_node);
}
return (make_binary_tree(array, 1, size, NULL, 'n'));
}
|
C
|
#include<stdio.h>
int main()
{
long long unsigned int num,fact,subs,temp;
scanf("%llu",&num);
if(num==1 || num == 0)
{
printf("1");
return 0;
}
/*
For an even number say 8
8! = 8*7*6*5*4*3*2*1
which is equal to
8! = 8*(7*2)*(6*3)*(5*4)
8! = 8*(8+6)*(14+4)*(18+2)
For an odd number say 7
7! = 7*6*5*4*3*2*1
which is equal to
7! = 7*(6*2)*(5*3)*4
7! = 7*(7+5)*(12+3)*ceil(7/2)
*/
subs=num-2;
fact=num;
temp=fact;
while(subs>=2)
{
temp=temp+subs;
fact*=temp;
subs-=2;
}
/* If number is odd multiply it with roundUp(num/2) */
if(num%2!=0)
fact*=(num/2+1);
printf("%llu",fact);
}
|
C
|
#include "special_Math_Functions.h"//mention .h file
#include <stdio.h>
#include <math.h>
void math_Functions()
{
static double result;
do
{
int select_option;
double input;
printf("Please choose only one option for special math functions:\n");//choose the operations
printf(" 1. logarithm calculation\n 2. exponent calculation\n 3. squareroot calculation\n");//operations
scanf("%d",&select_option);
switch(select_option)//using switch case
{
case 1 :
printf("Please enter the input value:\n");
scanf("%lf",&input);
result = logarithm(input);
printf("logarithm of %lf is %.2f\n",input,result);
break;
case 2 :
printf("Please enter the input value:\n");
scanf("%lf",&input);
result = exponent(input);
printf("exponent of %lf is %.2f\n",input,result);
break;
case 3 :
printf("Please enter the input value:\n");
scanf("%lf",&input);
result = squareroot(input);
printf("squareroot of %lf is %.2f\n",input,result);
break;
default:
printf("Invalid input!!! Please choose the correct option\n");
break;
}
}while(1);
}
double logarithm(double input)//logarithm function
{
double log_value;
log_value = log10(input);
return log_value;
}
double exponent(float input)//exponent function
{
double exp_value;
exp_value = exp(input);
return exp_value;
}
double squareroot(double input)//squareroot function
{
double sqrt_value;
sqrt_value = sqrt(input);
return sqrt_value;
}
|
C
|
#include<stdio.h>
int main(){
int i,j,sum=0,n;
int ar[20],tm[20];
int disk; //initialising disk variable
printf("Enter number of location \t");
scanf("%d",&n);
printf("Enter position of head \t");
scanf("%d",&disk);
printf("Enter elements of disk queue \n");
for(i=0;i<n;i++){
scanf("%d",ar[i]);//takes input from user about elements in disk queue,that is to be served disk memory
tm[i]=disk-ar[i];//dist bw disk head and task
if(tm[i]<0){tm[i]=ar[i]-disk;}
disk=ar[i];//move the header to the task
sum=sum+tm[i];/*total movement*/}
printf("No. of total cylinder moved is %d",sum);
return 0;
}
|
C
|
#include "mercury_queue.h"
#include "mercury_test_config.h"
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
hg_queue_t *queue = NULL;
int ret = EXIT_SUCCESS;
int value1 = 10, value2 = 20;
(void) argc;
(void) argv;
queue = hg_queue_new();
if (!hg_queue_is_empty(queue)) {
fprintf(stderr, "Error: queue should be empty\n");
ret = EXIT_FAILURE;
goto done;
}
hg_queue_push_head(queue, (hg_queue_value_t) &value1);
if (value1 != *((int *) hg_queue_peek_head(queue))) {
fprintf(stderr, "Error: values do not match\n");
ret = EXIT_FAILURE;
goto done;
}
if (hg_queue_is_empty(queue)) {
fprintf(stderr, "Error: queue should not be empty\n");
ret = EXIT_FAILURE;
goto done;
}
hg_queue_push_tail(queue, (hg_queue_value_t) &value2);
if (value2 != *((int *) hg_queue_peek_tail(queue))) {
fprintf(stderr, "Error: values do not match\n");
ret = EXIT_FAILURE;
goto done;
}
if (value2 != *((int *) hg_queue_pop_tail(queue))) {
fprintf(stderr, "Error: values do not match\n");
ret = EXIT_FAILURE;
goto done;
}
if (value1 != *((int *) hg_queue_pop_head(queue))) {
fprintf(stderr, "Error: values do not match\n");
ret = EXIT_FAILURE;
goto done;
}
if (!hg_queue_is_empty(queue)) {
fprintf(stderr, "Error: queue should be empty\n");
ret = EXIT_FAILURE;
goto done;
}
done:
hg_queue_free(queue);
return ret;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int isKeyword(char buffer[]){
char keywords[32][10] = {"auto","break","case","char","const","continue","default",
"do","double","else","enum","extern","float","for","goto",
"if","int","long","register","return","short","signed",
"sizeof","static","struct","switch","typedef","union",
"unsigned","void","volatile","while"};
int i, flag = 0;
for(i = 0; i < 32; ++i){
if(strcmp(keywords[i], buffer) == 0){
printf("\n %s , KEYWORD",buffer);
flag = 1;
break;
}
return flag;
}
}
char isArithOp(char ch)
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/')
{
return ch;
}
else
return '@';
}
char isRelOp(char ch)
{
if(ch=='<'){
//ch=buffer[i];
return ch;
}
else if(ch=='>')
{
//ch=buffer[i];
return ch;
}
else if(ch=='=')
{
//ch=buffer[i];
return ch;
}
else{
ch='@';
return ch;
}
}
char isLogOp(char ch)
{
if(ch=='&'){
//ch=buffer[i];
return ch;
}
else if(ch=='!')
{
//ch=buffer[i];
return ch;
}
else if(ch=='|')
{
//ch=buffer[i];
return ch;
}
else{
ch='@';
return ch;
}
}
char isSpecialSymbol(char ch)
{
if(ch=='#'||ch=='/'||ch==':'||ch==';'||ch=='{'||ch=='}'||ch=='('||ch==')'||ch=='['||ch==']'||ch==',')
{
return ch;
}
return '@';
}
char isIdentifier(char ch){
if(isalpha(ch)){
return ch;
}
}
int main(){
char ch,buffer[10];
FILE *fp;
int i,j=0;
fp = fopen("program.txt","r");
if(fp == NULL){
printf("\nerror while opening the file\n");
exit(0);
}
while((ch = fgetc(fp)) != EOF){
if(isArithOp(ch)!='@'){
printf("\n %c , ARITHMETIC_OPERATOR\n",ch);
}
if(isRelOp(ch)!='@'){
printf("\n %c , RELATIONAL_OPERATOR\n",ch);
}
if(isLogOp(ch)!='@'){
printf("\n %c , LOGICAL_OPERATOR\n",ch);
}
if(isSpecialSymbol(ch)!='@'){
printf("\n %c , SPECIAL_SYMBOL\n",ch);
}
if(isIdentifier(ch)!='@'){
printf("\n %c , IDENTIFIER\n",ch);
}
if(isalnum(ch)){
buffer[j++] = ch;
}
if((ch == ' ' || ch == '\n') && (j != 0)){
buffer[j] = '\0';
j = 0;
if(isKeyword(buffer) == 0)
;
else
;
}
}
fclose(fp);
return 0;
}
|
C
|
/* main.c - main */
#include <xinu.h>
pid32 senderID,receiverID;
sid32 sendsem,receivesem;
int32 CQfull(pid32);
int32 CQempty(pid32);
int32 CQcount(pid32);
void CQinsert(pid32,int32);
int32 CQdelete(pid32);
void receiver(sid32 , sid32 );
void sender(sid32 , sid32 );
int32 CQfull(pid32 pid)
{ struct procent *prptr; /* Ptr to process’ table entry */
prptr = &proctab[pid]; /* Function to Check Circular Queue Full */
if( (prptr->f==prptr->r+1) || (prptr->f == 0 && prptr->r== SIZE-1)) return 1;
return 0;
}
int32 CQempty(pid32 pid)
{ struct procent *prptr; /* Ptr to process’ table entry */
prptr = &proctab[pid]; /* Function to Check Circular Queue Empty */
if(prptr->f== -1) return 1;
return 0;
}
void CQinsert(pid32 pid,int32 elem)
{ struct procent *prptr; /* Ptr to process’ table entry */
prptr = &proctab[pid]; /* Function for Insert operation */
if(prptr->f==-1)prptr->f=0;
prptr->r=(prptr->r+1) % SIZE;
prptr->prmsgs[prptr->r]=elem;
}
int32 CQdelete(pid32 pid)
{ struct procent *prptr; /* Ptr to process’ table entry */
prptr = &proctab[pid]; /* Function for Delete operation */
int32 elem;
elem=prptr->prmsgs[prptr->f];
if(prptr->f==prptr->r){ prptr->f=-1; prptr->r=-1;} /* Q has only one element ? */
else
prptr->f=(prptr->f+1) % SIZE;
return(elem);
}
void sender(sid32 sendsem, sid32 receivesem)
{
int32 i = 0;
while( i<20 ){
wait(sendsem);
sendMsg(receiverID, i);
kprintf("%d msg sent to process %d\n", i, receiverID);
i++;
signal(receivesem);
}
}
void receiver(sid32 sendsem, sid32 receivesem)
{
int32 i = 0;
while( i<20 )
{
wait(receivesem);
kprintf("received msg %d\n",receiveMsg());
i++;
signal(sendsem);
}
}
/* function to initialize the front rear and msgcount of the process entry */
void initialize_proctab(int32 id){ // id - process id of the process entry to be initialized
struct procent * entry;
entry = &proctab[id];
entry->f = -1;
entry->r = -1;
entry->prmsgcount = 0;
}
process main(void)
{
kprintf("The main has executed\n");
recvclr();
sendsem = semcreate(1);
receivesem = semcreate(0);
senderID = create(sender, 1024, 20, "process 1", 2, sendsem,receivesem);
initialize_proctab(senderID) ;
receiverID = create(receiver, 1024, 20, "process 2", 2, sendsem,receivesem);
initialize_proctab(receiverID);
resume( senderID );
resume( receiverID );
return OK;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char* argv[])
{
FILE* archivo1;
FILE* archivo2;
char c;
archivo1 = fopen(argv[1], "r");
archivo2 = fopen(argv[2], "w");
if (archivo1 == NULL || archivo2 == NULL)
{
printf ("Error al abrir los archivos\n");
return 1;
}
do
{
c = getc(archivo1);
if (c == 'a')
{
putc('e', archivo2);
}
else
{
putc(c, archivo2);
}
}
while (c != EOF);
fclose(archivo1);
fclose(archivo2);
return 0;
}
|
C
|
#include <stdio.h>
int isPrime(int n,int divisor);
int main (void)
{
int num = 0;
printf("Ingrese un número entero: ");
scanf("%d",&num);
int div = num/2;
if(isPrime(num,div) == 1)
{
printf("El numero %d es primo\n", num);
}
else
{
printf("El numero %d no es primo\n", num);
}
return -1;
}
int isPrime( int n,int divisor)
{
if(divisor == 1)
{
return 1;
}
else if ((n%divisor)==0)
{
return 0;
}
else
{
isPrime(n,divisor-1);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
int main (){
double salFixo, totVendas, totReceber;
char nome[20];
scanf("%c", &nome);
gets(nome);
scanf("%lf", &salFixo);
scanf("%lf", &totVendas);
totReceber = salFixo + (totVendas * 0.15);
printf("TOTAL = R$ %.2lf\n", totReceber);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.