language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | #include "holberton.h"
/**
* _strcat - Function to return NULL.
* @dest: String to be recieved as argument (destiny).
* @src: String to be recieved as argument (source).
* Return: Always NULL.
*/
char *_strcat(char *dest, char *src)
{
return (NULL);
}
|
C | #include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
int fd_open,fd_open_creat,fd_creat;
if((fd_open=open("1.c",O_RDONLY))==-1)
{
perror("open");
exit(EXIT_FAILURE);
}
printf("(此文件已存在(只读打开1.c))\nthe one file's descriptor is:%d\n\n",fd_open);
char s[20],s1[20];
printf("(fd_open_creat)请输入文件名(此文件不存在):");
scanf("%s",s);
if((fd_open_creat=open(s,O_CREAT|O_EXCL,0644))==-1)
{
perror("open");
exit(EXIT_FAILURE);
}
printf("the two file's descriptor is:%d\n\n",fd_open_creat);
printf("(fd_creat)请输入文件名(此文件不存在(若存在会清空内容重新创建)):");
scanf("%s",s1);
if((fd_creat=creat(s1,0644))==-1)
{
perror("creat");
exit(EXIT_FAILURE);
}
printf("the three file's descriptor is:%d\n",fd_creat);
close(fd_open);
close(fd_open_creat);
close(fd_creat);
}
|
C | #include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void) {
int x, i, max;
int tab[10];
srand(time(NULL));
i = 0;
while (i < 10) {
x = (rand() % 100 - 50);
tab[i] = x;
printf("%d ", tab[i]);
i++;
}
i = 0;
max = tab[0];
while (i < 10) {
if (tab[i] > max)
max = tab[i];
i++;
}
printf("\n%d\n", max);
return EXIT_SUCCESS;
}
|
C | #pragma once //ֹͷļظ
#include <stddef.h>
#define SeqListMaxNum 1000 //Ԫظ
typedef char SeqListType; //ض
typedef struct SeqList
{
SeqListType SeqListArr[SeqListMaxNum];
size_t size; //Ԫظ
}SeqList;
void SeqListInit(SeqList* seq); //ʼ˳
void SeqListPrint(SeqList* seq, const char* ch); //ӡ˳
void SeqListPushEnd(SeqList* seq, SeqListType value); //βһԪ
void SeqListPopEnd(SeqList* seq); // βɾһԪ
void SeqListPushStart(SeqList* seq, SeqListType value); //ͷһԪ
void SeqListPopStart(SeqList* seq); //ͷɾһԪ
void SeqListPushPosition(SeqList* seq, size_t pos, SeqListType value); //±ΪposԪ
void SeqListPopPosition(SeqList* seq, size_t pos); //ɾ±ΪposԪ
void SeqListSetList(SeqList* seq, size_t pos, SeqListType value); //±ΪposԪ
SeqListType SeqListGetList(SeqList* seq, size_t pos); //±ΪposԪ
size_t SeqListGetpos(SeqList* seq, SeqListType value); //valueԪֵ±
void SeqListRemove(SeqList* seq, SeqListType to_delete); //ɾֵָĵһ
void SeqListRemoveAll(SeqList* seq, SeqListType to_delete); //ɾֵֵָ
size_t SeqListSize(SeqList* seq); //ȡ˳Ԫظ
int SeqListEmpty(SeqList* seq); //ж˳Ƿǿձ
void SeqListBubbleSort(SeqList* seq); //ð
void SeqListBubbleSortEx(SeqList* seq, int(*cmp)(SeqListType, SeqListType)); //ûصð
void SeqListSelectSort(SeqList* seq); //
size_t SeqListBinarySearch(SeqList* seq, SeqListType value); //ֲ
void SeqListDestroy(SeqList* seq); //˳
|
C | #include<stdio.h>
void main()
{
int i,j;
for(i=5;i>0;i--)
{
printf("%d\t%d\t%d\t%d\t%d\t%d\t",i*10+0,i*10+1,i*10+2,i*10+3,i*10+4,i*10+5);
}
}
|
C | #include <stdio.h>
#include <math.h>
int fibonacci(int N)
{
if (N == 1 || N == 2)
return 1;
return fibonacci(N-1)+fibonacci(N-2);
}
int main()
{
int N;
printf("Please, enter number N:");
scanf("%d", &N);
for ( int i = 1; i <= N; i++)
printf("%d ", fibonacci(i));
printf("\n");
return 0;
}
|
C | /*************************************************************************
> File Name: c.c
> Author: Stomach_ache
> Mail: [email protected]
> Created Time: 2013年12月07日 星期六 16时09分44秒
************************************************************************/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max(x, y) ((x) > (y) ? (x) : (y))
int n, m;
int a[5005];
int cmp(const void *x, const void *y) {
return (*(int*)x) - (*(int*)y);
}
int main(void) {
while (~scanf("%d %d", &n, &m)) {
int i, j;
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
qsort(a, n, sizeof(int), cmp);
int mx = -1;
for (i = 0, j = 0; i < n; i = j) {
while (j < n && a[j] == a[i]) j++;
mx = max(mx, j - i);
}
if (mx <= n - mx)
printf("%d\n", n);
else
printf("%d\n", 2 * (n - mx));
for (i = 0; i < n; i++)
printf("%d %d\n", a[i], a[(i + mx) % n]);
}
return 0;
}
|
C | /*
* Timer.c
*
* Created: 5/17/2021 9:47:22 PM
* Author: Moustafa Moubarak
*/
#include "Timer.h"
#include <avr/interrupt.h>
uint32 NUM_OVF_0 = 0;
uint8 INIT_VALUE_0 = 0;
uint32 NUM_OVF_1 = 0;
uint32 INIT_VALUE_1 = 0;
void(* PTR_0)(void);
void(* PTR_1)(void);
void Timer_Init(uint8 Timer)
{
switch(Timer)
{
case Timer0:
#if TIMER0_WAVEFORM_GEN_Mode == Normal
CLR_BIT(TCCR0, 3);
CLR_BIT(TCCR0, 6);
//Enable Global Interrupt
SET_BIT(SREG, 7);
//Enable Overflow Interrupt
SET_BIT(TIMSK, 0);
#elif TIMER0_WAVEFORM_GEN_Mode == CTC
SET_BIT(TCCR0, 3);
CLR_BIT(TCCR0, 6);
//Enable Global Interrupt
SET_BIT(SREG, 7);
//Enable Output Compare Match Interrupt
SET_BIT(TIMSK, 1);
#elif TIMER0_WAVEFORM_GEN_Mode == FAST_PWM
// Fast PWM Mode
SET_BIT(TCCR0, 3);
SET_BIT(TCCR0, 6);
// OC0 Pin Set to Output
DIO_SetPINDir(DIO_PORTB, DIO_PIN3, DIO_PIN_OUTPUT);
#if Timer0_PWM_WaveType == Non_Inverted
CLR_BIT(TCCR0, 4);
SET_BIT(TCCR0, 5);
#elif Timer0_PWM_WaveType == Inverted
SET_BIT(TCCR0, 4);
SET_BIT(TCCR0, 5);
#endif
#endif
break;
case Timer1:
#if TIMER1_WAVEFORM_GEN_Mode == Normal
CLR_BIT(TCCR1A,0);
CLR_BIT(TCCR1A,1);
CLR_BIT(TCCR1B,3);
CLR_BIT(TCCR1B,4);
//Enable Global Interrupt
SET_BIT(SREG, 7);
//Enable Overflow Interrupt
SET_BIT(TIMSK, 2);
#elif TIMER1_WAVEFORM_GEN_Mode == CTC
CLR_BIT(TCCR1A,0);
CLR_BIT(TCCR1A,1);
SET_BIT(TCCR1B,3);
CLR_BIT(TCCR1B,4);
//Enable Global Interrupt
SET_BIT(SREG, 7);
//Enable Output Compare Match Interrupt
SET_BIT(TIMSK, 4);
#elif TIMER1_WAVEFORM_GEN_Mode == FAST_PWM
// Mode5_Fast PWM 8bit
SET_BIT(TCCR1A,0);
CLR_BIT(TCCR1A,1);
SET_BIT(TCCR1B,3);
CLR_BIT(TCCR1B,4);
// OCR1A Pin Set to Output
DIO_SetPINDir(DIO_PORTD, DIO_PIN5, DIO_PIN_OUTPUT);
//Wave type Mode
#if Timer1_PWM_WaveType == Non_Inverted
CLR_BIT(TCCR1A, 6);
SET_BIT(TCCR1A, 7);
#elif Timer1_PWM_WaveType == Inverted
SET_BIT(TCCR1A, 6);
SET_BIT(TCCR1A, 7);
#endif
#endif
break;
default:
break;
}
}
void Timer_Start(uint8 Timer)
{
switch(Timer)
{
case Timer0:
#if TIMER0_PRESCALER == TIMER0_NO_PRESCALLING
SET_BIT(TCCR0, 0);
CLR_BIT(TCCR0, 1);
#elif TIMER0_PRESCALER == TIMER0_PRESCALER_8
SET_BIT(TCCR0, 1);
CLR_BIT(TCCR0, 0);
#elif TIMER0_PRESCALER == TIMER0_PRESCALER_64
SET_BIT(TCCR0, 0);
SET_BIT(TCCR0, 1);
#elif TIMER0_PRESCALER == TIMER0_PRESCALER_256
CLR_BIT(TCCR0, 0);
CLR_BIT(TCCR0, 1);
SET_BIT(TCCR0, 2);
#elif TIMER0_PRESCALER == TIMER0_PRESCALER_1024
SET_BIT(TCCR0, 0);
CLR_BIT(TCCR0, 1);
SET_BIT(TCCR0, 2);
#endif
break;
case Timer1:
#if TIMER1_PRESCALER == TIMER1_NO_PRESCALLING
SET_BIT(TCCR1B, 0);
CLR_BIT(TCCR1B, 1);
#elif TIMER1_PRESCALER == TIMER1_PRESCALER_8
SET_BIT(TCCR1B, 1);
CLR_BIT(TCCR1B, 0);
#elif TIMER1_PRESCALER == TIMER1_PRESCALER_64
SET_BIT(TCCR1B, 0);
SET_BIT(TCCR1B, 1);
#elif TIMER1_PRESCALER == TIMER1_PRESCALER_256
CLR_BIT(TCCR1B, 0);
CLR_BIT(TCCR1B, 1);
SET_BIT(TCCR1B, 2);
#elif TIMER1_PRESCALER == TIMER1_PRESCALER_1024
SET_BIT(TCCR1B, 0);
CLR_BIT(TCCR1B, 1);
SET_BIT(TCCR1B, 2);
#endif
break;
default:
break;
}
}
void Timer_Stop(uint8 Timer)
{
switch(Timer)
{
case Timer0:
CLR_BIT(TCCR0, 0);
CLR_BIT(TCCR0, 1);
CLR_BIT(TCCR0, 2);
break;
case Timer1:
CLR_BIT(TCCR1B, 0);
CLR_BIT(TCCR1B, 1);
CLR_BIT(TCCR1B, 2);
break;
default:
break;
}
}
Set_CallBack(uint8 Timer,void(* p)(void))
{
switch(Timer)
{
case Timer0:
PTR_0 = p;
case Timer1:
PTR_1 = p;
}
}
void Timer_SetDelay(uint8 Timer, uint32 Delay_Ms)
{
switch(Timer)
{
case Timer0:
{
#if TIMER0_WAVEFORM_GEN_Mode == Normal
uint8 Tick_Time = (PRESCALER_FACTOR_T0/16);
uint32 Total_Ticks = ((Delay_Ms * 1000)/Tick_Time);
NUM_OVF_0 = Total_Ticks/OVF_Ticks_T0 ;
INIT_VALUE_0 = OVF_Ticks_T0 - (Total_Ticks % OVF_Ticks_T0);
TCNT0 = INIT_VALUE_0;
if(INIT_VALUE_0 != 0)
{
NUM_OVF_0++;
}
#elif TIMER0_WAVEFORM_GEN_Mode == CTC
if (Delay_Ms < 16)
{
uint8 Tick_Time = PRESCALER_FACTOR_T0 / 16;
uint32 Total_Ticks = (Delay_Ms * 1000) / Tick_Time;
OCR0 = Total_Ticks - 1;
}
#endif
break;
}
case Timer1:
{
#if TIMER1_WAVEFORM_GEN_Mode == Normal
uint8 Tick_Time = (PRESCALER_FACTOR_T1/16);
uint32 Total_Ticks = ((Delay_Ms * 1000)/Tick_Time);
NUM_OVF_1 = Total_Ticks/OVF_Ticks_T1 ;
INIT_VALUE_1 = OVF_Ticks_T1 - (Total_Ticks % OVF_Ticks_T1);
TCNT1 = INIT_VALUE_1;
if(INIT_VALUE_1 != 0)
{
NUM_OVF_1++;
}
#elif TIMER1_WAVEFORM_GEN_Mode == CTC
if (Delay_Ms < 4000)
{
uint8 Tick_Time = PRESCALER_FACTOR_T1 / 16;
uint32 Total_Ticks = (Delay_Ms * 1000) / Tick_Time;
OCR1A = Total_Ticks - 1;
}
#endif
break;
}
default:
break;
}
}
void PWM_Generate(uint8 Timer,uint16 Duty_Cycle)
{
switch(Timer)
{
case Timer0:
#if Timer0_PWM_WaveType == Non_Inverted
OCR0 = ((Duty_Cycle*OVF_Ticks_T0)/100)-1;
#elif Timer0_PWM_WaveType == Inverted
OCR0 = 255-((Duty_Cycle * OVF_Ticks_T0)/100);
#endif
break;
case Timer1:
#if Timer1_PWM_WaveType == Non_Inverted
OCR1A = ((Duty_Cycle * OVF_Ticks_T1)/100)-1;
#elif Timer1_PWM_WaveType == Inverted
OCR1A = 255-((Duty_Cycle * OVF_Ticks_T1)/100);
#endif
break;
default:
break;
}
}
ISR(TIMER0_OVF_vect)
{
static uint32 cnt = 0;
cnt++;
if(cnt == NUM_OVF_0)
{
cnt = 0;
(*PTR_0)();
TCNT0 - INIT_VALUE_0;
}
}
ISR(TIMER0_COMP_vect)
{
(*PTR_0)();
}
ISR(TIMER1_OVF_vect)
{
static uint32 cnt = 0;
cnt++;
if(cnt == NUM_OVF_1)
{
cnt = 0;
(*PTR_1)();
TCNT1 - INIT_VALUE_1;
}
}
ISR(TIMER1_COMPA_vect)
{
(*PTR_1)();
} |
C | #include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node * next;
};
struct Node * head = NULL;
void add(){
int value;
printf("Enter a Value:");
scanf("%d", &value);
struct Node * temp;
struct Node *nt = malloc(sizeof(struct Node));
nt->data = value;
nt->next = NULL;
if(head == NULL){
head = nt;
}else{
temp = head;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = nt;
}
printf("Node Added.\n");
}
void display(){
printf("LL :");
struct Node * temp;
temp = head;
do{
printf("%d-->", temp->data);
temp = temp->next;
}while(temp->next != NULL);
printf("%d-->NULL", temp->data);
}
int main()
{
int choice;
printf("Enter an Choice:\n1.Add , 2.Display, 3. Exit\n\n");
while(1){
printf("Enter Choice:");
scanf("%d", &choice);
switch(choice){
case 1:
add();
break;
case 2:
display();
break;
case 3:
return 0;
default:
printf("Wrong Option.");
}
}
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sudoku_solution_checker.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fbertoia <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/09/10 18:32:37 by fbertoia #+# #+# */
/* Updated: 2017/09/10 18:32:39 by fbertoia ### ########.fr */
/* */
/* ************************************************************************** */
int ft_end_test_column(int **sudoku, int y)
{
int x;
int tmp;
x = 0;
tmp = 1;
while (x < 9)
{
tmp = tmp * sudoku[x][y];
x++;
}
if (tmp == 362880)
return (1);
return (0);
}
int ft_end_test_line(int **sudoku, int x)
{
int y;
int tmp;
y = 0;
tmp = 1;
while (y < 9)
{
tmp = tmp * sudoku[x][y];
y++;
}
if (tmp == 362880)
return (1);
return (0);
}
int ft_end_test_box(int **sudoku, int x, int y)
{
int i;
int j;
int tmp;
tmp = 1;
i = 0;
j = 0;
x = x - (x % 3);
y = y - y % 3;
while (i < 3)
{
while (j < 3)
{
tmp = tmp * sudoku[x + i][y + j];
j++;
}
j = 0;
i++;
}
if (tmp == 362880)
return (1);
return (0);
}
int ft_sudoku_solution_checker(int **sudoku, int position)
{
int x;
int y;
while (position <= 80)
{
x = position / 9;
y = position % 9;
if (ft_end_test_column(sudoku, y) == 0 ||
ft_end_test_line(sudoku, x) == 0 || ft_end_test_box(sudoku, x, y) == 0)
return (0);
position++;
}
return (1);
}
|
C | #include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
void write_fifo(void);
void read_fifo(void);
#define NAMEDPIPE_NAME "/tmp/my_named_pipe"
#define BUFSIZE 50
char buffer[] = "asdfasdfasdfasd";
int main() {
if (mkfifo(NAMEDPIPE_NAME, 0777)) {
perror("mkfifo");
abort();
}
switch (fork()) {
case -1:
perror("fork");
exit(1);
case 0:
read_fifo();
exit(EXIT_SUCCESS);
default:
write_fifo();
wait(NULL);
}
remove(NAMEDPIPE_NAME);
return EXIT_SUCCESS;
}
void write_fifo(void) {
int fd;
char buf[] = "asdfasdfasdfasd";
if ((fd = open(NAMEDPIPE_NAME, O_WRONLY)) <= 0) {
perror("open for write");
exit(EXIT_FAILURE);
}
if (write(fd, buf, sizeof(buf)) != sizeof(buf)) {
perror("write");
}
close(fd);
}
void read_fifo(void) {
int fd, len;
char buf[BUFSIZE];
if ((fd = open(NAMEDPIPE_NAME, O_RDONLY)) <= 0) {
perror("open for read");
exit(EXIT_FAILURE);
}
while ((len = read(fd, buf, BUFSIZE - 1)) == 0) {
}
if ((len = read(fd, buf, BUFSIZE - 1)) < 0) {
perror("read");
close(fd);
return;
}
assert(strcmp(buffer, buf) == 0);
} |
C | /* SPDX-License-Identifier: Apache-2.0 */
/*
* Copyright (C) 2014-2019 Intel Corporation
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <errno.h>
#include <stdint.h>
#include <stdbool.h>
#include <limits.h>
#include <ctype.h>
#include <linux/mei.h>
#include <metee.h>
#include "meiuuid.h"
struct params {
bool verbose;
uuid_le uuid;
int iterations;
};
static int work(struct params *p)
{
TEEHANDLE cl;
const unsigned char cmd[] = "AB";
const ssize_t sz = sizeof(cmd);
unsigned char *buf = NULL;
size_t rsz, wsz;
int i;
TEESTATUS status;
status = TeeInit(&cl, &p->uuid, NULL);
if (status != TEE_SUCCESS)
goto out;
status = TeeConnect(&cl);
if (status != TEE_SUCCESS)
goto out;
rsz = cl.maxMsgLen;
buf = (unsigned char *)malloc(rsz);
if (buf == NULL)
goto out;
memset(buf, 0, rsz);
for (i = 0; i < p->iterations; i++) {
status = TeeWrite(&cl, cmd , sz, &wsz, 0);
if (status != TEE_SUCCESS)
goto out;
if (wsz != sz) {
status = TEE_UNABLE_TO_COMPLETE_OPERATION;
goto out;
}
status = TeeRead(&cl, buf, rsz, NULL, 10000);
if (status != TEE_SUCCESS)
goto out;
}
out:
TeeDisconnect(&cl);
free(buf);
return status;
}
static void usage(const char *p)
{
fprintf(stdout, "%s: -u <uuid> [-i <iterations>] [-h]\n", p);
}
#define BIT(_x) (1L<<(_x))
#define UUID_BIT BIT(1)
#define ITER_BIT BIT(2)
static int mei_getopt(int argc, char *argv[], struct params *p)
{
unsigned long required = UUID_BIT;
unsigned long present = 0;
extern char *optarg;
int opt;
while ((opt = getopt(argc, argv, "hvu:i:")) != -1) {
switch (opt) {
case 'v':
p->verbose = true;
break;
case 'u':
present |= UUID_BIT;
if (mei_uuid_parse(optarg, &p->uuid) < 0)
return -1;
break;
case 'i':
present |= ITER_BIT;
p->iterations = strtoul(optarg, NULL, 10);
break;
case 'h':
case '?':
usage(argv[0]);
break;
}
}
if ((required & present) != required) {
usage(argv[0]);
return -1;
}
return 0;
}
int main(int argc, char *argv[])
{
struct params p;
int rc;
p.verbose = false;
p.uuid = NULL_UUID_LE;
p.iterations = 1;
#ifdef _WIN32
//p.uuid = ;
#else
rc = mei_getopt(argc, argv, &p);
if (rc) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
#endif /* _WIN32 */
rc = work(&p);
exit(rc);
}
|
C | /*************************************************************************
> File Name: my_lseek.c
> Author:
> Mail:
> Created Time: Mon 20 Jul 2015 10:57:56 CST
************************************************************************/
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
int main(int argc,char *argv[])
{
int fd,ret;
// char write_buf[40] = "yangbodongshitiancai";
char read_buf[40];
char write_buf[40];
int p;
if((fd = open("file2",O_RDWR|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR)) == -1)
{
perror("open");
exit(1);
}
printf("请输入要写入的内容\n");
scanf("%s",write_buf);
if( write(fd,write_buf,strlen(write_buf)) != strlen(write_buf))
{
perror("write");
exit(1);
}
// printf("write的返回值ret:%d\n",ret);
if((p =lseek(fd,3,SEEK_SET)) == -1)
{
perror("lseek");
exit(1);
}
printf("lseek函数的返回值p:%d \n",p);
if((ret =read(fd,read_buf,9) ) < 0)
{
perror("read");
exit(1);
}
printf("文件描述符fd:%d \n",fd);
printf("read函数的返回值ret:%d \n",ret);
printf("%s \n",read_buf);
for(ret=0;ret<=10;ret++)
printf("%d\n",read_buf[ret]);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define N 1000
struct nodes{
int number;
int value;
}nodes[N];
void remember_nodes(int number, int value){
int i = 0;
for (i = 1; i <= number; i++) {
if (nodes[i].value == value){
break;} else {
if (nodes[i].value == 0) {
nodes[i].value = value;
nodes[i].number = i;
break;
}
}
}
}
int check_node(int number,int value){
int i = 0;
for (i = 1; i <= number; i++) {
if (nodes[i].value == value){
return 1;
break;
} else { return 0; }
}
}
void print_nodes_and_values(int number){
int i = 0;
FILE *fp;
fp = fopen("gr1.txt","a");
for ( i = 1; i <= number; i++) {
fprintf(fp, "node%d [label = \" %d \" ];\n",nodes[i].number,nodes[i].value );
}
fclose(fp);
}
void print_connection(int count,int number1, int number2){
int i = 0;
int j = 0;
FILE *fp;
fp = fopen("gr1.txt","a");
for (i = 1; i <= count; i++) {
for (j = 1; j <= count; j++)
if ((number1 == nodes[i].number)&&(number2 == nodes[j].number)){
fprintf(fp, "node%d -- node%d; \n",nodes[i].number,nodes[j].number );
number1 = nodes[i].value;
number2 = nodes[j].value;
} //else { printf("Error \n");}
}
}
/*
void check_svaz(int number, int i){
if (number > 0.5*((i - 2)*(i - 1))){
printf("svaz\n");
} else {
printf("ne svaz \n");
}
}
*/
/*
int find_value(int num1, int num2,int count){
for (int i = 0; i < count; i++)
for (int j = 0; j < count; j++)
if ((num1 == nodes[i].number)&&(num2 == nodes[j].number)){
num1 = nodes[i].value;
num2 = nodes[j].value;
}
}
*/
int main(void) {
int value;
int connection1 = 1;
int i = 0;
int a = 0;
int connection2;
int number;
int k = 0;
int same = 0;
int* con1;
int* con2;
FILE *fp;
FILE *cashe;
fp = fopen("gr1.txt","w");
fprintf(fp, "%s\n","graph G {" );
fclose(fp);
fp = fopen("gr1.txt","a");
printf("Write number of nodes \n");
scanf("%d",&number);
con1 = (int*) calloc(pow(2,number),sizeof(int));
con2 = (int*) calloc(pow(2,number),sizeof(int));
printf("Write node's values: \n");
while (k < number) {
scanf("%d",&value);
remember_nodes(number, value);
if (check_node(number,value) == 0) {
k++;
}
}
k = 0;
print_nodes_and_values(number);
printf("\n Here Are you node's values: \n \n" );
printf("|number|value| \n");
for (i = 1; i <= number; i++) {
printf("| %d | %d | \n",(nodes[i].number), nodes[i].value);
}
i = 0;
printf("\n Write connections (write 0 to end)\n");
while ((connection1 != 0)&&(connection2 != 0)){
scanf("%d %d\n",&connection1,&connection2);
print_connection(number,connection1,connection2);
k++; if ((connection1 == 0)||(connection2 == 0)) {
}else{
// find_value(connection1, connection2,number);
for (int i = 0; i <= number; i++)
for (int j = 0; j <= number; j++)
if ((connection1 == nodes[i].number)&&(connection2 == nodes[j].number)){
connection1 = nodes[i].value;
connection2 = nodes[j].value;
}
con1[a] = connection1;
con2[a] = connection2;
a++;}
}
//check_svaz(number,i);
fclose(fp);
i = 0;
cashe = fopen("cashe1.txt","w");
while (con1[i]!=0) {
fprintf(cashe,"%d %d \n",con1[i],con2[i]);
i++;
}
fclose(cashe);
// system("dot -Tpng gr1.txt -o gr1.png");
// system("xdg-open gr1.png");
return 0;
}
|
C | #include "libmx.h"
void mx_print_unicode(wchar_t c) {
char output[5] = {0};
if (c < 0x80)
output[0] = (c >> 0 & 0x7F) | 0x00;
else if (c < 0x0800) { // < 2048
output[0] = (c >> 6 & 0x1F) | 0xC0;
output[1] = (c >> 0 & 0x3F) | 0x80;
}
else if (c < 0x010000) { // < 65536
output[0] = (c >> 12 & 0x0F) | 0xE0;
output[1] = (c >> 6 & 0x3F) | 0x80;
output[2] = (c >> 0 & 0x3F) | 0x80;
}
else { // < 1114112
output[0] = (c >> 18 & 0x07) | 0xF0;
output[1] = (c >> 12 & 0x3F) | 0x80;
output[2] = (c >> 6 & 0x3F) | 0x80;
output[3] = (c >> 0 & 0x3F) | 0x80;
}
write(1, output, mx_strlen(output));
}
|
C | #include <stdio.h>
int main()
{
int ara[5], i, j, count=0;
for(i=0; i<4; i++)
{
scanf(" %d", &ara[i]);
}
for(i=0; i<4; i++)
{
for(j=i+1; j<4; j++)
{
if((ara[i]==ara[j])&& ara[j]>0)
{
count++;
ara[j]=0;
}
}
}
printf("%d\n", count);
return 0;
}
|
C | //
// main.c
// queue_simulation
//
// Created by Bradley Morgan on 11/14/18.
// Copyright © 2018 BiT8. All rights reserved.
//
//
// this program simulates a queue using a circular array
// data structure to track arrivals and departures, i.e...
//
// departure<-[head][*][*][*][tail]<-arrival
//
// this data structure is used as an efficient way
// to simulate a queue at O(1) complexity (if implemented
// correctly)
//
// this implementation uses an arrival (packet) data structure
// and a queue data structure holding an array of these arrivals
//
// arrival rate (λ) and service rate (µ) are defined
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <math.h>
#include <unistd.h>
#include <string.h>
const int MAX_PACKETS = 10000;
const int MAX_QUEUE = 9;
const int MAX_SERVERS = 2;
const float TIME_ARRIVAL_MS = 100000.0;
const float TIME_SERVICE_MS = 200000.0;
struct packet {
int id;
int queue_position;
struct timeval arrival_time;
struct timeval departure_time;
};
struct queue {
char *id;
int head, tail;
int len, capacity, lost;
struct packet *array;
};
struct queue *init_queue(unsigned int capacity, char *qid) {
struct queue *queue = (struct queue *) malloc(sizeof(struct queue));
queue->id = qid;
queue->capacity = capacity;
queue->len = queue->lost = 0;
queue->head = queue->tail = 0;
queue->array = (struct packet *) malloc(queue->capacity * sizeof(struct packet));
return queue;
}
struct packet *init_packet(int id) {
struct packet *p = (struct packet *) malloc(sizeof(struct packet));
p->id = id;
return p;
}
int full(struct queue *q) {
return q->len >= q->capacity;
}
int empty(struct queue *q) {
return q->len == 0;
}
void display(struct queue *q) {
if (empty(q)) { printf("\n"); return; }
int i;
if(q->head < q->tail) {
for(i = q->head; i < q->tail; i++) {
printf("%d ", q->array[i].id);
}
} else {
for(i = q->head; i < q->capacity; i++) {
printf("%d ", q->array[i].id);
}
for(i = 0; i < q->tail; i++) {
printf("%d ", q->array[i].id);
}
}
printf("\n");
}
void enqueue(struct queue *q, struct packet *p) {
if(full(q)) { q->len = q->capacity; q->lost++; return; }
struct timeval t;
gettimeofday(&t, 0);
p->arrival_time = t;
q->array[q->tail] = *p;
q->tail = (q->tail + 1) % q->capacity;
q->len++;
printf("%s enqueued: 1 | head: %d | tail: %d | count %d | lost: %d | queue: ",q->id, q->head, q->tail, q->len, q->lost);
display(q);
}
void dequeue(struct queue *q) {
if(empty(q)) { q->len = 0; return; }
struct timeval t;
gettimeofday(&t, 0);
q->array[q->head].departure_time = t;
q->head = (q->head + 1) % q->capacity;
q->len--;
printf("%s dequeued: 1 | head: %d | tail: %d | count %d | lost: %d | queue: ",q->id, q->head, q->tail, q->len, q->lost);
display(q);
}
float factorial(float f) {
if ( f == 0.0 ) {
return 1.0;
}
float res = f * factorial(f - 1.0);
return res;
}
float calc_bp(float lambda, float mu) {
// for an m/m/c/k queue, load is arrival rate divided by the service rate
// multiplied by the number of servers ...
float load = lambda / (MAX_SERVERS * mu);
//float k = MAX_QUEUE * MAX_SERVERS;
float f1 = powf(load, MAX_SERVERS) / factorial(MAX_SERVERS);
printf("\nload: %3.5f, f1: %3.5f ", load, f1);
float f2 = 0.0;
int i;
for (i = 0; i <= MAX_SERVERS; i++) {
f2 += (powf(load, i) / factorial(i));
}
float f3 = f1 / f2;
printf(" f2: %3.5f, f3: %3.5f", f2, f3);
return f3;
}
int main(int argc, const char * argv[]) {
// initialize the queues
calc_bp(TIME_ARRIVAL_MS, TIME_SERVICE_MS);
struct queue *q1 = init_queue(MAX_QUEUE, "1Q");
struct queue *q2 = init_queue(MAX_QUEUE, "2Q");
struct timespec start, end, t;
int i;
for(i = 0; i <= (q1->capacity - 1); i++) {
struct packet *p = init_packet(i);
enqueue(q1, p);
enqueue(q2, p);
}
for(i = 0; i <= (q1->capacity - 1); i++) {
dequeue(q1);
dequeue(q2);
}
clock_gettime(CLOCK_MONOTONIC, &start);
printf("\n*** start ***\n\n");
for(i = 0; i <= MAX_PACKETS; i++) {
int random_packet = rand() % MAX_SERVERS;
struct packet *p = init_packet(i);
do {
clock_gettime(CLOCK_MONOTONIC, &t);
} while(fmod(t.tv_nsec, TIME_ARRIVAL_MS) != 0.0 && fmod(t.tv_nsec, TIME_SERVICE_MS) != 0.0);
if(fmod(t.tv_nsec, TIME_SERVICE_MS) == 0.0) {
printf("DEPARTURE: %lu\n", t.tv_nsec);
dequeue(q1);
dequeue(q2);
}
if(fmod(t.tv_nsec, TIME_ARRIVAL_MS) == 0.0) {
printf("ARRIVAL: %lu\n", t.tv_nsec);
if(random_packet == 0) {
enqueue(q1, p);
} else {
enqueue(q2, p);
}
}
}
float blocking_probability = ((float)q1->lost + (float)q1->lost) / (float)MAX_PACKETS;
printf("λ,µ,ρ,bp,\n");
printf("%g,%g,%5.5f,%5.5f\n", TIME_ARRIVAL_MS, TIME_SERVICE_MS, (TIME_ARRIVAL_MS / (TIME_SERVICE_MS * 2.0)), blocking_probability);
printf("Blocking Probability (%d + %d / %d): %5.5f\n", q1->lost, q2->lost, MAX_PACKETS, blocking_probability);
clock_gettime(CLOCK_MONOTONIC, &end);
return 0;
}
|
C | #include <stdio.h>
#define MAX_WORD_LENGTH 10
// TODO, fix off-by one, then do vertical orientation next
int main(void)
{
int freqs[MAX_WORD_LENGTH + 1];
int c;
int currentWordLength = 0;
int j;
int i;
for (i = 1; i <= MAX_WORD_LENGTH; i++)
freqs[i] = 0;
while ((c = getchar()) != EOF)
{
if (c != ' ' && c != '\n' && c != '\t')
{
currentWordLength++;
}
else if (currentWordLength <= MAX_WORD_LENGTH)
{
freqs[currentWordLength]++;
currentWordLength = 0;
}
}
int maxFreq = 0;
for (i = 1; i <= MAX_WORD_LENGTH; i++)
{
if (freqs[i] > maxFreq)
{
maxFreq = freqs[i];
}
}
// printf("max freq is: %d", maxFreq);
for (i = maxFreq; i > 0; i--)
{
for (j = 1; j <= MAX_WORD_LENGTH; j++)
{
if (freqs[j] >= i)
{
printf(" X");
}
else
{
printf(" ");
}
}
printf("\n");
}
for (j = 1; j <= MAX_WORD_LENGTH; j++)
{
printf("%3d", j);
}
printf("\n");
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Ͽ ִ ܾ ִ
#define MAXWORD 1000
#define DELEMETERS " ,.!?\t\n"
// Լ
void initialize();
void read_file();
void move_downward(int);
void insert_data(int, const char *);
void print_words();
void deallocate();
void convert_lower(char *);
int linear_search(const char *, int *);
// ܾ ü
struct word_count {
char *str; // ܾ
int count; // ܾ Ÿ Ƚ
};
// ܾ 迭(ͷ )
struct word_count *words;
// 迭 Ǿ ִ ܾ
int nwords;
int main() {
initialize(); // ü 迭 Ҵϰ ʱȭ
read_file(); // Ͽ ܾ Ͽ words[]
print_words(); // words[] Ǿ ִ ܾ Ƚ
deallocate(); // Ҵ Ҹ
return 0;
}
void initialize() {
// ü 迭 Ҵϰ ʱȭ
words = (struct word_count *) malloc(sizeof(struct word_count) * MAXWORD);
memset(words, 0, sizeof(struct word_count) * MAXWORD);
nwords = 0;
}
void read_file() {
char buffer[256], *token;
int found, index;
FILE *fp = fopen("programming.txt", "r");
while (fgets(buffer, 255, fp)) {
token = strtok(buffer, DELEMETERS);
while (token) {
convert_lower(token);
index = linear_search(token, &found);
if (found) {
// ܾ ̹ ִٸ ش ܾ īƮ
words[index].count++;
}
else {
move_downward(index); // ܾ ĭ ڷ ű
insert_data(index, token); // ܾ ش ġ ߰.
}
token = strtok(NULL, DELEMETERS);
}
}
fclose(fp);
}
void move_downward(int index) {
// index ܾ ڷ ĭ ű
int n;
if (nwords < MAXWORD - 1) {
// ܾ 迭 ִ ʰ
for (n = nwords; n >= index; n--) {
// words[n + 1].str = words[n].str;
// words[n + 1].count = words[n].count;
words[n + 1] = words[n];
}
}
}
void insert_data(int index, const char *word) {
// index شϴ ġ word ߰
int size;
if (nwords < MAXWORD - 1) {
// ܾ 迭 ִ ʰ
size = strlen(word) + 1;
words[index].str = (char *)malloc(size);
strcpy(words[index].str, word);
words[index].count = 1;
nwords++;
}
}
void convert_lower(char *str) {
while (*str) {
*str = tolower(*str);
str++;
}
}
int linear_search(const char *key, int *found) {
int n, compare;
*found = 0; // ã
for (n = 0; n < nwords; n++) {
compare = strcmp(key, words[n].str);
if (compare <= 0) {
*found = compare == 0; // compare 0̸ ã
break;
}
}
// 迭 ε
return n;
}
void print_words() {
// ̷
}
void deallocate() {
int n;
for (n = 0; n < nwords; n++) {
// words 迭 Ҵ str ڿ 迭
if (words[n].str) free(words[n].str);
}
free(words);
}
|
C | #include <project.h>
unsigned char GetASCh(unsigned int uiNum, unsigned char ucNum);
void Print_Temp(unsigned int uiTemp);
void Print_All(unsigned char ucHTemp, unsigned char ucLTemp);
int main(void)
{
unsigned char ucHTemp = 0;
unsigned char ucLTemp = 0;
unsigned int uiValue = 0;
Lcd_Init();
Timer_Init();
Spi_Init();
while (1)
{
// Ÿ µ
*AT91C_SPI_CR = AT91C_SPI_SPIEN;
ms_delay(1);
ucLTemp = Spi_Data(0xA0); // ȣ
ms_delay(10);
ucLTemp = Spi_Data(0x22); // 1 byte
ms_delay(10);
ucHTemp = Spi_Data(0x22); // 1 byte
*AT91C_SPI_CR = AT91C_SPI_SPIDIS;
Lcd_Inst(0x80 | 0x00);
Print_All(ucHTemp, ucLTemp);
ms_delay(100);
// ֺ µ
*AT91C_SPI_CR = AT91C_SPI_SPIEN;
ms_delay(1);
ucLTemp = Spi_Data(0xA1);
ms_delay(10);
ucLTemp = Spi_Data(0x22);
ms_delay(10);
ucHTemp = Spi_Data(0x22);
*AT91C_SPI_CR = AT91C_SPI_SPIDIS;
Lcd_Inst(0x80 | 0x40);
Print_All(ucHTemp, ucLTemp);
ms_delay(1000);
}
return 0;
}
void Print_All(unsigned char ucHTemp, unsigned char ucLTemp)
{
unsigned int uiValue;
uiValue = ucHTemp<<8;
uiValue = uiValue|ucLTemp;
Print_Temp(uiValue/100);
Lcd_Data('.');
Print_Temp(uiValue%100);
Lcd_Print("/ ");
Lcd_Data(GetASCh(uiValue, 4));
Lcd_Data(GetASCh(uiValue, 3));
Lcd_Data(GetASCh(uiValue, 2));
Lcd_Data(GetASCh(uiValue, 1));
return;
}
void Print_Temp(unsigned int uiTemp)
{
unsigned char ucTen = (uiTemp/10)%10;
unsigned char ucOne = uiTemp%10;
Lcd_Data(ucTen + '0');
Lcd_Data(ucOne + '0');
return;
}
unsigned char GetASCh(unsigned int uiNum, unsigned char ucNum)
{
unsigned int tmp = uiNum;
tmp = (uiNum>>(4*(ucNum-1)))&0x000F;
if(tmp >= 10)
return 'A'+tmp-10;
else
return '0'+tmp;
}
|
C |
int iterative_factorial(int nb)
{
int num;
num = 1;
if (nb < 0)
return (0);
while (nb != 0)
{
num = num * nb;
nb--;
}
return (num);
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
#define pr_usage(fmt, ...) \
fprintf(stderr, fmt, ##__VA_ARGS__)
static const char *execname = "";
static void base_usage(const char *name, const char *help)
{
pr_usage("\t%s\t%s\n", name, help);
}
static void argument_usage(const char *argname, const char *arghelp)
{
base_usage(argname, arghelp);
}
static void option_usage(const char *opname, const char *ophelp)
{
base_usage(opname, ophelp);
}
static void usage()
{
pr_usage("usage: %s [OPTIONS] ARG1\n", execname);
pr_usage("arguments:\n");
argument_usage("ARG1", "placeholder");
pr_usage("options:\n");
option_usage("-h,--help", "Print this help message");
}
int main(int argc, char *argv[])
{
static struct option options [] = {
{ "help" , 0 , 0, 'h' },
{ /* sentinel */ }
};
static const char * opstring = "h";
int ch;
execname = argv[0];
// process options
while ((ch = getopt_long(argc, argv, opstring, options, NULL)) != -1) {
switch (ch) {
case 'h':
usage();
exit(0);
default:
usage();
exit(1);
}
}
argc -= optind;
argv += optind;
// rest of code here
return 0;
}
|
C | #include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#define N 1000
#define NBMAT 10
double counter=0;
double serialFunc(){
counter++;
return counter;
}
void *multiplyMatCst(void *arg){
int i,j;
double *M;
M = (double *) arg;
for (i=0;i<N;i++){
for (j=0;j<N;j++){
M[i*N+j] = M[i*N+j]*10.0;
}
}
return NULL;
}
//return the wallclock time in seconds
double wallclock(){
struct timeval tv;
double t;
gettimeofday(&tv, NULL);
t = (double)tv.tv_sec;
t += ((double)tv.tv_usec)/1000000.0;
return t;
}
int main(int argc, char *argv[]){
double tstart, tend;
pthread_t mytask_thread[NBMAT];
double *matArray[NBMAT];
int i,j,k;
printf("Initializing the matrices\n");
tstart = wallclock();
for (k=0;k<NBMAT;k++){
matArray[k] = (double *) malloc (N*N*sizeof(double));
for (i=0;i<N;i++){
for(j=0;j<N;j++){
matArray[k][i*N+j] = serialFunc();
}
}
}
tend = wallclock();
printf("Execution time serial part %f sec.\n", tend - tstart);
for (k=0;k<NBMAT;k++){
printf("Before creating the threads --> %f\n",matArray[k][(N*N+N)/2]);
}
tstart = wallclock();
// create a set of threads
for (k=0;k<NBMAT;k++){
if(pthread_create(&(mytask_thread[k]), NULL, multiplyMatCst, matArray[k])) {
fprintf(stderr, "Error creating thread\n");
return 1;
}
}
// wait for the threads to finish
for (k=0;k<NBMAT;k++){
if(pthread_join(mytask_thread[k], NULL)) {
fprintf(stderr, "Error joining thread\n");
return 2;
}
}
tend = wallclock();
printf("Execution time parallel part %f sec.\n", tend - tstart);
for (k=0;k<NBMAT;k++){
printf("After joining the threads --> %f\n",matArray[k][(N*N+N)/2]);
}
for (k=0;k<NBMAT;k++){
free(matArray[k]);
}
return 0;
}
|
C | #include<stdio.h>
#include<stdlib.h>
int max(int x,int y){
return x>y?x:y;
}
void populate_arran(int*array,size_t arraySize,int (*getNextValue)(void)){
for (size_t i=0;i<arraySize;i++){
array[i]=getNextValue();
}
}
int getNextValue(){
return rand();
}
int main(){
// int(*p)(int ,int)=&max;
// int a,b,c,d;
// scanf("%d %d %d",&a,&b,&c);
// d=p(p(a,b),c);
// printf("%d",d);
int myArray[10];
populate_arran(myArray,10,getNextValue);
for (int i=0;i<10;i++){
printf("%d\n",myArray[i]);
}
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include "matrix.h"
Matrix* create_matrix(int row, int col)
{
Matrix* matrix = calloc(row*col,sizeof(Matrix));
if(matrix ==NULL)
{
printf("Not enough memory!\n");
exit(1);
}
return matrix;
}
double get_l_norm(Matrix *matrix, int row, int col)
{
int i, j, col_n;
double temp_l_max = 0;
double l_norma_max = 0;
for(i = 0; i<col; i++)
{
temp_l_max = 0;
for(j = i; j<row*col; j++)
{
if(matrix[i].col == matrix[j].col)
{
if(matrix[j].value < 0)
{
temp_l_max +=matrix[j].value*(-1);
}
else
temp_l_max +=matrix[j].value;
}
}
if(l_norma_max<temp_l_max)
{
col_n = i;
l_norma_max = temp_l_max;
}
}
printf("\nl-norm of given Matrix is %.02f (in col[%i])\n", l_norma_max, col_n);
return l_norma_max;
}
Matrix* create_matrix_from_file(FILE* file)
{
int i, j,k, row, col;
if(file == NULL)
{
printf("Can not open file");
exit(0);
}
else
{
int fSpace = 1, nCount = 0;
char ch[2]= {0};
while(! feof(file))
{
fgets(ch ,2, file);
if(ch[0] > 41)
fSpace = 0;
else if( fSpace ==0)
{
nCount++;
fSpace = 1;
}
ch[0] = 0;
}
fseek(file , 0 , SEEK_END);
long lSize = ftell(file);
rewind (file);
double buff[nCount];
for(i = 0; i<nCount; i++)
{
if(fscanf(file, "%lf", &buff[i]) !=1)
{
printf("Incorrect matrix elements");
exit(0);
}
}
if((buff[0] - (int)buff[0] != 0)||(buff[1] - (int)buff[1] != 0))
{
printf("N. of rows and cols must be an integer");
exit(0);
}
else
{
row = buff[0];
col = buff[1];
}
if(row*col != nCount -2)
{
printf("Wrong number of elements");
exit(0);
}
printf("\n*************\n");
Matrix *matrix = create_matrix(row, col);
j = 0;
i = 0;
matrix[0].cols = col;
matrix[0].rows = row;
for(k = 2; k< row*col+2; k++)
{
matrix[k-2].value = buff[k];
matrix[k-2].row = i;
matrix[k-2].col = j;
j++;
if(j==col)
{
i++;
j = 0;
}
}
fclose(file);
get_l_norm(matrix, row, col);
return matrix;
}
}
void set_elem(Matrix* matrix, int row, int col, double val)
{
int i;
for(i = 0; i<row*col; i++)
{
if((matrix[i].col ==col)&&(matrix[i].row ==row))
matrix[i].value = val;
}
}
double get_elem(Matrix* matrix, int row, int col)
{
double elem;
int i;
for(i = 0; i<col*row; i++)
{
if((matrix[i].col ==col)&&(matrix[i].row ==row))
elem = matrix[i].value;
else printf("Element with these coordinates doesn't exist");
}
return elem;
}
int get_rows(Matrix* matrix)
{
int rows = matrix[0].rows;
return rows;
}
int get_cols(Matrix* matrix)
{
int cols = matrix[0].cols;
return cols;
}
void free_matrix(Matrix* matrix)
{
free(matrix);
}
|
C | #include <stdio.h>
#include <unistd.h>
#include <tipos.h>
#include <bisection.h>
/*
* Main
*/
void no_friction(Params *p);
void friction(Params *p);
int main(int argc, char* argv[]){
// Aca se asignan los params parseados del CLI al estilo -h <valor> -v <valor>
static const char *optString = "M:h:v:t:m:c:i:a:b:f:";
int method, c;
char * pEnd;
Params p;
while((c = getopt(argc, argv, optString)) != -1){
switch(c){
case 'M': { method = atoi(optarg); break; }
case 'h': { p.h = TFloat(atof(optarg),T); break; }
case 'v': { p.v = TFloat(atof(optarg),T); break; }
case 't': { p.tol_bisect = TFloat(atof(optarg),T); break; }
case 'm': { p.mass = TFloat(atof(optarg),T); break; }
case 'c': { p.cr = TFloat(atof(optarg),T); break; }
case 'i': { p.max_iterations = strtoul(optarg,&pEnd,10); break; }
case 'a': { p.a = TFloat(atof(optarg),T); break; }
case 'b': { p.b = TFloat(atof(optarg),T); break; }
case 'f': { p.f = TFloat(atof(optarg),T); break; }
default: { printf("Cannot parse.\n"); }
}
}
switch(method) {
case 0: { no_friction(&p); break; }
case 1: { friction(&p); break; }
default: { printf("Metodo no valido.\n"); }
}
return 0;
}
void no_friction(Params *p){
Result primer_impacto, segundo_impacto;
TFloat a;
printf("No Friction: \n");
primer_impacto = zero_bisection(p, &position);
primer_impacto.speed = speed(p, primer_impacto.zero);
for(a= 0; a < primer_impacto.zero; a = a + .5){
mechanical_energy_output(a, mechanical(p,a ), position(p,a));
}
// Preparamos para el segundo impacto
p->h = 0;
p->v = primer_impacto.speed * -1;
p->b = 100; // El segundo impacto ocurre antes del 100. Como no sabiamos como calcularlo, en las consultas nos permitieron hardcodearlo.
segundo_impacto = zero_bisection(p, &position);
segundo_impacto.speed = speed(p, segundo_impacto.zero);
printf(" 1 Impacto \n");
for(a= 0; a < segundo_impacto.zero; a = a + .5){
mechanical_energy_output(a + primer_impacto.zero, mechanical(p,a ), position(p,a));
}
// Preparamos para ver mas alla del 2 impacto
p->v = segundo_impacto.speed * -1;
printf(" 2 Impacto \n");
for(a= 0; a < 2; a = a + .5){
mechanical_energy_output(a + primer_impacto.zero + segundo_impacto.zero, mechanical(p,a), position(p,a));
}
}
/*
* Energia mecanica considerando la friccion, alpha != 0
*/
void friction(Params *p){
Result primer_impacto, segundo_impacto;
TFloat a;
printf("With Friction: \n");
primer_impacto = zero_bisection(p, &position_with_friction);
primer_impacto.speed = speed_with_friction(p, primer_impacto.zero);
for(a= 0; a < primer_impacto.zero; a=a+.5){
mechanical_energy_output(a, mechanical_with_friction(p,a ), position_with_friction(p,a));
}
p->h = 0;
p->v = primer_impacto.speed * -1 * p->f;
p->b = 50;
segundo_impacto = zero_bisection(p, &position_with_friction);
segundo_impacto.speed = speed_with_friction(p, segundo_impacto.zero);
printf(" 1 Impacto \n");
for(a= 0; a < segundo_impacto.zero; a= a+.5){
mechanical_energy_output(a + primer_impacto.zero, mechanical_with_friction(p,a ), position_with_friction(p, a));
}
p->h = 0;
p->v = segundo_impacto.speed * -1 * p->f;
printf(" 2 Impacto \n");
// Para ver que pasa un poquito despues del segundo impacto
for(a= 0; a < 2; a = a + .5){
mechanical_energy_output(a + primer_impacto.zero + segundo_impacto.zero, mechanical_with_friction(p,a), position_with_friction(p,a));
}
}
|
C | /*
Eric Paulz (epaulz)
CPSC 3600-001
Homework 4
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
// thread function prototype
void *connection_handler(void *);
int main( int argc, char **argv){
int ld, sd=0, addrLen, len;
struct sockaddr_in skaddr;
struct sockaddr_in from;
// check for usage
if(argc != 2){
printf("Usage: <executable> <port>\n");
exit(0);
}
// create socket
if((ld = socket(PF_INET, SOCK_STREAM, 0)) < 0){
perror("Error creating socket.\n");
exit(1);
}
// establish address structure
skaddr.sin_family = AF_INET;
skaddr.sin_addr.s_addr = htonl(INADDR_ANY);
skaddr.sin_port = htons(atoi(argv[1]));
if(bind(ld, (struct sockaddr*)&skaddr, sizeof(skaddr)) < 0){
perror("Error binding.\n");
exit(0);
}
// determine port number and print
len = sizeof(skaddr);
if(getsockname(ld, (struct sockaddr*)&skaddr, &len) < 0){
perror("Error getsockname.\n");
exit(1);
}
printf("Passive server socket port number: %d\n", ntohs(skaddr.sin_port));
// put socket into passive mode
if(listen(ld, 5) < 0){
perror("Error calling listen.\n");
exit(1);
}
// process connections forever
while(1){
if(sd==0)
printf("Ready for a connection...\n\n");
addrLen = sizeof(skaddr);
if((sd = accept(ld, (struct sockaddr*)&from, &addrLen)) < 0){
perror("Problem with accept call.\n");
exit(1);
}
printf("Got a connection - processing...\n\n");
pthread_t child;
// determine address/port of new server socket and print
len = sizeof(skaddr);
if(getsockname(sd, (struct sockaddr*)&skaddr, &len) < 0){
perror("Error getsockname.\n");
exit(1);
}
printf("Active server port number: %d\n", ntohs(skaddr.sin_port));
printf("Active server IP: %s\n", inet_ntoa(skaddr.sin_addr));
// print client address
if(getsockname(sd, (struct sockaddr*)&from, &len) < 0){
perror("Error getsockname.\n");
exit(1);
}
printf("Client port number: %d\n", ntohs(from.sin_port));
printf("Client IP: %s\n\n", inet_ntoa(from.sin_addr));
// create thread
pthread_create(&child, 0, connection_handler, (void*)&sd);
}
return 0;
}
// thread function to handle data transfer for connections
void *connection_handler(void *sock_desc){
int n=-1, m, sd=0;
bool w=true;
char eof=(char)0x04, buff1[100], buff2[100], buff3[100], timeStr[9], *charPtr, msg[50];
time_t current_time;
struct tm* timeInfo;
sd = *(int*)sock_desc;
// read data
while(1){
if((m = recv(sd, msg, 50, 0)) < 0)
perror("Error receiving message.\n");
else if(m==0)
printf("Connection closed.\n");
msg[m] = '\0';
printf("Data received from client file '%s'.\n", msg);
charPtr = strchr(msg, '.');
if(charPtr!=NULL)
*charPtr = '\0';
time(¤t_time);
timeInfo = localtime(¤t_time);
strftime(timeStr, sizeof(timeStr), "%H-%M-%S", timeInfo);
strcat(msg, "(");
strcat(msg, timeStr);
strcat(msg, ").txt");
if((send(sd, msg, strlen(msg), 0)) < 0){
fprintf(stderr, "Error sending message.\n");
close(sd);
}
printf("Data stored in file '%s'.\n\n", msg);
break;
}
FILE* newFile = fopen(msg,"w");
if(newFile == NULL){
perror("Error opening file.\n");
return 0;
}
while((n = read(sd, buff1, 100)) > 0){
int i = 0, j, k = 0;
while(i < n){
j = 0;
while(buff1[i] != '\n'){
buff2[j] = buff1[i];
i++;
j++;
}
buff2[j] = '\n';
while(j >= 0){
buff3[j] = buff2[k];
k++;
j--;
}
i++;
}
fwrite(buff3, n, 1, newFile);
write(sd, &eof, 1);
}
if(n==0)
printf("Data transfer successful... closing connection\n\n");
if(newFile != NULL)
fclose(newFile);
close(sd);
sd = 0;
return 0;
}
|
C | /**
Lab 4 for SYSC 3310A: Intro to Real Time Systems (Summer 2021)
This application uses two switches, a built-in 16 bit timer called TimerA and two LEDs (a red LED and an RGB LED).
Only one LED can be controlled at any given time, and that LED that is being controlled is referred to as the 'selected' LED
switch 1 switches the selection between the RGB and the red LED.
When the timer counts to 1 second, it sends an interrupt which ultimatly cuases the selected LED to change state.
The red LED has two states (on/off) while the RGB LED has 8 states (corresponding to 8 different colors it can produce).
After counting to 1 second, the timer resets to 0, and starts counting up again.
By clicking switch 2, the user can pause timer.
##Objective
To learn how to use timers generally, and to set up ISRs that rely on timers
author name: Arsalan Syed
author student ID: 101169528
date: July 1st, 2021
*/
#include "msp.h"
#include <stdio.h>
#define RED_LED 0
#define RGB_LED 1
#define INPUT 0
#define OUTPUT 1
#define ONE_SECOND 32767//32768 - 1 // assuming a 32768 Hz clock, this is how many ticks are required to count 1 second
static uint8_t LED_selection = RGB_LED; //specifies which LED is currently selected
static uint8_t RGB_LED_state = 0;
static uint8_t red_LED_state = 0;
/*
based on LED_selection, this turns on one LED and turns off the other. For example
when LED_selection = RED_LED, then the red LED is turned on, and the RGB LED is turned on
*/
void updateLED(){
if(LED_selection == RED_LED){
//set the red LED's state
/*
TO DO:
for some reason, the program crashes when p1 is written to directly, so we have
to use this less elegent method for toggling the bits. Should probably figure out
why this is the case.
*/
if (red_LED_state == 1)
P1->OUT |= 0x1;
else if(red_LED_state == 0)
P1->OUT &= ~0x1;
//turn off the RGB LED
P2->OUT &= ~(BIT0 | BIT1 | BIT2);
}else if (LED_selection == RGB_LED){
//turn off the red LED
P1->OUT &= ~ BIT0;
//set the RGB LED to a color corresponding to it's current state
P2->OUT = (uint8_t)(RGB_LED_state);
}
}
/*Interrupt handler for port 1. Activated when switch one or two is clicked*/
void PORT1_IRQHandler(void){
if(P1IFG & BIT1){ //switch one has been clicked, so we will change the LED selected
P1IFG &= ~BIT1; // clear the interrupt flag
//change the LED that is selected
if(LED_selection == RED_LED)
LED_selection = RGB_LED;
else
LED_selection = RED_LED;
}
else if(P1IFG & BIT4) { // second switch has been selected
P1IFG &= ~BIT4; //clear the interrupt flag
//Toggle whether the timer is on or off
TA0CTL ^= (uint16_t)(BIT4);
}
updateLED();
return;
}
/*configure timerA0 to repeatedly count to 1 second, at which time it will produce an interupt
After reaching 1 second, timerA0 resets immediately to 0, and starts counting up again.*/
void configureTimer(){
TA0CTL &= (uint16_t)(~(BIT5 | BIT5)); //stop the timer
TA0CTL &= (uint16_t)(BIT0); //reset timer
TA0CTL |= (uint16_t)(~BIT9); //select SMCLK as the clock source (32.768 khz)
TA0CTL &= (uint16_t)(BIT8); //this bit needs to be cleared to use SMCLK as the clock source
TA0CTL &= (uint16_t)(~(BIT7 | BIT6)); //set the input divider to the clock as 1 (ID register)
TA0EX0 &= (uint16_t)(~(BIT0 | BIT1 | BIT2)); // set the input divider as 1 (input divider expansion)
TA0CCR0 = (uint16_t)(ONE_SECOND); //count up to 1 second
TA0CTL &= (uint16_t)(~BIT0); //clear interrupt flag
TA0CTL |= (uint16_t)(BIT1); //enable interrupts
TA0CTL |= (uint16_t)(BIT4); // upmode counter
//enable TA interrupts in the NVIC
NVIC_SetPriority(TA0_N_IRQn, 3);
NVIC_ClearPendingIRQ(TA0_N_IRQn);
NVIC_EnableIRQ(TA0_N_IRQn);
}
/*configure p1.1 and p1.4 sa input pins that are active low
configure p1.0 and p2.0, p2.1, p2.2 as output pins.
p1.0 is connected to a red LED
p2.0...p2.3 are the three cathodes connected to an RGB LED*/
void configureIO(){
//configure pins as GPIO
P1->SEL0 &= ~(BIT0 | BIT1 | BIT4); //configuring pins 0,1 and 4 of port 1 as GPIO
P1->SEL1 &= ~(BIT0 | BIT1 | BIT4);
P2->SEL0 &= ~(BIT0 | BIT1 | BIT2); //configuring pins 0,1, and 2 of port 2 as GPIO
P2->SEL1 &= ~(BIT0 | BIT1 | BIT2);
//configuring the input pins
P1->DIR &= ~(BIT1 | BIT4); //set the pins as input (port 1, pin 1 and 4)
P1->REN |= (BIT1 | BIT4); //set the resistor for the input pins
P1->OUT |= (BIT1 | BIT4); //set the resistors as pull up resistors
//configuring the output pins
P2->DIR |= (BIT0 | BIT1 | BIT2); // setting pins 0, 1, 2 as outputs (powers RGB led)
P1->DIR |= BIT0; // setting pin 0 (port 1) as output (powers red LED)
P1->DS &= ~ BIT0; //set the drive strength of the output pins as 'regular strength' for port 1 pins
P2->DS &= ~(BIT0 | BIT1 | BIT2); //set the drive strength of the output pins as 'regular strength' for port 2 pins
//configuring interrupts
P1IES |= (BIT1 | BIT4); //select falling edge as trigger generator
P1IFG &= ~(BIT1 | BIT4); //remove any flags that are up right now relating to our input pins
P1IE |= (BIT1 | BIT4); //enable interrupts on pins 1 and 4
//NVIC configuration
NVIC_SetPriority(PORT1_IRQn, 2);
NVIC_ClearPendingIRQ(PORT1_IRQn);
NVIC_EnableIRQ(PORT1_IRQn);
}
/*interrupt handler for timer. This function is called when the timer counts to 1 second*/
void TA0_N_IRQHandler(void) {
TA0CTL &= (uint16_t)(~BIT0); //clear the flag
if(LED_selection == RGB_LED)
RGB_LED_state = (RGB_LED_state + 1 ) % 0x8; //flip to the next color on the RGB LED
else if(LED_selection == RED_LED)
red_LED_state ^= BIT0;
updateLED();
}
int main(void){
//disable watchdog timer
WDT_A->CTL = WDT_A_CTL_PW | WDT_A_CTL_HOLD;
configureTimer();
configureIO();
//enable global interrupts
__ASM("CPSIE I");
//done with configuration
while(1){
__ASM("WFI"); //wait for interrupts
}
return 0;
}
|
C | /*
** my_prinf.c for my_prinf.c in /home/bequig_s//workspace/module-Unix/my_printf/my_prinf2
**
** Made by sebastien bequignon
** Login <[email protected]>
**
** Started on Sat Nov 17 09:27:20 2012 sebastien bequignon
** Last update Sun Nov 18 20:54:59 2012 sebastien bequignon
*/
#include <stdarg.h>
int my_printf(char *format, ...)
{
int wrote;
va_list va;
va_start(va, format);
wrote = exec(format, va);
va_end(va);
return (wrote);
}
|
C | void ft_putchar(char c);
void ft_swap(char **s1, char **s2)
{
char *tmp;
tmp = *s1;
*s1 = *s2;
*s2 = tmp;
}
void ft_putstr(char *str)
{
while (*str)
ft_putchar(*(str++));
}
int ft_strcmp(char *s1, char *s2)
{
int i;
i = 0;
while (s1[i] == s2[i])
i++;
return (s1[i] - s2[i]);
}
int main(int argc, char **argv)
{
int i;
int j;
i = 0;
while (++i < argc)
{
j = 0;
while (++j < argc - i)
if (ft_strcmp(argv[j], argv[j + 1]) > 0)
ft_swap(argv + j, argv + j + 1);
}
i = 0;
while (++i < argc)
{
ft_putstr(argv[i]);
ft_putchar('\n');
}
return (0);
}
|
C | /***************************************************************************************
*
*
*
*Author: Jiwen CHEN <[email protected]>
*
*
*
*
*
*
****************************************************************************************/
/*
*2.7ǰNȻһ
*/
#include <stdio.h>
#include "sort.h"
#include <time.h>
#include <memory.h>
#include <stdlib.h>
#include "common.h"
#include <math.h>
#include <direct.h>
#include <io.h>
int ramdonInt(int m)
{
return m - rand() % ((m << 1) + 1);
}
/*
*random(int m, int n):
* return a random number between m and n, include m and n
* the max value returned by rand() is 0x7fff, to generate
* a 32-bit random value, (rand() << 16) | rand()
*
*/
int random(int m, int n) {
int res = (rand() << 16) | rand();
return m + res % (n - m + 1);
}
/*
*int* randomPermutation(int n):
* return a random permutation of [1,2,3,...,n]
*
*algorithm description:
* 1. generate A[0,...,i]
* 2. generate A[i+1] which is not present in A[0,...,i]
*/
int* randomPermutation(int n) {
int* pRes = NULL;
int i = 0, j = 0;
int temp = 0;
pRes = (int*)malloc(n * sizeof(int));
if (!pRes)
{
return NULL;
}
while (i < n)
{
temp = random(1, n);
for (j = 0; j < i && (temp != *(pRes + j)); j++);
if (j == i)
{
*(pRes + i) = temp;
i++;
}
}
return pRes;
}
/*
*int* randomPermutationByArray(int n):
* return a random permutation of [1,2,3,...,n]
*
*algorithm description:
* 1. generate A[0,...,i]
* 2. generate A[i+1] which is not present in A[0,...,i]
* 3. use a array to indicate whether the randomValue is generated or not
*/
int* randomPermutationByArray(int n) {
int* pRes = NULL;
int i = 0;
int temp = 0;
int* usedRan = NULL;
pRes = (int*)malloc(n * sizeof(int));
if (!pRes)
{
return NULL;
}
/*
*as usedRan[temp], 1 <= temp <= n, so need allocate n + 1 array
*/
usedRan = (int*)malloc((n + 1) * sizeof(int));
if (!usedRan)
{
return NULL;
}
//memset the array as zero first
memset(usedRan, 0, (n + 1) * sizeof(int));
i = 0;
while (i < n)
{
temp = random(1, n);
if (!usedRan[temp])
{
//if random value is not generated, update it as TRUE
usedRan[temp] = TRUE;
*(pRes + i) = temp;
i++;
}
}
free(usedRan);
return pRes;
}
/*
*int* randomPermutationBySwap(int n):
* return a random permutation of [1,2,3,...,n]
*
*algorithm description:
* 1. generate A[0,...,i]
* 2. generate A[i+1] which is not present in A[0,...,i]
* 3. use a array to indicate whether the randomValue is generated or not
*/
int* randomPermutationBySwap(int n) {
int* pRes = NULL;
int i, j = 0;
int temp = 0;
int needRegenerate = 1;
pRes = (int*)malloc(n * sizeof(int));
//set the permutation first as [1,2,...,n]
for (i = 0; i < n; i++)
{
*(pRes + i) = i + 1;
}
//swap the A[i] with a A[random(0,i)]
for (i = 1; i < n; i++)
{
swap(pRes + i, pRes + random(0, i));
}
return pRes;
}
int* randomArrayBySwap(int n) {
int* pRes = NULL;
int i, j = 0;
int temp = 0;
int needRegenerate = 1;
pRes = (int*)malloc(n * sizeof(int));
//set the permutation first as [1,2,...,n]
for (i = 0; i < n; i++)
{
*(pRes + i) = ramdonInt(100);
}
//swap the A[i] with a A[random(0,i)]
for (i = 1; i < n; i++)
{
swap(pRes + i, pRes + random(0, i));
}
return pRes;
}
/*
*2.10
*issue description:
* f(x) = A[0]*x^0 + A[1]*x^1 + ... A[N]*x^N
*
*complexity:
* a)S = 1 + 2 + ... + N = O(N^2)
* b)S = O(NlogN) use the quick power:
* proof:
* S = log1 + log2 + ... log(N/2) + ... + log(N) <= Nlog(N)
*
* S > log(N/2) + ... log(N) > N/2*log(N/2)
* thus S = O(Nlog(N))
* c)Horner ruleO(N)
* f(x) = A[0]+A[1]*x+A[2]*x^2+...+A[N]*x^N
* = A[0]+x*(A[1]+x*(A[2]+x*(A[3]+...x*(A[N-1] + x*(A[N]+x*(0)))))
*
*/
int polyComputeBruce(int cofficient[], int x, int degree)
{
int sum = 0;
int i, j = 0;
int res = 0;
for (i = 0; i <= degree; i++)
{
res = cofficient[i];
for (j = 0; j < i; j++)
{
res *= x;
}
sum += res;
}
return sum;
}
extern int QuickPower(int exp, int base);
int polyComputeByQP(int cofficient[], int x, int degree)
{
int sum = 0;
int i, j = 0;
int res = 0;
for (i = 0; i <= degree; i++)
{
res = cofficient[i];
if (res)
{
res *= QuickPower(i,x);
}
sum += res;
}
return sum;
}
/*
*Horner rule:
* f(x) = A[0]+A[1]*x+A[2]*x^2+...+A[N]*x^N
* = A[0]+x*(A[1]+x*(A[2]+x*(A[3]+...x*(A[N-1] + x*(A[N]+x*(0)))))
*/
int polyComputeByHorner(int cofficient[], int x, int degree)
{
int poly = 0;
int i = 0;
poly = 0;
for (i = degree; i >= 0; i--)
{
poly = x*poly + cofficient[i];
}
return poly;
}
/*
*2.11 һЧ㷨ȷϸA1,...,A[N]ǷiʹA[i]=i.
*
*mid = (low + high)/2
*if A[mid] == mid: return mid
*else if A[mid] < mid: for any 0 <= i <= mid then A[i] < i
*else if A[mid] > mid: for any mid <= i <= high, there must be A[i] > i
*
*proof:
*
* if A[i] = i, then A[mid] > A[i] + mid - i = mid, there is a contradict.
*
*/
int CheckIfNumPresent(int A[], int len, int i)
{
return binarySearch(A, len, i);
}
/*
*2.12
*1.Ск
*2.Ск
*3.г˻
*
*/
/*
*int minSubseqSumByBruce(int A[], int len)
* ÿһiA[i]ͣȻͬСıȽϣӶΪO(N^2)
*/
int minSubseqSumByBruce(int A[], int len, int *pSeqBegin, int *pSeqEnd)
{
int minSum = INT_MAX;
int tempSum = 0;
int i = 0, j = 0;
for (i = 0; i < len; i++)
{
tempSum = 0;
for (j = i; j < len; j++)
{
tempSum += A[i];
if (tempSum < minSum)
{
minSum = tempSum;
*pSeqBegin = i;
*pSeqEnd = j;
}
}
}
return minSum;
}
/*
*int minSumSubseqByConcur(int A[], int len):
*
*
*algorithm description:
* divide the array into two parts, then the minSum subsequence is one of the three:
* 1. exist in left the part
* 2. exist in the right the part
* 3. accross the left part and right part
*/
int minSumSubseqByConcur(int A[], int left, int right, int *pSeqBegin, int *pSeqEnd)
{
int minSumL = 0, minSumR = 0, minSum = INT_MAX;
int i = 0, thisSum = 0, mid = 0, lAccrossBegin = 0, rAccrossEnd = 0;
int lLSeqBegin = 0, lRSeqEnd = 0, rLSeqBegin = 0, rRSeqEnd = 0;
if (left == right)
{
*pSeqBegin = left;
*pSeqEnd = right;
return A[left];
}
mid = left + (right - left) / 2;
minSumL = minSumSubseqByConcur(A, left, mid, &lLSeqBegin, &lRSeqEnd);
minSumR = minSumSubseqByConcur(A, mid + 1, right, &rLSeqBegin, &rRSeqEnd);
thisSum = 0;
i = mid;
while (i >= left)
{
thisSum += A[i];
if (thisSum < minSum)
{
minSum = thisSum;
lAccrossBegin = i;
}
}
i = mid + 1;
while (i <= right)
{
thisSum += A[i];
if (thisSum < minSum)
{
minSum = thisSum;
rAccrossEnd = i;
}
}
if (minSum < minSumL)
{
if (minSum < minSumR)
{
*pSeqBegin = lAccrossBegin;
*pSeqEnd = rAccrossEnd;
}
else
{
*pSeqBegin = rLSeqBegin;
*pSeqEnd = rRSeqEnd;
}
}
else
{
if (minSumL < minSumR)
{
*pSeqBegin = lLSeqBegin;
*pSeqEnd = lRSeqEnd;
}
else
{
*pSeqBegin = rLSeqBegin;
*pSeqEnd = rRSeqEnd;
}
}
return minSum;
}
int minSumSubseqDP(int A[], int len)
{
int minSum = INT_MAX;
int tempSum = 0;
int i = 0;
for (i = 0; i < len; i++)
{
tempSum += A[i];
if (tempSum < minSum)
{
minSum = tempSum;
}
else if (tempSum > 0)
{
tempSum = 0;
}
}
return minSum;
}
/*
**2.Ск
*sum[0]=a[0]
*sum[1]=sum[0]+a[1]
*
*sum[i]=sum[i-1]+a[i]
*
*sum[]Ȼsum[i]-sum[i-1]IJֵСֵ
*/
/*
*дһһǷ
*O(sqrt(N))
*֤
* һx2sqrt(N)֮ûӣΪȻxΪ
*s2<=s<t-1ʹx|ss > sqrt(N)t=x/s | xx|t
*t< sqrt(N)ìܡxΪ
*/
int isPrimeNum(unsigned long num)
{
unsigned long div = 0;
unsigned long i = 0;
if (num == 0 || num == 1)
{
return FALSE;
}
if (num == 2)
{
return TRUE;
}
div = (int)sqrt(num);
for (i = 2; i <= div; i++)
{
if (num % i == 0)
{
return FALSE;
}
}
return TRUE;
}
/*
*Eratosthese algorithm:
* remove 2*i
* remove 3*i
* ...
* remove k*i k <= sqrt(N)
*/
unsigned long* makePrimeTable(unsigned long num)
{
unsigned long* pPrimTable = NULL;
unsigned long i = 0, k = 0;
pPrimTable = (unsigned long*)malloc((num + 1) * sizeof(unsigned long));
if (!pPrimTable)
return pPrimTable;
for (i = 0; i <= num; i++)
*(pPrimTable + i) = i;
for (i = 2; i <= (unsigned long)sqrt(num); i++)
{
if (*(pPrimTable + i))
{
for (k = 2; k <= num / i; k++)
pPrimTable[k * i] = 0;
}
}
if (0)
{
printf("Prime number table less than:%10d\n", num);
k = 0;
for (i = 2; i < num; i++)
{
if (pPrimTable[i])
{
printf("%10d", pPrimTable[i]);
k++;
if (k % 5 == 0)
{
printf("\n");
}
}
}
}
return pPrimTable;
}
/*
*decmical to binary
*/
void decToBin(unsigned long x)
{
int res[128] = { 0 };
int i = 0;
if (x == 0 || x == 1)
{
printf("%d\n", x);
return;
}
while(x)
{
res[i++] = x & 1;
x = x >> 1;
}
while (i)
{
printf("%d", res[--i]);
if (i % 4 == 0 && i != 0)
printf(",");
}
printf("\n");
}
/*2.15 8μx^62
*x*x->x^2
*x^2*x^2->x^4
*x^4*x^4 ->x^8
*x^8*x^8->x^16
*x^4*x16->x^20
*x^20*x^10->x^40
*x^40*x^20->x^60
*x^60*x^2->x^62
*/
/*
*2.16 õݹʵֿ
*/
double quickPow(double x, int n)
{
double res = 1.0;
if (n < 0)
{
x = 1.0 / x;
n = -n;
}
if (x == 0.0)
res = 0.0;
while (n)
{
if (n & 1)
res *= x;
x *= x;
n >>= 1;
}
return res;
}
/*2.17
*ݵij˷
*2N - 1+ M NǶ1ĸM0ĸ
*ķǵݹ㷨֪λΪ1γ˷λΪ0ֻһγ˷
*/
/*
*2.19 жǷԪԪĴN/2
*㷨
*
* AȡA1,A2ȣB,ѡȡA3,A4ǰȽ
*һԪӵBôBĺѡԪҲAĺѡԪΪBеԪ
*AеԪ˫˫ȽȲġijһBеĵAԪX,ضԪ
*Ϊn/2˫˫ԱȽϣxû뵽B,˵Ԫصĸᳬn/2
*
* N/2+N/4...+1 = O(N)
*
*
*㷨2
* ÿѡ㷨ѡλȻλ
*
*㷨3
* һmap<int, int>,ɨ飬keyֵĴи£Ͱ/
*/
int SelectPivot(int A[], int len)
{
int i = 0, k = 0;
if (len == 0)
{
return -1;
}
if (len == 1)
{
return A[0];
}
if (len == 2)
{
return PIVOT_FLAG;
}
while (i + 1 < len)
{
if (A[i] == A[i + 1])
{
A[k++] = A[i];
}
i += 2;
}
if (len & 1)
{
A[k++] = A[i];
}
return SelectPivot(A, k);
}
int isCandidatePivot(int candidate, int A[], int len)
{
int i = -1;
int count = 0;
i = 0;
while (i < len)
{
if (candidate == A[i++])
count++;
}
if (count >= ((len >> 1) + 1))
return TRUE;
return FALSE;
}
int FindPivot(int A[], int len)
{
int candidate = -1;
int count = 0;
int i = 0;
int* pTemBuff;
int candidate2 = -1, candidate1 = -1;
int isCanPivot = FALSE;
pTemBuff = (int*)malloc(len * sizeof(int));
for (i = 0; i < len; i++)
{
pTemBuff[i] = A[i];
}
candidate = SelectPivot(pTemBuff, len);
if (candidate == -1)
{
return -1;
}
if (PIVOT_FLAG == candidate)
{
candidate1 = pTemBuff[0];
candidate2 = pTemBuff[1];
}
free(pTemBuff);
if (PIVOT_FLAG == candidate)
{
isCanPivot = isCandidatePivot(candidate1, A, len);
if (isCanPivot)
return candidate1;
isCanPivot = isCandidatePivot(candidate1, A, len);
if (isCanPivot)
return candidate2;
}
else
{
isCanPivot = isCandidatePivot(candidate, A, len);
if (isCanPivot)
return candidate;
}
return -1;
}
void dsa_test_random()
{
int count = 0, limit = 100;
int lineCnt = 5;
int i = 0;
int m = 0, n = 0;
int failCount = 0;
int* nums = NULL;
printf("Please enter two number to generate the random number in [-limit, limit].\n\
please enter the count of random number and max limit of random:\n");
printf("the input format is:count,limit\n");
srand((unsigned)time(NULL));
scanf_s("%d,%d", &count, &limit);
for (i = 0; i < count; i++)
{
if (i % lineCnt == 0)
{
printf("\n");
}
printf("%4d ", ramdonInt(limit));
}
INPUT:
printf("\nplease enter two numbers m and n to generate random number in [m, n],m < n:");
scanf_s("%d,%d", &m, &n);
if (m >= n && failCount < 5)
{
printf("make sure the first number is smaller than the second!\n");
failCount++;
goto INPUT;
}
if (failCount >= 5)
{
return;
}
nums = (int*)malloc(count * sizeof(int));
for (i = 0; i < count; i++)
{
if (i % lineCnt == 0)
{
printf("\n");
}
printf("%4d ", nums[i] = random(m, n));
}
quickSort(nums, count);
printf("\nsorted nums:");
for (i = 0; i < count; i++)
{
if (i % lineCnt == 0)
{
printf("\n");
}
printf("%4d ", nums[i]);
}
free(nums);
}
#define PERMUTATION_TEST_CNT 8
#define MAX_PATH_LENGTH 1024
void dsa_permutation_alg_analysis() {
int i = 0;
int* pAns = NULL;
clock_t start, end;
double duration;
int errorcode = -1;
int permuNumByComp[PERMUTATION_TEST_CNT] = { 500, 1000, 2000, 4000, 8000, 16000, 20000, 40000 };
int permuNumByArra[PERMUTATION_TEST_CNT] = { 50000, 100000, 200000, 400000, 800000, 1600000, 3200000, 6400000 };
int permuNumBySwap[PERMUTATION_TEST_CNT] = { 50000, 100000, 200000, 400000, 800000, 1600000, 3200000, 6400000 };
double durationByComp[PERMUTATION_TEST_CNT] = { 0.0 };
double durationByArra[PERMUTATION_TEST_CNT] = { 0.0 };
double durationBySwap[PERMUTATION_TEST_CNT] = { 0.0 };
char currPath[MAX_PATH_LENGTH];
FILE* fp = NULL;
char* pFileName = ".\\data\\permutation.txt";
char filePath[256] = {0};
_getcwd(currPath, MAX_PATH_LENGTH); //derive current path
strrchr(currPath, '\\');
char* pTemp = pFileName;
char* p = NULL;
if(_access(pTemp, 0)){
pTemp = strrchr(pFileName, '\\');
p = pFileName;
memset(filePath, 0, sizeof(filePath));
while (p != pTemp)
{
filePath[i++] = *p++;
}
_mkdir(filePath);
}
fp = fopen(pFileName, "w+");
if (!fp)
{
printf("Fail to open file:%s\n", pFileName);
return;
}
srand((unsigned)time(NULL));
fprintf(fp, "randomPermutationByCompare:\n");
fprintf(fp, " number time\n");
for (i = 0; i < PERMUTATION_TEST_CNT; i++)
{
start = clock();
pAns = randomPermutation(permuNumByComp[i]);
end = clock();
if (!pAns)
{
printf("Fail to generate the permutation!!!\n");
return;
}
if (pAns)
{
free(pAns);
}
durationByComp[i] = duration = (double)(end - start) / CLOCKS_PER_SEC;
printf("\nnumbers:%d, randomPermutation: %.4f seconds, %.4f \n", permuNumByComp[i], duration, log(permuNumByComp[i]));
fprintf(fp, "%10d %10.4f\n", permuNumByComp[i], duration);
if (i > 0)
{
printf("\nduration[%d]/duration[%d]=%.2f\n", i, i - 1, durationByComp[i] / durationByComp[i - 1]);
}
}
fprintf(fp, "randomPermutationByArray:\n");
fprintf(fp, " number time\n");
for (i = 0; i < PERMUTATION_TEST_CNT; i++)
{
start = clock();
pAns = randomPermutationByArray(permuNumByArra[i]);
end = clock();
if (pAns)
{
free(pAns);
}
durationByArra[i] = duration = (double)(end - start) / CLOCKS_PER_SEC;
printf("\nnumbers:%d, randomPermutationByArray: %.4f seconds, %.4f\n", permuNumByArra[i], duration, log(permuNumByArra[i]));
fprintf(fp, "%10d %10.4f\n", permuNumByArra[i], duration);
if (i > 0)
{
printf("\nduration[%d]/duration[%d]=%.2f\n", i, i - 1, durationByArra[i] / durationByArra[i - 1]);
}
}
fprintf(fp, "randomPermutationBySwap:\n");
fprintf(fp, " number time\n");
for (i = 0; i < PERMUTATION_TEST_CNT; i++)
{
start = clock();
pAns = randomPermutationBySwap(permuNumBySwap[i]);
end = clock();
if (pAns)
{
free(pAns);
}
durationBySwap[i] = duration = (double)(end - start) / CLOCKS_PER_SEC;
printf("\nnumbers:%d, randomPermutationBySwap: %.4f seconds, %.4f\n", permuNumBySwap[i], duration, log(permuNumBySwap[i]));
fprintf(fp, "%10d %10.4f\n", permuNumBySwap[i], duration);
if (i > 0)
{
printf("\nduration[%d]/duration[%d]=%.2f\n", i, i - 1, durationBySwap[i] / durationBySwap[i - 1]);
}
}
fclose(fp);
}
void dsaPrimeTest()
{
unsigned long d = 0;
int res = 0;
unsigned long* pPrimeTable = NULL;
double x = 1.0;
int n = 0;
printf("\nPrime test, input -1 to end test:\n");
printf("1. Dec to binary test. \n");
while (d != -1)
{
printf(">>:");
scanf("%uL", &d);
if (d == -1)
{
break;
}
decToBin(d);
}
d = 0;
printf("\n2. Prime Number test, please enter a number(-1 to quit):\n");
while (d != -1)
{
printf(">>:");
scanf("%uL", &d);
if (d == -1)
{
break;
}
res = isPrimeNum(d);
printf("%d is %s \n", d, res ? "a prime" : "NOT a prime");
}
printf("\n3. Input number to generate prime table:\n");
printf(">>:");
scanf("%uL", &d);
pPrimeTable = makePrimeTable(d);
if (pPrimeTable)
free(pPrimeTable);
printf("\n4. QuickPow test, enter base and exponets(0 to quit)\n");
printf("input format: base exponent\n");
while (x != 0.0)
{
printf(">>:");
scanf("%lf %d", &x, &n);
if (x == 0.0 && n < 0)
{
printf("invalid input\n");
break;
}
printf("pow(%f,%d) = %.4f:\n", x, n, quickPow(x, n));
}
}
void dsaPivotTest()
{
//int arrayA[] = { 3,3,4,2,4,4,2,4 };
//int arrayA[] = { 3,3,4,2,4,4,2,4, 4 };
//int arrayA[] = { 3,3,4,2,4,4,2,4, 4 };
int arrayA[64] = { 0 };
int candidate = -1;
int len = 64;
int i = 0, d = 0, k = 0 ;
char buf[128];
printf("\n******dsaPivotTest********\n");
//printNums(arrayA, sizeof(arrayA) / sizeof(arrayA[0]));
printf("Please enter at most 64 numbers to test:\n");
fgets(buf, sizeof(buf), stdin);
for (i = 0; i < len ; i++)
{
d = buf[i];
if (d == ' ' || d == '\n' || d == '\t' || d == ',')
continue;
if (d == '\0')
break;
arrayA[k++] = d - '0';
}
candidate = FindPivot(arrayA, k);
if (candidate != -1)
{
printf("\nPivot is:%d\n", candidate);
}
else
{
printf("\nPivot is not present\n");
}
}
void dsa_chap2_test()
{
char c = 0;
dsaPivotTest();
dsaPrimeTest();
printf("\n\nDo you want to test the performance of permutation/random algorithm?...Y or N\n");
while (c != 'N' && c != 'n' && c != 'Y' && c != 'y')
{
scanf("%c", &c);
}
if (c == 'N' || c == 'n')
{
return;
}
else if (c == 'y' || c == 'Y')
{
printf("\nPlease select the algorithm to test: \n P: Permutation \n R: Random\n ");
do
{
scanf("%c", &c);
} while (c != 'P' && c != 'R');
if (c == 'P')
{
dsa_permutation_alg_analysis();
}
else if (c == 'R')
{
dsa_test_random();
}
}
}
|
C | ///
// Buffers.c
//
// Vertex and element buffer implementations.
//
// Author: Warren R. Carithers
// Date: 2017/02/11 22:34:54
//
// This file should not be modified by students.
///
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif
#ifndef __APPLE__
#include <GL/glew.h>
#endif
#include <GLFW/glfw3.h>
#include "Buffers.h"
#include "Canvas.h"
///
// initBuffer(buf) - reset the supplied BufferSet to its "empty" state
//
// @param buf - which buffer to reset
///
void initBuffer( BufferSet *buf ) {
buf->vbuffer = buf->ebuffer = 0;
buf->numElements = 0;
buf->vSize = buf->eSize = buf->tSize = buf->cSize = buf->nSize = 0;
buf->bufferInit = false;
}
///
// dumpBuffer(buf) - dump the contents of a BufferSet
//
// @param which - description of the buffer
// @param buf - the buffer to dump
///
void dumpBuffer( const char *which, BufferSet *buf ) {
printf( "Dumping buffer %s (%s):\n", which,
buf->bufferInit ? "initialized" : "not initialized" );
printf( " IDs: v %u e %u #elements: %d\n", buf->vbuffer,
buf->ebuffer, buf->numElements );
printf( " Sizes: v %ld e %ld t %ld c %ld n %ld\n", buf->vSize,
buf->eSize, buf->tSize, buf->cSize, buf->nSize );
}
///
// makeBuffer() - make a vertex or element array buffer
//
// @param target - which type of buffer to create
// @param data - source of data for buffer (or NULL)
// @param size - desired length of buffer
//
// @return the ID of the new buffer
//
GLuint makeBuffer( GLenum target, const void *data, GLsizeiptr size )
{
GLuint buffer;
glGenBuffers( 1, &buffer );
glBindBuffer( target, buffer );
glBufferData( target, size, data, GL_STATIC_DRAW );
return( buffer );
}
///
// createBuffers(buf,canvas) create a set of buffers for the object
// currently held in 'canvas'.
//
// @param B - the BufferSet to be modified
// @param C - the Canvas we'll use for drawing
///
void createBuffers( BufferSet *B, Canvas *C ) {
// reset this BufferSet if it has already been used
if( B->bufferInit ) {
// must delete the existing buffer IDs first
glDeleteBuffers( 1, &(B->vbuffer) );
glDeleteBuffers( 1, &(B->ebuffer) );
initBuffer( B );
}
///
// vertex buffer structure
//
// our vertex buffers will always have locations, but the
// other fields may or may not be present; this depends on
// how the shape was created
//
// data components offset to beginning
// [ locations ] XYZW 0
// [ colors ] RGBA vSize
// [ normals ] XYZ vSize+cSize
// [ t. coords ] UV vSize+cSize+nSize
///
// get the vertex count
B->numElements = canvasNumVertices( C );
// if there are no vertices, there's nothing for us to do
if( B->numElements < 1 ) {
return;
}
// OK, we have vertices!
float *points = canvasGetVertices( C );
// #bytes = number of elements * floats/element * bytes/float
B->vSize = B->numElements * 4 * sizeof(float);
// accumulate the total vertex buffer size
GLsizeiptr vbufSize = B->vSize;
// get the color data (if there is any)
float *colors = canvasGetColors( C );
if( colors != NULL ) {
B->cSize = B->numElements * 4 * sizeof(float);
vbufSize += B->cSize;
}
// get the normal data (if there is any)
float *normals = canvasGetNormals( C );
if( normals != NULL ) {
B->nSize = B->numElements * 3 * sizeof(float);
vbufSize += B->nSize;
}
// get the (u,v) data (if there is any)
float *uv = canvasGetUV( C );
if( uv != NULL ) {
B->tSize = B->numElements * 2 * sizeof(float);
vbufSize += B->tSize;
}
// get the element data
GLuint *elements = canvasGetElements( C );
// #bytes = number of elements * bytes/element
B->eSize = B->numElements * sizeof(GLuint);
// first, create the connectivity buffer
B->ebuffer = makeBuffer( GL_ELEMENT_ARRAY_BUFFER, elements, B->eSize );
// next, the vertex buffer, containing vertices and "extra" data
// note that we use glBufferSubData() calls to do the copying
B->vbuffer = makeBuffer( GL_ARRAY_BUFFER, NULL, vbufSize );
// copy in the location data
glBufferSubData( GL_ARRAY_BUFFER, 0, B->vSize, points );
// offsets to subsequent sections are the sum of
// the preceding section sizes (in bytes)
GLintptr offset = B->vSize;
// add in the color data (if there is any)
if( B->cSize > 0 ) {
glBufferSubData( GL_ARRAY_BUFFER, offset, B->cSize, colors );
offset += B->cSize;
}
// add in the normal data (if there is any)
if( B->nSize > 0 ) {
glBufferSubData( GL_ARRAY_BUFFER, offset, B->nSize, normals );
offset += B->nSize;
}
// add in the (u,v) data (if there is any)
if( B->tSize > 0 ) {
glBufferSubData( GL_ARRAY_BUFFER, offset, B->tSize, uv );
offset += B->tSize;
}
// sanity check!
if( offset != vbufSize ) {
fprintf( stderr,
"*** selectBuffers: size mismatch, offset %ld vbufSize %ld\n",
offset, vbufSize );
}
// NOTE: 'points', 'colors', etc. are dynamically allocated, but
// we don't free them here because they will be freed at the next
// call to clear() or the get*() functions
// finally, mark it as set up
B->bufferInit = true;
}
|
C | //Tyler Harley and Margaux LeBlanc
//11/3/14
//Graphics
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <color.h>
#include <list.h>
#include <image.h>
#include <math.h>
#include "graphics.h"
#include "drawstate.h"
#include "light.h"
#include "polygon.h"
#include "matrix.h"
#include "view.h"
#include "model.h"
#include "bezier.h"
//Curve and surface functions
//sets the z buffer flag to 1 and the curve points to the X-axis between 0 and 1
void bezierCurve_init(BezierCurve *b){
int i;
if(!b){
fprintf(stderr, "Bezier Curve not found\n");
return;
}
else{
b->zbuffer = 1;
for(i=0; i<4; i++){
b->controlPt[i].val[0] = .5;
b->controlPt[i].val[1] = 0; //set y and z to 0 so lies on x axis
b->controlPt[i].val[2] = 0;
b->controlPt[i].val[3] = 1;
}
}
}
//sets the zbuffer flat to 1 and the surface to the X-Z plane between (0,0) and (1,1)
void bezierSurface_init(BezierSurface *b){
int i;
if(!b){
fprintf(stderr, "Bezier Surface not found\n");
return;
}
else{
b->zbuffer = 1;
for(i=0; i<16; i++){
b->controlPt[i].val[0] = .5; //put it in x-z plane
b->controlPt[i].val[1] = 0;
b->controlPt[i].val[2] = .5;
b->controlPt[i].val[3] = 1;
}
}
}
//Sets the control points of the BezierCurve to the four points in the vlist array
void bezierCurve_set(BezierCurve *b, Point *vlist){
int i;
//do I have to check if b and vlist are not null?
//copy vlist to bezier curve
for(i=0; i<4; i++){
b->controlPt[i] = vlist[i];
}
}
//Sets the control points of the BezierSurface to the 16 points in the vlist array
void bezierSurface_set(BezierSurface *b, Point *vlist){
//do I have to check if b and vlist are not null?
int i;
for(i=0; i<16; i++){
b->controlPt[i] = vlist[i];
}
}
//sets the zbuffer flag to the given value
void bezierCurve_zBuffer(BezierCurve *b, int flag){
b->zbuffer = flag;
}
//sets the zbuffer flag tot he given value
void bezierSurface_zBuffer(BezierSurface *b, int flag){
b->zbuffer = flag;
}
void deCasteljau(Point *src, Point *dst, Point *dst2){
dst[0] = src[0];
dst[1].val[0] = .5*(src[0].val[0] + src[1].val[0]);
dst[1].val[1] = .5*(src[0].val[1] + src[1].val[1]);
dst[1].val[2] = .5*(src[0].val[2] + src[1].val[2]);
dst[1].val[3] = 1.0;
dst[2].val[0] = .5*(dst[1].val[0]) + .25*(src[1].val[0]+ src[2].val[0]);
dst[2].val[1] = .5*(dst[1].val[1]) + .25*(src[1].val[1]+ src[2].val[1]);
dst[2].val[2] = .5*(dst[1].val[2]) + .25*(src[1].val[2]+ src[2].val[2]);
dst[2].val[3] = 1.0;
dst2[3] = src[3];
dst2[2].val[0] = .5*(src[2].val[0] + src[3].val[0]);
dst2[2].val[1] = .5*(src[2].val[1] + src[3].val[1]);
dst2[2].val[2] = .5*(src[2].val[2] + src[3].val[2]);
dst2[2].val[3] = 1.0;
dst2[1].val[0] = .5*(dst2[2].val[0]) + .25*(src[1].val[0] + src[2].val[0]);
dst2[1].val[1] = .5*(dst2[2].val[1]) + .25*(src[1].val[1] + src[2].val[1]);
dst2[1].val[2] = .5*(dst2[2].val[2]) + .25*(src[1].val[2] + src[2].val[2]);
dst2[1].val[3] = 1.0;
dst[3].val[0] = .5*(dst[2].val[0] + dst2[1].val[0]);
dst[3].val[1] = .5*(dst[2].val[1] + dst2[1].val[1]);
dst[3].val[2] = .5*(dst[2].val[2] + dst2[1].val[2]);
dst[3].val[3] = 1.0;
dst2[0] = dst[3];
//return dst;
}
/*
Draws the bezier curve, given in screen coords, into the image using the
given color. Uses an appropriate number of line segments to draw the
curve. Ex) if the bounding box of the control points is less than 10 pixels in the largest dimension, then it is reasonable to draw the lines btw the
control points as an approximation to the curve
*/
void bezierCurve_draw(BezierCurve *b, Image *src, Color c, int zBufferFlag){
int thresh = 10;
int i;
double ymin = b->controlPt[0].val[1];
double ymax = b->controlPt[0].val[1];
double xmin = b->controlPt[0].val[0];
double xmax = b->controlPt[0].val[0];
Polyline pl;
BezierCurve q, r;
Point vlistR[4];
Point vlistQ[4];
//find bounding box
for(i=1; i<4; i++){
if(b->controlPt[i].val[0] < xmin)
xmin = b->controlPt[i].val[0];
else if(b->controlPt[i].val[0] > xmax)
xmax = b->controlPt[i].val[0];
if(b->controlPt[i].val[1] < ymin)
ymin = b->controlPt[i].val[1];
else if(b->controlPt[i].val[1] > ymax)
ymax = b->controlPt[i].val[1];
}
//if bounding box is less than ten pexels, draw
if( (ymax-ymin <thresh) && (xmax-xmin < thresh) ){
//draw lines
/*for(i=0; i<3; i++){
line_set(&l, b->controlPt[i], b->controlPt[i+1]);
line_draw(&l, src, c);
printf("line %d drawing\n", 1 + i);
}*/
polyline_init(&pl);
polyline_set(&pl, 4, b->controlPt);
polyline_draw(&pl, src, c, zBufferFlag);
return;
}
//all in the recursion
else{
deCasteljau(b->controlPt, vlistQ, vlistR);
bezierCurve_set(&q, vlistQ);
bezierCurve_set(&r, vlistR);
bezierCurve_draw(&q, src, c, zBufferFlag);
bezierCurve_draw(&r, src, c, zBufferFlag);
}
}
//bezier curve and surface module functions
/*
Use the de Casteljau algorithm to subdivide the Bezier surface divisions
times. Then draw either the lines connecting the control points to the module.
For example if divisions is 1, the four original Bezier curve control points will be used to generate eight control points and two new Bezier curves.
Then the algorithm will add six lines to the module, three for each of the
smaller Bezier curves.
*/
void module_bezierCurve(Module *m, BezierCurve *b, int divisions){
Line l;
BezierCurve q, r;
Point vlistR[4];
Point vlistQ[4];
int i;
if(divisions == 0){
for(i=0; i<3; i++){
line_set(&l, b->controlPt[i], b->controlPt[i+1]);
module_line(m, &l);
}
}
else{
deCasteljau(b->controlPt, vlistQ, vlistR);
bezierCurve_set(&q, vlistQ);
bezierCurve_set(&r, vlistR);
module_bezierCurve(m, &q, divisions - 1);
module_bezierCurve(m, &r, divisions - 1);
}
}
// find the normals of a triangle
void findNormals(Polygon *p){
int i;
Vector nList[3];
Vector v1, v2;
//printf("within findNormals");
point_print(&p->vertex[0]);
//printf("%f\n", x);
//vector_set(&v1, 1, 0, 0);
//vector_set(&v1, p->vertex[0].val[0] - p->vertex[1].val[0],
// p->vertex[0].val[1] - p->vertex[1].val[1],
// p->vertex[0].val[2] - p->vertex[1].val[2]);
/*vector_set(&v2, p->vertex[2].val[0] - p->vertex[1].val[0],
p->vertex[2].val[1] - p->vertex[1].val[1],
p->vertex[2].val[2] - p->vertex[1].val[1]);
for(i=0; i<3; i++){
vector_cross(&v1, &v2, &nList[i]);
}*/
}
/*
Use the de Casteljau algorithm to subidivide the bezier surface divisions
times, then draw either the lines connecting the control points, if solid is
0, or draw triangles using the four corner control points.
*/
void module_bezierSurface(Module *m, BezierSurface *b, int divisions, int solid){
Polygon *p;
Line l;
BezierSurface s, t, u, v;
Point vlistR[16], vlistInR[4];
Point vlistQ[16], vlistInQ[4];
Point vlistS[16];
Point vlistT[16];
Point vlistU[16];
Point vlistV[16];
Point vlistPoly[3];
Vector v1, v2, v3, v4;
Vector vList[3];
int i, j, k;
p = polygon_create();
polygon_init(p);
if(divisions == 0){
if(solid == 0){
for(i=0; i<=12; i+=4){
line_set(&l, b->controlPt[i], b->controlPt[i+1]);
module_line(m, &l);
line_set(&l, b->controlPt[i+1], b->controlPt[i+2]);
module_line(m, &l);
line_set(&l, b->controlPt[i+2], b->controlPt[i+3]);
module_line(m, &l);
}
//draw in other direction now
for(j=0; j<4; j++){
line_set(&l, b->controlPt[j], b->controlPt[j+4]);
module_line(m, &l);
line_set(&l, b->controlPt[j+4], b->controlPt[j+8]);
module_line(m, &l);
line_set(&l, b->controlPt[j+8], b->controlPt[j+12]);
module_line(m, &l);
}
}
else{
//put in polygon triangles
//first one is a special case
vlistPoly[0] = b->controlPt[0];
vlistPoly[1] = b->controlPt[3];
vlistPoly[2] = b->controlPt[12];
polygon_set(p, 3, &vlistPoly);
polygon_setSided(p, 0);
// find normals
vector_set(&v1, vlistPoly[1].val[0] - vlistPoly[0].val[0],
vlistPoly[1].val[1] - vlistPoly[0].val[1],
vlistPoly[1].val[2] - vlistPoly[0].val[2]);
vector_set(&v2, vlistPoly[2].val[0] - vlistPoly[0].val[0],
vlistPoly[2].val[1] - vlistPoly[0].val[1],
vlistPoly[2].val[2] - vlistPoly[0].val[2]);
vector_cross(&v1, &v2, &vList[0]);
// normal for control point 3
vector_set(&v1, vlistPoly[0].val[0] - vlistPoly[1].val[0],
vlistPoly[0].val[1] - vlistPoly[1].val[1],
vlistPoly[0].val[2] - vlistPoly[1].val[2]);
vector_set(&v2, vlistPoly[2].val[0] - vlistPoly[1].val[0],
vlistPoly[2].val[1] - vlistPoly[1].val[1],
vlistPoly[2].val[2] - vlistPoly[1].val[2]);
vector_cross(&v1, &v2, &vList[1]);
// normal for control point 12
vector_set(&v1, vlistPoly[0].val[0] - vlistPoly[2].val[0],
vlistPoly[0].val[1] - vlistPoly[2].val[1],
vlistPoly[0].val[2] - vlistPoly[2].val[2]);
vector_set(&v2, vlistPoly[1].val[0] - vlistPoly[2].val[0],
vlistPoly[1].val[1] - vlistPoly[2].val[1],
vlistPoly[1].val[2] - vlistPoly[2].val[2]);
vector_cross(&v1, &v2, &vList[2]);
polygon_setNormals(p, 3, &vList);
module_polygon(m, p);
vlistPoly[0] = b->controlPt[15];
vlistPoly[1] = b->controlPt[3];
vlistPoly[2] = b->controlPt[12];
polygon_set(p, 3, &vlistPoly);
polygon_setSided(p, 0);
// normal for control point 15
vector_set(&v1, vlistPoly[1].val[0] - vlistPoly[0].val[0],
vlistPoly[1].val[1] - vlistPoly[0].val[1],
vlistPoly[1].val[2] - vlistPoly[0].val[2]);
vector_set(&v2, vlistPoly[2].val[0] - vlistPoly[0].val[0],
vlistPoly[2].val[1] - vlistPoly[0].val[1],
vlistPoly[2].val[2] - vlistPoly[0].val[2]);
vector_cross(&v1, &v2, &vList[0]);
polygon_setNormals(p, 3, &vList);
module_polygon(m, p);
}
}
else{
for(i=0; i<4; i++){
deCasteljau(&(b->controlPt[i*4]), &(vlistQ[i*4]), &(vlistR[i*4]));
}
for(j=0; j<4; j++){
for(k=0; k<4; k++){
vlistInQ[k] = vlistQ[j+k*4];
vlistInR[k] = vlistR[j+k*4];
}
deCasteljau(vlistInQ, &(vlistS[j*4]), &(vlistT[j*4]));
deCasteljau(vlistInR, &(vlistU[j*4]), &(vlistV[j*4]));
//deCasteljau(&(vlistS[i*4]), &(vlistW[i*4]), &(vlistX[i*4]));
}
bezierSurface_set(&s, vlistS);
bezierSurface_set(&t, vlistT);
bezierSurface_set(&u, vlistU);
bezierSurface_set(&v, vlistV);
module_bezierSurface(m, &s, divisions - 1, solid);
module_bezierSurface(m, &t, divisions - 1, solid);
module_bezierSurface(m, &u, divisions - 1, solid);
module_bezierSurface(m, &v, divisions - 1, solid);
printf("bezier surface added to model\n");
}
polygon_free(p);
}
// makes and adds a sphere out of bezier surfaces
void module_sphere(Module *md, int divisions, int solid){
Point pt[16];
BezierSurface bs;
point_set3D(&pt[0], 0, 0, .5);
point_set3D(&pt[3], .5*cos(22.5*M_PI/180.0)*sin(0),.5*sin(22.5*M_PI/180.0)*sin(0), .5*cos(0));
point_set3D(&pt[6], .5*cos(M_PI/4.0)*sin(0),.5*sin(M_PI/4.0)*sin(0), .5*cos(0));
point_set3D(&pt[9], .5*cos(67.5*M_PI/180.0)*sin(0),.5*sin(67.5*M_PI/180.0)*sin(0), .5*cos(0));
point_set3D(&pt[12], .5, 0, 0);
point_set3D(&pt[1], .5*cos(0)*sin(M_PI/4.0),.5*sin(0)*sin(M_PI/4.0), .5*cos(M_PI/4.0));
point_set3D(&pt[10], .5*cos(67.5*M_PI/180.0)*sin(M_PI/4.0),.5*sin(67.5*M_PI/180.0)*sin(M_PI/4.0), .5*cos(M_PI/4.0));
point_set3D(&pt[7], .5*cos(M_PI/4.0)*sin(M_PI/4.0),.5*sin(M_PI/4.0)*sin(M_PI/4.0), .5*cos(M_PI/4.0));
point_set3D(&pt[4], .5*cos(22.5*M_PI/180.0)*sin(M_PI/4.0),.5*sin(22.5*M_PI/180.0)*sin(M_PI/4.0), .5*cos(M_PI/4.0));
point_set3D(&pt[13], .5*cos(M_PI/2.0)*sin(M_PI/4.0),.5*sin(M_PI/2.0)*sin(M_PI/4.0), .5*cos(M_PI/4.0));
/*
point_set3D(&pt[2], .5*cos(0)*sin(M_PI/3.0),.5*sin(0)*sin(M_PI/3.0), .5*cos(M_PI/3.0));
point_set3D(&pt[6], .5*cos(22.5*M_PI/180.0)*sin(M_PI/3),.5*sin(22.5*M_PI/180.0)*sin(M_PI/3.0), .5*cos(M_PI/6));
point_set3D(&pt[9], .5*cos(M_PI/4.0)*sin(M_PI/3.0),.5*sin(M_PI/4.0)*sin(M_PI/3.0), .5*cos(M_PI/3.0));
point_set3D(&pt[12], .5*cos(67.5*M_PI/180.0)*sin(M_PI/3.0),.5*sin(67.5*M_PI/180.0)*sin(M_PI/3.0), .5*cos(M_PI/3));
point_set3D(&pt[15], .5*cos(M_PI/2.0)*sin(M_PI/3),.5*sin(M_PI/2.0)*sin(M_PI/3.0), .5*cos(M_PI/3.0));
*/
point_set3D(&pt[2], 0, .5, 0);
point_set3D(&pt[5], 0, .5, 0);
point_set3D(&pt[8], 0, .5, 0);
point_set3D(&pt[11], 0, .5, 0);
point_set3D(&pt[14], 0, .5, 0);
point_set3D(&pt[15], 0, .5, 0);
bezierSurface_set(&bs, pt);
module_bezierSurface(md, &bs, divisions, solid);
}
|
C | #include<stdio.h>
int main()
{
int a,b,num1,num2,sum;
while(1)
{
int carcnt=0,cf=0;
scanf("%d%d",&a,&b);
if(a==0&&b==0)
break;
while(a!=0||b!=0)
{
num1=a%10; num2=b%10; sum=cf+num1+num2;
if(sum>=10)
{
carcnt++;
cf=1;
}
else
cf=0;
a/=10;
b/=10;
}
if(carcnt==0)
printf("No carry operation.\n");
else if(carcnt==1)
printf("1 carry operation.\n");
else
printf("%d carry operations.\n",carcnt);
}
return 0;
} |
C | #include <stdio.h>
int main(){
char a,b,c,d,e;
printf("Informe 5 letras:\n");
scanf("%c%c%c%c%c",&a,&b,&c,&d,&e);
if(a == e && b == d && c == c && d == b && e == a){
printf("a palavra eh palindromo\n");
exit(0);
}else{
printf("a palavra nao eh palindromo\n");
exit(0);
}
return 0;
}
|
C | #ifndef __DHERA_STACK__
#define __DHERA_STACK__
/*
defines stack, pop and push fucntions.
*/
typedef struct Stack
{
float info;
struct Stack * next;
}Stack;
void push(Stack ** top, float input);
float pop(Stack** top);
#endif |
C | #include "holberton.h"
/**
* print_last_digit - print_last_digit
*
*@n: variable the number
*
* Return: Always 0 (Success)
*/
int print_last_digit(int n)
{
if (n < 0)
{
n = n % 10;
n = n * -1;
_putchar(n + '0');
}
else
{
n = n % 10;
_putchar(n + '0');
}
return (n);
}
|
C | #include <limits.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include "graph.h"
#include "deque.h"
struct graph {
VertexHashSet *vertices; //used as just a set rather than a map of vertices to weights
};
Graph *makeGraph() {
Graph *graph = malloc(sizeof(*graph));
graph->vertices = makeEmptySetVertex();
return graph;
}
VertexHashSet *vertices(Graph *graph) {
return graph->vertices;
}
Edge *makeEdge(Vertex *vertex1, Vertex *vertex2, int weight) {
Edge *edge = malloc(sizeof(*edge));
edge->vertex1 = vertex1;
edge->vertex2 = vertex2;
edge->weight = weight;
return edge;
}
EdgeHashSet *edges(Graph *graph) {
VertexSetIterator *vertexIterator = iteratorVertex(graph->vertices);
EdgeHashSet *edgeSet = makeEmptySetEdge();
while (hasNextVertex(vertexIterator)) {
Vertex *vertex = nextVertex(vertexIterator);
VertexSetIterator *neighbors = iteratorVertex(vertex->adjacent);
while (hasNextVertex(neighbors)) {
Vertex *neighbor = nextVertex(neighbors);
addElementEdge(edgeSet, makeEdge(vertex, neighbor, weightToVertex(vertex->adjacent, neighbor))); //guarantee that each edge is only printed once
}
free(neighbors);
}
free(vertexIterator);
return edgeSet;
}
VertexHashSet *neighbors(Graph *graph, Vertex *vertex) {
return vertex->adjacent;
}
Edge *addEdge(Graph *graph, Vertex *vertex1, Vertex *vertex2, int weight) { //the returned edge is newly malloc'd and must be freed when done being used
if (vertex1 == vertex2) return NULL; //can't have a vertex connected to itself
else {
addElementVertex(vertex1->adjacent, vertex2, weight);
return makeEdge(vertex1, vertex2, weight);
}
}
Vertex *addVertex(Graph *graph, VertexData data) { //the returned vertex is part of the graph, so it should NOT be freed
Vertex *vertex = malloc(sizeof(*vertex));
vertex->data = data;
vertex->adjacent = makeEmptySetVertex();
addElementVertex(graph->vertices, vertex, 0);
return vertex;
}
void deleteEdge(Graph *graph, Edge *edge) { //will free the edge passed in
removeElementVertex(edge->vertex1->adjacent, edge->vertex2);
removeElementVertex(edge->vertex2->adjacent, edge->vertex1);
free(edge);
}
void freeVertex(Vertex *vertex) {
freeSetVertex(vertex->adjacent);
free(vertex);
}
void deleteVertex(Graph *graph, Vertex *vertex) { //takes care of freeing the vertex as it is no longer needed
removeElementVertex(graph->vertices, vertex);
VertexSetIterator *vertices = iteratorVertex(graph->vertices);
while (hasNextVertex(vertices)) removeElementVertex(nextVertex(vertices)->adjacent, vertex);
free(vertices);
freeVertex(vertex);
}
void printVertex(Vertex *vertex) {
printf("%c\n", vertex->data);
}
void printGraph(Graph *graph) {
VertexSetIterator *vertices = iteratorVertex(graph->vertices);
puts("Vertices:");
while (hasNextVertex(vertices)) {
Vertex *vertex = nextVertex(vertices);
printVertex(vertex);
}
free(vertices);
puts("Edges:");
EdgeHashSet *edgeSet = edges(graph);
EdgeSetIterator *edgeIterator = iteratorEdge(edgeSet);
while (hasNextEdge(edgeIterator)) {
const Edge *edge = nextEdge(edgeIterator);
printf("%c -(%d)-> %c\n", edge->vertex1->data, weightToVertex(edge->vertex1->adjacent, edge->vertex2), edge->vertex2->data);
}
free(edgeIterator);
freeSetEdge(edgeSet);
}
void traverseDepthFirst(Graph *graph, Vertex *start, void (*visit)(Vertex *)) {
VertexHashSet *visited = makeEmptySetVertex(); //used as just a set rather than a map of vertices to weights
addElementVertex(visited, start, 0);
Deque *stack = makeEmptyDeque();
pushFront(start, stack);
while (!isEmptyDeque(stack)) { //while some connected vertices haven't yet been looked at
Vertex *current = popFront(stack); //look at the current vertex
(*visit)(current);
VertexHashSet *adjacent = neighbors(graph, current);
VertexSetIterator *neighborIterator = iteratorVertex(adjacent);
while (hasNextVertex(neighborIterator)) { //add any unadded neighbors to the queue
Vertex *next = nextVertex(neighborIterator);
if (!containsVertex(visited, next)) {
addElementVertex(visited, next, 0);
pushFront(next, stack);
}
}
}
freeSetVertex(visited);
freeDeque(stack);
}
int shortestPath(Graph *graph, Vertex *start, Vertex *end) {
//Store the shortest distances found from start to vertices (or INT_MAX if none exists)
VertexHashSet *shortest = makeEmptySetVertex(); //stores the current shortest path to each vertex
VertexSetIterator *vertices = iteratorVertex(graph->vertices);
while (hasNextVertex(vertices)) {
Vertex *vertex = nextVertex(vertices);
if (vertex == start) addElementVertex(shortest, vertex, 0); //only known one
else addElementVertex(shortest, vertex, INT_MAX);
}
free(vertices);
//Calculate shortest distances
unsigned int vertexCount = size(graph->vertices);
for (unsigned int i = 1; i != vertexCount; i++) { //if no negative loops exist, longest possible paths traverses V-1 vertices
VertexSetIterator *vertices = iteratorVertex(graph->vertices);
while (hasNextVertex(vertices)) {
Vertex *examinedVertex = nextVertex(vertices);
VertexSetIterator *possiblyAdjacent = iteratorVertex(graph->vertices);
while (hasNextVertex(possiblyAdjacent)) {
Vertex *adjacentCandidate = nextVertex(possiblyAdjacent);
if (containsVertex(adjacentCandidate->adjacent, examinedVertex)) { //look for a vertex that can reach this one
const int otherDistance = weightToVertex(shortest, adjacentCandidate);
if (otherDistance != INT_MAX) { //make sure the other vertex has been reached from start
const int currentWeight = weightToVertex(shortest, examinedVertex); //old shortest path
const int newWeight = otherDistance + weightToVertex(adjacentCandidate->adjacent, examinedVertex); //new shortest path
if (newWeight < currentWeight) { //update shortest value in the set
removeElementVertex(shortest, examinedVertex);
addElementVertex(shortest, examinedVertex, newWeight);
}
}
}
}
free(possiblyAdjacent);
}
free(vertices);
}
//Find path from resulting distances
const int result = weightToVertex(shortest, end);
if (result == INT_MAX) { //could not get to end
freeSetVertex(shortest);
return -1;
}
else {
Vertex *pathVertex = end;
Deque *visitedStack = makeEmptyDeque();
while (pathVertex != start) { //go backward from end to start
pushFront(pathVertex, visitedStack);
const int minDistance = weightToVertex(shortest, pathVertex);
VertexSetIterator *possiblyAdjacent = iteratorVertex(graph->vertices);
while (hasNextVertex(possiblyAdjacent)) {
Vertex *adjacentCandidate = nextVertex(possiblyAdjacent);
//Look for a vertex that can reach pathVertex and matches the minimum path length calculated before
if (containsVertex(adjacentCandidate->adjacent, pathVertex)) {
const int otherDistance = weightToVertex(shortest, adjacentCandidate);
if (otherDistance != INT_MAX && otherDistance + weightToVertex(adjacentCandidate->adjacent, pathVertex) == minDistance) {
pathVertex = adjacentCandidate;
break; //no need to look for any other path
}
}
}
free(possiblyAdjacent);
}
freeSetVertex(shortest);
printVertex(start); //print the final vertex too (since loop ends when pathVertex == start)
while (!isEmptyDeque(visitedStack)) printVertex(popFront(visitedStack)); //print in reverse order
freeDeque(visitedStack);
return result;
}
}
void freeGraph(Graph *graph) {
VertexSetIterator *vertices = iteratorVertex(graph->vertices);
while (hasNextVertex(vertices)) deleteVertex(graph, nextVertex(vertices));
free(vertices);
freeSetVertex(graph->vertices);
free(graph);
} |
C |
/*
* Copyright (c) 1991-1997 Science Applications International Corporation.
*
* NAME
* solve_via_svd -- Perform Singular Value Decomposition.
* FILE
* solve_via_svd.c
* SYNOPSIS
* int
* solve_via_svd (icov, nd, np, maxp, at, d, damp, cnvgtst, condit, xsol,
* covar, data_importances, applied_damping, rank)
* int icov; (i) Compute covariance matrix: 1 = No; 2 = Yes
* int nd; (i) Number of data (rows; observations)
* int np; (i) Number of parameters (columns)
* int maxp; (i) Leading dimension of at[] and covar[]
* double *at; (i) Transpose of the derviative (system) matrix
* double *d; (i) Data (residual) vector
* double damp; (i) User-specified percent damping to be applied
* to diagonal elements of at[] [g[]]. That
* is damping as a percent of the largest
* singular value. If damp < 0.0, only damp
* when condition number > 30.0.
* double *cnvgtst; (o) Convergence test measure of Paige and
* Saunders (1982).
* double condit[0]; (o) True condition number of non-zero singular
* values returned from dsvdc. That is,
* largest sval/smallest sval calculated
* before scaling limit enforced.
* double condit[1]; (o) Effective condition number of non-zero
* singular values. In this case, the actual
* largest sval/smallest sval retained for
* use in obtaining solution.
* double *xsol; (o) Solution (adjustment) vector
* double covar[][]; (o) Model covariance matrix [square-symmetric]
* double *data_importances: (o) Hypocentral data importance vector
* double *applied_damping: (o) Percent damping actually applied to the
* diagonal elements of at[] [g[]]. If
* damp < 0.0, only apply damping when
* condition number > 30.0.
* double rank: (o) Effective rank of matrix
* DESCRIPTION
* Function. Compute hypocentral solution vector by Singular Value
* Decomposition (SVD) of a given system matrix. We decompose an
* arbitrary NxM rectangular matrix, G, via the method of SVD into its
* component parts using a standard LINPACK routine. This
* mini-driver determines a solution of the form:
* G = U * sval * V-transpose, where U and V contain the left
* and right singular vectors, respectively, while sval
* holds the corresponding singular values.
* It is the rank of G that determines the maximum number of possible
* singular values that are calculated. So, if nd < np, then the
* maximum rank of at[] is nd, and only nd singular values can be
* calculated. If the variable, info, is non-zero, then the number
* of singular values will not be np.
* Given, k = MIN(nd, np)
* Subr. dsvdc fills U with left singular vectors stored as,
* | vector 1 vector 2 ... vector k |
* | u1(1) u2(1) ... uk(1) |
* | u1(2) u2(2) ... uk(1) |
* u(np,np) = | . . ... . |
* | . . ... . |
* | . . ... . |
* | u1(np) u2(np) ... uk(np) |
* Given, k = MIN(nd, np)
* Subr. dsvdc fills V with right singular vectors stored as,
* | vector 1 vector 2 ... vector k |
* | v1(1) v2(1) ... vk(1) |
* | v1(2) v2(2) ... vk(1) |
* v(nd,nd) = | . . ... . |
* | . . ... . |
* | . . ... . |
* | v1(nd) v2(nd) ... vk(nd) |
* Then given,
* G * m = d
* Subr. dsvdc decomposes G as,
* G => ( V * LAMBDA * U-transpose )
* So,
* G * m = ( V * LAMBDA * U-transpose ) * m
* And,
* m = ( U * LAMBDA-inverse * V-transpose ) * d
* it's not, Gm = (U * sval * V-transpos)m,
* but, Gm = (V * sval * U-transpos)m
* so, m = (U * sval-inverse * V-Transpose) * d
* ---- Subroutines called ----
* Local
* dsvdc: LINPACK Singular Value Decomposition routine
* DIAGNOSTICS
* Makes checks for invalid singular values and simply ignores them.
* NOTES
* Beware of problems associated with variable, info, from LINPACK
* subroutine dsvdc.
* SEE ALSO
* LINPACK, John Dongarra for explanation of SVD application along
* with corresponding subroutines; and NETLIB ([email protected]) for
* obtaining any LINPACK source code.
* AUTHOR
* Walter Nagy, 6/91, Created.
* Walter Nagy, 8/24/92, Damping removed from calculation of covariance
* matrix. applied_damping argument also added.
* Walter Nagy, 9/25/92, Fixed divide-by-zero problems noted by Fred
* Dashiell at Inference.
*/
#include "config.h"
#include <math.h>
#ifdef HAVE_IEEEFP_H
#include <ieeefp.h>
#endif /* HAVE_IEEEFP_H */
#include "locp.h"
#include "loc_defs.h"
#define MAX_DATA 800
static int maxdata = MAX_DATA;
extern int dsvdc(double*,int,int,int, double*, double*, double*,
int, double*, int, double*, int, int*);
int
solve_via_svd (int icov, int nd, int np, int maxp, double *at, double *d,
double damp, double *cnvgtst, double *condit, double *xsol,
double covar[][MAX_PARAM], double *data_importances,
double *applied_damping, double *rank)
{
int job = 21;
int i, icnt, info, j, k, neig, norder;
double *e, *g, gscale[MAX_PARAM], gtr[MAX_PARAM], smax, sum;
double sval[MAX_PARAM+1], tmp[MAX_PARAM], u[MAX_PARAM][MAX_PARAM];
double *v, work[MAX_PARAM];
double dscale, frob, gtrnorm, rnorm;
e = UALLOCA (double, nd);
g = UALLOCA (double, MAX_PARAM * nd);
v = UALLOCA (double, MAX_DATA * nd);
/*
* Variable, norder, limits the maximum possible number of singular
* values. Variable, job, controls the singular values sent back
* from dsvdc. Current job setting tells dsvdc to ignore bogus
* values and pass both left and right singular vectors back.
*/
norder = MIN(np, nd);
/*
* Unit-column normalize at[] matrix and stuff it into g[], since
* subr. dsvdc overwrites original matrix upon its return.
*/
for (j = 0; j < np; ++j)
gscale[j] = 0.0;
for (i = 0; i < nd; ++i)
{
for (j = 0; j < np; ++j)
{
dscale = at[j + i*maxp];
gscale[j] += dscale*dscale;
}
}
for (j = 0; j < np; ++j)
{
if (gscale[j] > 0.0)
gscale[j] = 1.0/sqrt(gscale[j]);
else
gscale[j] = 1.0;
}
/*
* Scale origin terms of similar dimension to spatial terms,
* assuming a medium velocity of 8 km./sec.
*/
/* gscale[0] = 0.125*gscale[0]; */
for (i = 0; i < nd; ++i)
for (j = 0; j < np; ++j)
g[j + i*maxp] = at[j + i*maxp] * gscale[j];
/*
* Compute norms and undertake convergence test.
*/
frob = 0.0;
rnorm = 0.0;
gtrnorm = 0.0;
for (i = 0; i < nd; ++i)
{
rnorm = rnorm + d[i]*d[i];
for (j = 0; j < np; ++j)
{
dscale = g[j + i*maxp];
frob += dscale*dscale;
}
}
for (j = 0; j < np; ++j)
{
gtr[j] = 0.0;
for (i = 0; i < nd; ++i)
gtr[j] += g[j + i*maxp]*d[i];
gtrnorm += gtr[j]*gtr[j];
}
*cnvgtst = gtrnorm / (frob*rnorm);
/* printf ("gtrnorm = %g frob = %g\n", gtrnorm, frob); */
/* printf ("rnorm = %g cnvgtst = %g\n", rnorm, *cnvgtst); */
/*
* Decompose the matrix into its right and left singular vectors,
* u[] and v[], respectively, as well as the diagonal matrix of
* singular values, sval. That is, perform an SVD. LINPACK routine,
* dsvdc, of John Dongarra is chosen here.
*/
dsvdc(g, maxp, np, nd, sval, e, (double *)u, maxp, v, maxdata, work, job, &info);
if (info >= norder)
return (GLerror6);
/*
* Adjust variable, neig, to control singular value cutoff,
* effectively determining which singular values to keep and/or
* ignore.
* Note: The good singular values are stored at the end of
* sval(), not the beginning. smax is always sval(info+1)
* with the descending values immediately following.
*/
neig = norder - info;
/*
* Avoid small singular values (limit condition number to ctol)
* That is, set a singular value cutoff (i.e., singular values
* < pre-set limit, in order to obtain an effective condition number).
*/
smax = sval[info];
for (j = info + 1; j < norder; ++j)
{
if (smax > sval[j]*COND_NUM_LIMIT)
{
neig = j - info;
break;
}
}
/*
* Construct the real (condit[0]) and effective (condit[1])
* condition numbers from the given singular values
*/
if (sval[norder-1] > 0.0)
condit[0] = sval[info] / sval[norder-1];
else
condit[0] = HUGE_VAL;
condit[1] = sval[info] / sval[info+1 + (neig-1) - 1];
if (isnan (condit[0]) || isnan (condit[1]))
return (GLerror6);
/*
* If only the covariance matrix is desired, do NOT damp!!!
*/
if (icov > 1)
{
/*
* Construct the parameter (model) covariance matrix,
* if requested
*/
icnt = info+1 + (neig-1);
for (i = info; i < icnt; ++i)
sval[i] = 1.0/(sval[i]*sval[i]);
for (i = 0; i < np; ++i)
{
for (j = 0; j <= i; ++j)
{
sum = 0.0;
icnt = info+1 + (neig-1);
for (k = info; k < icnt; ++k)
sum += u[k][i] * u[k][j] * sval[k];
covar[j][i] = sum * gscale[j]*gscale[i];
}
}
/*
* and then, the data importances (i.e., the diagonal
* elements of the data resolution matrix)
*/
*rank = 0.0;
for (i = 0; i < nd; ++i)
{
sum = 0.0;
for (j = 0; j < np; ++j)
{
icnt = i + j*MAX_DATA;
sum += v[icnt]*v[icnt];
}
*rank += sum;
data_importances[i] = sum;
}
}
else
{
/* Apply damping, if necessary */
*applied_damping = 0.0;
if (damp < 0.0)
{
if (condit[0] > 30.0)
{
/*
* Apply damping of 1% largest singular value for
* moderately ill-conditioned system. Make this 5%
* for more severely ill-conditioned system and 10%
* for highly ill-conditioned problems.
*/
icnt = info+1 + (neig-1);
*applied_damping = 0.01;
if (condit[0] > 300.0)
*applied_damping = 0.05;
if (condit[0] > 3000.0)
*applied_damping = 0.10;
for (i = info; i < icnt; ++i)
sval[i] += smax * (*applied_damping);
}
}
else
{
*applied_damping = damp;
icnt = info+1 + (neig-1);
for (i = info; i < icnt; ++i)
sval[i] += smax * 0.01*(*applied_damping);
}
/*
* Find solution vector --
* First, compute (1/sval) * V-trans * d,
*/
icnt = info+1 + (neig-1);
for (j = info; j < icnt; ++j)
{
sum = 0.0;
for (i = 0; i < nd; ++i)
sum += v[i + j*MAX_DATA] * d[i];
tmp[j] = sum/sval[j];
}
/*
* then, multiply by U, which yields the desired solution
* vector, (i.e., xsol = U * (1/sval) * V-trans*d) = U * tmp
*/
for (j = 0; j < np; ++j)
{
sum = 0.0;
icnt = info+1 + (neig-1);
for (i = info; i < icnt; ++i)
sum += u[i][j] * tmp[i];
xsol[j] = sum*gscale[j];
}
}
return (OK);
}
|
C | // Module: rnrcs.c
//
// Description:
// This sample illustrates how a server can create a socket and
// advertise the existance of the service to clients. It also
// shows how a client with knowledge of the server's name only
// can find out how to connect to the server in order to transmit
// data. The server accomplishes this by installing a service
// class which describes the basic characteristics of the service
// and then registering an instance of the server which references
// the given class. The service can be registered for multiple
// name spaces such as IPX and NTDS.
//
// The client can query the available name spaces for knowledge
// of a service of the given name. If the query completes
// successfully, the address of the service is returned. All
// the client needs to do is use that address in either a
// connect or sendto call.
//
// Compile:
// cl rnrcs.c ws2_32.lib user32.lib ole32.lib
//
// Command Line Arguments/Parameters
// rnrcs -c:ServiceName -s:ServiceName -t:ID -n:NameSpace
// -c:ServiceName Act as client and query for this service name
// -s:ServiceName Act as server and register service as this name
// -t:ID SAP ID to register under
// -n:NameSpace Name space to register service under
// Supported namespaces are NS_ALL, NS_SAP, NS_NTDS
// -d Delete the service if found
//
#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <nspapi.h>
#include <svcguid.h>
#include "mynsp.h"
#include <stdio.h>
#include <stdlib.h>
#define MAX_NUM_CSADDRS 20
#define MAX_INTERFACE_LIST 20
#define MAX_NUM_SOCKETS 20
#define MAX_BUFFER_SZ 512
#define MAX_SERVER_NAME_SZ 64
#define DEFAULT_SERVER_NAME "JunkServer"
char szServerName[MAX_SERVER_NAME_SZ]; // Server name
BOOL bServer, // Client or server?
bDeleteService;
DWORD dwUniqueId; // Used to create a GUID
SOCKET sock;
//
// Function: usage
//
// Description:
// Print usage information.
//
void usage(char *progname)
{
printf("usage: %s -c:Service -s -t:ID\n",
progname);
printf(" -c:ServiceName Act as client and query for this service name\n");
printf(" -s:ServiceName Act as server and register service as this name\n");
printf(" -t:ID Unique ID to register under\n");
printf(" -d Delete the service on a successful query\n");
ExitProcess(-1);
}
//
// Function: ValidateArgs
//
// Description:
// Parse command line parameters and set some global variables used
// by the application.
//
void ValidateArgs(int argc, char **argv)
{
int i;
// Set some default values
//
lstrcpy(szServerName, TEXT(DEFAULT_SERVER_NAME));
dwUniqueId = 200;
bDeleteService = FALSE;
for (i=1; i < argc ;i++)
{
if ((argv[i][0] == '-') || (argv[i][0] == '/'))
{
switch (tolower(argv[i][1]))
{
case 't': // SAP id used to generate GUID
//if (lstrlen(argv[i]) > 3)
// dwUniqueId = atoi(&argv[i][3]);
break;
case 'c': // Client, query for given service
bServer = FALSE;
if (lstrlen(argv[i]) > 3)
lstrcpy(szServerName, &argv[i][3]);
break;
case 's': // Server, register as the given service
bServer = TRUE;
if (lstrlen(argv[i]) > 3)
lstrcpy(szServerName, &argv[i][3]);
break;
case 'd':
bDeleteService = TRUE;
break;
default:
usage(argv[0]);
return;
}
}
else
usage(argv[0]);
}
return;
}
//
// Function: EnumNameSpaceProviders
//
// Description:
// Returns an array of those name spaces which our application
// supports. If one day, NS_DNS becomes dynamic, modify this
// function to return that structure as well.
//
WSANAMESPACE_INFO *EnumNameSpaceProviders(int *count)
{
WSANAMESPACE_INFO *nsinfo,
*nsinfocpy;
BYTE *pbuf=NULL,
*pbufcpy=NULL;
DWORD dwBytes;
int i, j,
ret;
*count = 0;
dwBytes = 0;
//
// First find out how big of a buffer we need
//
ret = WSAEnumNameSpaceProviders(&dwBytes, NULL);
if (ret == SOCKET_ERROR)
{
if (WSAGetLastError() != WSAEFAULT)
{
printf("WSAEnumNameSpaceProviders() failed: %d\n",
WSAGetLastError());
return NULL;
}
}
// Allocate this buffer and call the function again
//
pbuf = (BYTE *)GlobalAlloc(GPTR, dwBytes);
if (!pbuf)
{
printf("GlobaAlloc() failed: %d\n", GetLastError());
return NULL;
}
nsinfo = (WSANAMESPACE_INFO *)pbuf;
ret = WSAEnumNameSpaceProviders(&dwBytes, nsinfo);
if (ret == SOCKET_ERROR)
{
printf("WSAEnumNameSpaceProviders() failed: %d\n",
WSAGetLastError());
HeapFree(GetProcessHeap(), 0, pbuf);
return NULL;
}
// Make a copy buffer which we will return our data in
//
pbufcpy = GlobalAlloc(GPTR, dwBytes);
if (!pbufcpy)
{
printf("GlobaAlloc() failed: %d\n", GetLastError());
return NULL;
}
// Loop throug the returned name space structures picking
// those which our app supports
//
nsinfocpy = (WSANAMESPACE_INFO *)pbufcpy;
printf("%d name spaces are available\n", ret);
j = 0;
for(i=0; i < ret ;i++)
{
switch (nsinfo[i].dwNameSpace)
{
// In this example all we want is our own name space
//
case NS_MYNSP:
printf("Found a match: %S\n", nsinfo[i].lpszIdentifier);
memcpy(&nsinfocpy[j++], &nsinfo[i], sizeof(WSANAMESPACE_INFO));
break;
default:
break;
}
}
// Free the original buffer and return our copy of useable name spaces
//
GlobalFree(pbuf);
printf("Found %d useable name spaces\n\n", j);
*count = j;
return nsinfocpy;
}
//
// Function: InstallServiceClass
//
// Description:
// This function installs the service class which is required before
// registering an instance of a service. A service class defines the
// generic attributes of a class of services such as whether it is
// connection oriented or not as well as what protocols is supports
// (IPX, IP, etc).
//
BOOL InstallServiceClass(GUID *svcguid, WSANAMESPACE_INFO *nsinfo, int nscount)
{
WSASERVICECLASSINFO sci;
WSANSCLASSINFO *nsclass=NULL;
DWORD dwOne=1;
TCHAR szServiceClassName[64];
int i,
ret;
BOOL bRet;
bRet = TRUE;
//
// Generate a name of our service class
//
wsprintf(szServiceClassName, TEXT("Service Class/TCP Port: %003d"), dwUniqueId);
printf("Installing service class: '%s'\n", szServiceClassName);
//
// There are 2 attributes we need to set for every name space
// we want to register in: Connection Oriented/Connectionless as
// well as the address family of the protocols we support.
//
nsclass = GlobalAlloc(GPTR, sizeof(WSANSCLASSINFO) * nscount * 2);
if (!nsclass)
{
printf("GlobalAlloc() failed: %d\n", GetLastError());
return FALSE;
}
// Initialize the structure
//
memset(&sci, 0, sizeof(sci));
sci.lpServiceClassId = svcguid;
sci.lpszServiceClassName = szServiceClassName;
sci.dwCount = nscount * 2;
sci.lpClassInfos = nsclass;
printf("Namespace count: %d, Namespace: %d\n", nscount, nsinfo[0].dwNameSpace);
for(i=0; i < nscount ;i++)
{
// No matter what name space we use we set the connection
// oriented attribute to false (i.e. connectionless)
//
nsclass[i*2].lpszName = SERVICE_TYPE_VALUE_CONN;
nsclass[i*2].dwNameSpace = nsinfo[i].dwNameSpace;
nsclass[i*2].dwValueType = REG_DWORD;
nsclass[i*2].dwValueSize = sizeof(DWORD);
nsclass[i*2].lpValue = &dwOne;
if (nsinfo[i].dwNameSpace == NS_MYNSP)
{
// If NS_MYNSP is available we will be running a UDP
// based service on the given port number
//
printf("Setting NS_MYNSP info...\n");
nsclass[(i*2)+1].lpszName = SERVICE_TYPE_VALUE_TCPPORT;
nsclass[(i*2)+1].dwNameSpace = nsinfo[i].dwNameSpace;
nsclass[(i*2)+1].dwValueType = REG_DWORD;
nsclass[(i*2)+1].dwValueSize = sizeof(DWORD);
nsclass[(i*2)+1].lpValue = &dwUniqueId;
}
}
// Install the service class
//
ret = WSAInstallServiceClass(&sci);
if (ret == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAEALREADY)
{
printf("Service class already registered\n");
bRet = TRUE;
}
else
{
printf("WSAInstallServiceClass() failed: %d\n",
WSAGetLastError());
bRet = FALSE;
}
}
GlobalFree(nsclass);
return bRet;
}
//
// Function: GetIPInterfaceList
//
// Description:
// This function returns an array of SOCKADDR_IN structures,
// one for every local IP interface on the machine. We use
// the ioctl command SIO_GET_INTERFACE_LIST to do this although
// we could have used any number of method such as gethostbyname(),
// SIO_INTERFACE_LIST_QUERY, or the IP helper APIs.
//
SOCKADDR_IN *GetIPInterfaceList(SOCKET s, int *count)
{
static SOCKADDR_IN sa_in[MAX_NUM_CSADDRS];
INTERFACE_INFO iflist[MAX_INTERFACE_LIST];
DWORD dwBytes;
int ret,
i;
*count = 0;
ret = WSAIoctl(s, SIO_GET_INTERFACE_LIST, NULL, 0, &iflist,
sizeof(iflist), &dwBytes, NULL, NULL);
if (ret == SOCKET_ERROR)
{
printf("WSAIoctl(SIO_GET_INTERFACE_LIST) failed: %d\n",
WSAGetLastError());
return NULL;
}
// Loop through the interfaces and copy them into the SOCKADDR_IN
// array.
//
*count = dwBytes / sizeof(INTERFACE_INFO);
for(i=0; i < *count ;i++)
{
memcpy(&sa_in[i], &iflist[i].iiAddress.AddressIn, sizeof(SOCKADDR_IN));
}
return sa_in;
}
//
// Function: Advertise
//
// Description:
// This function advertises an instance of the server. This
// function also creates the server for each available name
// space. To advertise you need all the local interfaces that
// the client can connect the to the server. This is done
// by filling out a WSAQUERYSET structure along with the
// appropriate CSADDR_INFO structures. The CSADDR_INFO
// structures define the interfaces the service is listening on.
//
BOOL Advertise(GUID *guid, WSANAMESPACE_INFO *nsinfo,
int nscount, TCHAR *servicename)
{
WSAQUERYSET qs;
CSADDR_INFO csaddrs[MAX_NUM_CSADDRS];
int ret,
i, j,
iSize,
addrcnt;
// Initialize the WSAQUERYSET structure
//
memset(&qs, 0, sizeof(WSAQUERYSET));
qs.dwSize = sizeof(WSAQUERYSET);
qs.lpszServiceInstanceName = servicename;
qs.lpServiceClassId = guid;
qs.dwNameSpace = NS_MYNSP;
qs.lpNSProviderId = &nsinfo[0].NSProviderId;
qs.lpcsaBuffer = csaddrs;
qs.lpBlob = NULL;
qs.lpszComment = "Dork this";
addrcnt=0;
//
// For each valid name space we create an instance of the
// service and find out what local interfaces are available
// that the client can connect to and communicate with the server.
//
for (i=0; i < nscount ;i++)
{
if (nsinfo[i].dwNameSpace == NS_MYNSP)
{
SOCKADDR_IN localip;
SOCKADDR_IN *iflist=NULL;
int ipifcount;
// Create a TCP based server
//
printf("Setting up NS_MYNSP entry...\n");
sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP,
NULL, 0, WSA_FLAG_OVERLAPPED);
if (sock == INVALID_SOCKET)
{
printf("WSASocket() failed: %d\n", WSAGetLastError());
return FALSE;
}
localip.sin_family = AF_INET;
localip.sin_port = htons((short)dwUniqueId);
localip.sin_addr.s_addr = htonl(INADDR_ANY);
ret = bind(sock, (SOCKADDR *)&localip, sizeof(localip));
if (ret == SOCKET_ERROR)
{
printf("bind() failed: %d\n", WSAGetLastError());
return FALSE;
}
// Get a list of the IP interfaces
//
iflist = GetIPInterfaceList(sock, &ipifcount);
if (!iflist)
{
printf("Unable to enumerate IP interfaces!\n");
return FALSE;
}
// Fill out the CSADDR_INFO structures with each IP interface
//
for (j=0; j < ipifcount ;j++)
{
iflist[j].sin_family = AF_INET;
iflist[j].sin_port = htons((short)dwUniqueId);
csaddrs[addrcnt].iSocketType = SOCK_STREAM;
csaddrs[addrcnt].iProtocol = IPPROTO_TCP;
csaddrs[addrcnt].LocalAddr.lpSockaddr = (SOCKADDR *)&iflist[j];
csaddrs[addrcnt].LocalAddr.iSockaddrLength = sizeof(iflist[j]);
csaddrs[addrcnt].RemoteAddr.lpSockaddr = (SOCKADDR *)&iflist[j];
csaddrs[addrcnt].RemoteAddr.iSockaddrLength = sizeof(iflist[j]);
printf("\t[%d] Local IP [%s:%d]\n", j,
inet_ntoa(((SOCKADDR_IN *)(csaddrs[addrcnt].LocalAddr.lpSockaddr))->sin_addr),
ntohs(((SOCKADDR_IN *)(csaddrs[addrcnt].LocalAddr.lpSockaddr))->sin_port));
printf("\t[%d] Remote IP [%s:%d]\n", j,
inet_ntoa(((SOCKADDR_IN *)(csaddrs[addrcnt].RemoteAddr.lpSockaddr))->sin_addr),
ntohs(((SOCKADDR_IN *)(csaddrs[addrcnt].RemoteAddr.lpSockaddr))->sin_port));
addrcnt++;
}
}
}
qs.dwNumberOfCsAddrs = addrcnt;
//
// Register our service(s)
//
ret = WSASetService(&qs, RNRSERVICE_REGISTER, 0L);
if (ret == SOCKET_ERROR)
{
printf("WSASetService() failed: %d\n", WSAGetLastError());
return FALSE;
}
printf("WSASetService() succeeded\n");
return TRUE;
}
//
// Function: LookupService
//
// Description:
// This function queries for an instance of the given service
// running on the network. You can either query for a specific
// service name or specify the wildcard string "*". If an instance
// is found, send some data to it.
//
void LookupService(GUID *guid, int sapid, int ns, TCHAR *servername)
{
WSAQUERYSET qs,
*pqs;
AFPROTOCOLS afp[1] = { {AF_INET, IPPROTO_TCP} };
char querybuf[sizeof(WSAQUERYSET) + 4096];
DWORD nSize = sizeof(WSAQUERYSET) + 4096,
i;
HANDLE hLookup;
int ret, err;
// Initialize the WSAQUERYSET structure
//
pqs = (WSAQUERYSET *)querybuf;
memset(&qs, 0, sizeof(WSAQUERYSET));
qs.dwSize = sizeof(WSAQUERYSET);
qs.lpszServiceInstanceName = servername;
qs.lpServiceClassId = guid;
qs.lpNSProviderId = &MY_NAMESPACE_GUID;
qs.dwNameSpace = NS_MYNSP;
qs.dwNumberOfProtocols = ns;
qs.lpafpProtocols = afp;
//
// Begin the lookup. We want the name and address back
//
ret = WSALookupServiceBegin(&qs, LUP_RETURN_ADDR | LUP_RETURN_NAME,
&hLookup);
if (ret == SOCKET_ERROR)
{
printf("WSALookupServiceBegin failed: %d\n", WSAGetLastError());
return;
}
while (1)
{
// Loop, calling WSALookupServiceNext until WSA_E_NO_MORE is
// returned.
//
nSize = sizeof(WSAQUERYSET) + 4096;
memset(querybuf, 0, nSize);
pqs->dwSize = sizeof(WSAQUERYSET);
ret = WSALookupServiceNext(hLookup, 0, &nSize, pqs);
if (ret == SOCKET_ERROR)
{
err = WSAGetLastError();
if ((err == WSA_E_NO_MORE) || (err == WSAENOMORE))
{
printf("No more data found!\n");
break;
}
else if (err == WSASERVICE_NOT_FOUND)
{
printf("Service not found!\n");
break;
}
printf("WSALookupServiceNext() failed: %d\n", WSAGetLastError());
WSALookupServiceEnd(hLookup);
return;
}
// Now that we've found a server out there, print some info and
// send some data to it.
//
printf("\nFound service: %s\n\n", pqs->lpszServiceInstanceName);
printf("Returned %d CSADDR structures\n", pqs->dwNumberOfCsAddrs);
for(i=0; i < pqs->dwNumberOfCsAddrs ;i++)
{
switch (pqs->lpcsaBuffer[i].iProtocol)
{
case IPPROTO_TCP:
printf("IPPROTO_TCP: '%s'\n", inet_ntoa(((SOCKADDR_IN *)pqs->lpcsaBuffer[i].RemoteAddr.lpSockaddr)->sin_addr));
((SOCKADDR_IN *)pqs->lpcsaBuffer[i].RemoteAddr.lpSockaddr)->sin_family = AF_INET;
break;
default:
printf("Unknown!: %d\n", pqs->lpcsaBuffer[i].iProtocol);
break;
}
// Send data
//
}
if (bDeleteService)
ret = WSASetService(pqs, RNRSERVICE_DELETE, 0L);
}
WSALookupServiceEnd(hLookup);
printf("DONE!\n");
return;
}
//
// Function: main
//
// Description:
// Initialize Winsock, parse the arguments, and start either the
// client or server depending on the arguments.
//
int main(int argc, char **argv)
{
WSANAMESPACE_INFO *nsinfo=NULL;
WSADATA wsd;
GUID svcguid;
int nscount,
ret,
i;
WCHAR szTemp[256];
ValidateArgs(argc, argv);
if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
{
printf("WSAStartup() failed: %d\n", GetLastError());
return -1;
}
// Generate a GUID for our service class
//
SET_TCP_SVCID(&svcguid, dwUniqueId);
//
// Enumerate the name spaces that we can use
//
nsinfo = EnumNameSpaceProviders(&nscount);
if (!nsinfo)
{
printf("unable to enumerate name space info!\n");
return -1;
}
for(i=0; i < nscount ;i++)
printf("Found NS: %s\n", nsinfo[i].lpszIdentifier);
if (bServer)
{
if (szServerName[0] == '*')
{
printf("You must specify a server name!\n");
usage(argv[0]);
return -1;
}
// Install the service class
//
if (!InstallServiceClass(&svcguid, nsinfo, nscount))
{
printf("Unable to install service class!\n");
return -1;
}
// Advertise our service
//
if (!Advertise(&svcguid, nsinfo, nscount, szServerName))
{
printf("Unable to advertise service!\n");
return -1;
}
}
else
{
// Lookup the service
//
LookupService(&svcguid, dwUniqueId, NS_MYNSP, szServerName);
}
HeapFree(GetProcessHeap(), 0, nsinfo);
WSACleanup();
return 0;
}
|
C | #include<stdio.h>
main()
{
int n ;
scanf("%d",&n);
int reverse=0;
int s=0;
int nn=n;
int i=0;
while(nn)
{
nn=nn>>1;
s++;
}
nn=n;
while(s>0)
{
nn=n;
nn=nn>>s-1;
nn=nn&1;
nn=nn<<i;
reverse=reverse|nn;
s--;
i++;
}
printf("%d",reverse);
}
|
C | #include<stdio.h>
int main()
{
int x,i,j,k;
char a,arr[5][10]={"Ram","Sham","Aryan","Karan","Hari"};
for(i=0;i<=5;i++)
{
for(j=0;j<5-1-i;j++)
{
if(arr[j][0]>arr[j+1][0])
{
a=arr[j];
arr[j]=arr[j+1];
arr[j+1]=a;
}
}
}
//printf("----------------\n");
for(i=0;i<=5;i++)
{
puts(arr[i]);
}
return 0;
}
|
C | #include <stdio.h>
#include <math.h>
int main(void)
{
unsigned int year;//year count
int rate;//interest rate
double amount;//amount on deposit
double principal = 5000.0;//starting principal
//loop through interest rates 10% to 12%
for (rate = 10; rate <= 12; ++rate)
{
//display table headers
printf("Interest Rate: %f\n", rate / 100.0);
printf("%s%21s\n", "Year", "Amount on deposit");
//calculate amount on deposit for each of fifteen years
for (year = 1; year <= 15; ++year)
{
//calculate new amount for specified year
amount = principal * pow(1 + (rate / 100.0), year);
//output one table row
printf("%4u%21.2f\n", year, amount);
}//end for
puts("");
}//end for
}//end main |
C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include<netinet/in.h>
#include <netdb.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd,portno,n;
struct sockaddr_in serv_addr;
struct hostent *server;
char userInput[1024], target[1024], task[1024];
char buffer[256];
char colon = ';';
if (argc < 3 )
{
fprintf(stderr, "usage %s hostname port\n" , argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET ,SOCK_STREAM,0 );
if(sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL)
{
fprintf(stderr, "Error , no such host" );
}
bzero((char *) &serv_addr , sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *) server->h_addr ,(char *) &serv_addr.sin_addr.s_addr ,server->h_length);
serv_addr.sin_port = htons(portno);
if(connect(sockfd , (struct sockaddr *) &serv_addr , sizeof(serv_addr))<0)
error("connection failed");
char ans[1024];
int choice ;
S:bzero(buffer,256);
n = read(sockfd,buffer,255);
if(n < 0)
error("ERROR reading from socket");
printf("Server - %s\n",buffer);
gets(userInput);
// scanf("%s" ,str1);
//write(sockfd, userInput, sizeof(char *));
send(sockfd, userInput , 1024 , 0);
// printf("%s\n",userInput);
/* n = read(sockfd,buffer,255);
if(n < 0)
error("ERROR reading from socket");
printf("Server - %s\n",buffer);
scanf("%d" ,&choice);
write(sockfd, &choice, sizeof(int));
if(choice == 5)
goto Q;*/
//read(sockfd , &ans , sizeof(char *));
recv(sockfd, ans , 1024 , 0);
printf("server- The answer is: %s\n", ans);
/* if(choice != 5)
goto S;*/
/*Q :
printf("You have selected to exit. Exit successful.");*/
close(sockfd);
return 0;
}
|
C | #include <stdlib.h>
#include <stdint.h>
#include "test_semantics.h"
#include "ctverif.h"
int32_t get100_wrapper(void) {
return get100();
}
int32_t identity_wrapper(int32_t my_int) {
return identity(my_int);
}
int32_t mutateArray_wrapper(int32_t arr[5]) {
public_in(__SMACK_value(arr));
return mutateArray(arr);
}
int32_t mutateArray2_wrapper(int32_t arr2[5], int32_t val){
public_in(__SMACK_value(arr2));
return mutateArray2(arr2, val);
}
int32_t simpleIf_wrapper(int32_t cond) {
return simpleIf(cond);
}
int32_t mediumComplexIf_wrapper(int32_t cond) {
return mediumComplexIf(cond);
}
int32_t mixedIf_wrapper(int32_t cond) {
return mixedIf(cond);
}
int32_t mixedIf2_wrapper(int32_t cond) {
return mixedIf2(cond);
}
int32_t nestedIf_wrapper(int32_t cond) {
return nestedIf(cond);
}
/*public return*/
int32_t simpleLoop_wrapper() {
public_out(__SMACK_return_value());
return simpleLoop();
}
int32_t loopAcc_wrapper() {
return loopAcc();
}
/*public return*/
int32_t loopAssignArray_wrapper(uint32_t arr[5]) {
public_out(__SMACK_return_value());
public_in(__SMACK_value(arr));
return loopAssignArray(arr);
}
/*public return*/
int32_t add_wrapper(/*public*/ int32_t a, /*public*/ int32_t b) {
public_out(__SMACK_return_value());
public_in(__SMACK_value(a));
public_in(__SMACK_value(b));
return add(a,b);
}
/*public return*/
int32_t add10And20_wrapper() {
public_out(__SMACK_return_value());
return add10And20();
}
int32_t addAll_wrapper(const int32_t arr[5]) {
public_in(__SMACK_value(arr));
return addAll(arr);
}
int32_t multiply_wrapper(int32_t a, int32_t b) {
return multiply(a, b);
}
uint8_t equal_wrapper(int32_t a,int32_t b) {
return equal(a,b);
}
uint8_t nequal_wrapper(int32_t a,int32_t b) {
return nequal(a,b);
}
int32_t lshift_wrapper(int32_t num,uint32_t shift) {
return lshift(num,shift);
}
int32_t rshift_wrapper(int32_t num,uint32_t shift) {
return rshift(num,shift);
}
uint8_t gt_wrapper(int32_t a,int32_t b) {
return gt(a,b);
}
uint8_t gte_wrapper(int32_t a,int32_t b) {
return gte(a,b);
}
uint8_t lt_wrapper(int32_t a,int32_t b) {
return lt(a,b);
}
uint8_t lte_wrapper(int32_t a,int32_t b) {
return lte(a,b);
}
int32_t neg_wrapper(int32_t a) {
return neg(a);
}
int32_t xor_wrapper(int32_t a,int32_t b) {
return xor(a,b);
}
int32_t prec_wrapper(int32_t a) {
return prec(a);
}
int32_t opassign_wrapper() {
return opassign();
}
/*public return*/
int32_t add5int8_wrapper(/*public*/ int8_t num) {
public_out(__SMACK_return_value());
public_in(__SMACK_value(num));
return add5int8(num);
}
/*public return*/
int32_t complicatedAdd5_wrapper(/*public*/ int32_t num){
public_out(__SMACK_return_value());
public_in(__SMACK_value(num));
return complicatedAdd5(num);
}
/*public return*/
uint32_t add5uint32_wrapper(/*public*/ uint32_t num) {
public_out(__SMACK_return_value());
public_in(__SMACK_value(num));
return add5uint32(num);
}
/*public return*/
uint16_t add5uint16_wrapper(/*public*/ uint16_t num) {
public_out(__SMACK_return_value());
public_in(__SMACK_value(num));
return add5uint16(/*public*/ num);
}
/*public return*/
uint32_t add5uintUnify_wrapper(/*public*/ uint16_t num) {
public_out(__SMACK_return_value());
public_in(__SMACK_value(num));
return add5uintUnify(/*public*/ num);
}
int32_t summ_wrapper(const int32_t arr[],/*public*/ uint32_t __arr_len) {
public_in(__SMACK_value(arr));
public_in(__SMACK_value(__arr_len));
return summ(arr,/*public*/ __arr_len);
}
int32_t summZero_wrapper() {
return summZero();
}
int32_t summNonZero_wrapper() {
return summNonZero();
}
int32_t summZeroDynamic_wrapper() {
return summZeroDynamic();
}
int32_t summNonZeroDynamic_wrapper() {
return summNonZeroDynamic();
}
int32_t summCopyZero_wrapper() {
return summCopyZero();
}
int32_t summCopyNonZero_wrapper() {
return summCopyNonZero();
}
int32_t summCopyZeroDynamic_wrapper() {
return summCopyZeroDynamic();
}
int32_t summCopyNonZeroDynamic_wrapper() {
return summCopyNonZeroDynamic();
}
int32_t summViewZero_wrapper() {
return summViewZero();
}
int32_t summViewNonZero_wrapper() {
return summViewNonZero();
}
int32_t summViewDynamic_wrapper(const int32_t arr[],/*public*/ uint32_t __arr_len) {
public_in(__SMACK_value(arr));
public_in(__SMACK_value(__arr_len));
return summViewDynamic(arr,/*public*/ __arr_len);
}
int32_t arrget1_wrapper() {
return arrget1();
}
int32_t arrget2_wrapper() {
return arrget2();
}
int32_t arrget3_wrapper() {
return arrget3();
}
int32_t arrget4_wrapper() {
return arrget4();
}
int32_t arrgetDynamic1_wrapper(const int32_t arr[],/*public*/ uint32_t __arr_len) {
public_in(__SMACK_value(arr));
public_in(__SMACK_value(__arr_len));
return arrgetDynamic1(arr,/*public*/ __arr_len);
}
int32_t arrgetDynamic2_wrapper(const int32_t arr[],/*public*/ uint32_t __arr_len) {
public_in(__SMACK_value(arr));
public_in(__SMACK_value(__arr_len));
return arrgetDynamic2(arr,/*public*/ __arr_len);
}
int32_t arrgetDynamic3_wrapper(const int32_t arr[],/*public*/ uint32_t __arr_len) {
public_in(__SMACK_value(arr));
public_in(__SMACK_value(__arr_len));
return arrgetDynamic3(arr,/*public*/ __arr_len);
}
int32_t arrgetDynamic4_wrapper(const int32_t arr[],/*public*/ uint32_t __arr_len) {
public_in(__SMACK_value(arr));
public_in(__SMACK_value(__arr_len));
return arrgetDynamic4(arr,/*public*/ __arr_len);
}
int32_t mutateRef_wrapper(int32_t * a) {
return mutateRef(a);
}
int32_t mutateRefCall_wrapper() {
return mutateRefCall();
}
int32_t simpleArrAccess_wrapper() {
return simpleArrAccess();
}
int32_t simpleArrZerosAccess_wrapper() {
return simpleArrZerosAccess();
}
int32_t simpleArrViewAccess_wrapper() {
return simpleArrViewAccess();
}
int32_t paramArrAccess_wrapper(const int32_t arr[5]) {
public_in(__SMACK_value(arr));
return paramArrAccess(arr);
}
int32_t paramArrAccessDyn_wrapper(const int32_t arr[],/*public*/ uint32_t __arr_len) {
public_in(__SMACK_value(arr));
public_in(__SMACK_value(__arr_len));
return paramArrAccessDyn(arr,/*public*/ __arr_len);
}
int32_t paramArrViewAccess_wrapper(const int32_t arr[5]) {
public_in(__SMACK_value(arr));
return paramArrViewAccess(arr);
}
int32_t paramArrViewAccessDyn_wrapper(const int32_t arr[],/*public*/ uint32_t __arr_len) {
public_in(__SMACK_value(arr));
public_in(__SMACK_value(__arr_len));
return paramArrViewAccessDyn(arr,/*public*/ __arr_len);
}
int32_t simpleArrayMutation_wrapper(int32_t arr[],/*public*/ uint32_t __arr_len) {
public_in(__SMACK_value(arr));
public_in(__SMACK_value(__arr_len));
return simpleArrayMutation(arr,/*public*/ __arr_len);
}
int32_t complexArrayMutation_wrapper(int32_t arr[5]) {
public_in(__SMACK_value(arr));
return complexArrayMutation(arr);
}
int32_t complexArrayViewMutation_wrapper(int32_t arr[10]) {
public_in(__SMACK_value(arr));
return complexArrayViewMutation(arr);
}
int32_t simpleArrayRead_wrapper(int32_t arr[],/*public*/ uint32_t __arr_len,/*public*/ int32_t index) {
public_in(__SMACK_value(arr));
public_in(__SMACK_value(__arr_len));
public_in(__SMACK_value(index));
return simpleArrayRead(arr,/*public*/ __arr_len,/*public*/ index);
}
int32_t complexArrayViewRead_wrapper(int32_t arr[10],/*public*/ int32_t index) {
public_in(__SMACK_value(arr));
public_in(__SMACK_value(index));
return complexArrayViewRead(arr,/*public*/ index);
}
/*public return*/
int32_t simpleArrCopy_wrapper(int8_t c[],/*public*/ uint32_t __c_len,const int8_t k[5]) {
public_out(__SMACK_return_value());
public_in(__SMACK_value(c));
public_in(__SMACK_value(__c_len));
public_in(__SMACK_value(k));
return simpleArrCopy(c,/*public*/ __c_len,k);
}
/*public return*/
int32_t simpleArrCopy32_wrapper(int32_t c[],/*public*/ uint32_t __c_len,const int32_t k[5]) {
public_out(__SMACK_return_value());
public_in(__SMACK_value(c));
public_in(__SMACK_value(__c_len));
public_in(__SMACK_value(k));
return simpleArrCopy32(c,/*public*/ __c_len,k);
}
/*public return*/
int32_t simpleArrCopyStatic_wrapper(int8_t c[5],const int8_t k[5]) {
public_out(__SMACK_return_value());
public_in(__SMACK_value(c));
public_in(__SMACK_value(k));
return simpleArrCopyStatic(c,k);
}
/*public return*/
int32_t simpleArrCopyStatic32_wrapper(int32_t c[5],const int32_t k[5]) {
public_out(__SMACK_return_value());
public_in(__SMACK_value(c));
public_in(__SMACK_value(k));
return simpleArrCopyStatic32(c,k);
}
/*public return*/
int32_t arrCopy_wrapper(/*public*/ const int32_t arr[5],/*public*/ int32_t index) {
public_out(__SMACK_return_value());
public_in(__SMACK_value(arr));
public_in(__SMACK_values(arr,5));
public_in(__SMACK_value(index));
return arrCopy(/*public*/ arr,/*public*/ index);
}
/*public return*/
int32_t mediumComplexArrCopy_wrapper(/*public*/ int32_t index) {
public_out(__SMACK_return_value());
public_in(__SMACK_value(index));
return mediumComplexArrCopy(/*public*/ index);
}
/*public return*/
int32_t complexArrCopy_wrapper(/*public*/ int32_t index) {
public_out(__SMACK_return_value());
public_in(__SMACK_value(index));
return complexArrCopy(/*public*/ index);
}
|
C | #define _CRT_SECURE_NO_WARNINGS 1
//qsortϰʹ
#include <stdio.h>
#include < stdlib.h >
void test(void);
int my_strcmp1(const void* s1, const void* s2); //ȽС
int my_strcmp2(const void* s1, const void* s2); //ȽַС
int my_strcmp3(const void* s1, const void* s2); //ȽϽṹ-С
int my_strcmp4(const void* s1, const void* s2); //ȽϽṹ-ִС
int main()
{
test();
return 0;
}
int my_strcmp1(const void* s1, const void* s2) //ȽС
{
return *(int*)s1 > * (int*)s2 ? 1 : 0;
}
int my_strcmp2(const void* s1, const void* s2) //ȽַС
{
return strcmp((char*)s1, (char*)s2);
}
int my_strcmp3(const void* s1, const void* s2) //ȽϽṹ-С
{
return *((char*)s1 + 20) > * ((char*)s2 + 20) ? 1 : 0;
}
int my_strcmp4(const void* s1, const void* s2) //ȽϽṹ-ִС
{
return strcmp((char*)s1, (char*)s2); //-1С 0 1
}
struct MyStruct
{
char name[20];
int age;
};
void test(void)
{
int i = 0;
/***************************/
int a[10] = {1,2,5,3,4,9,6,7,8,10};
qsort(a,10,4, my_strcmp1);
for (i=0;i<10;i++)
{
printf("%d ",a[i]);
}
printf("\n");
/**********ַ*****************/
char b[10] = {2,4,1,3,5,6,9,8,7,10};
char c[5] = { 'a','r','g','z','b' };
qsort(b, 10, 1, my_strcmp2);
for (i = 0; i < 10; i++)
{
printf("%d ", b[i]);
}
printf("\n");
qsort(c, 5, 1, my_strcmp2);
for (i = 0; i < 5; i++)
{
printf("%c ", c[i]);
}
printf("\n");
/**********ṹ*****************/
struct MyStruct stu[4] =
{ {"zhang", 15 } ,{ "wang",18 } ,{ "li",25 },{ "qi",16 } };
/**********ṹ--***********/
qsort(stu, 4, 24, my_strcmp3); //
for (i = 0; i < 4; i++)
{
printf("%s ", stu[i].name);
printf("%d ", stu[i].age);
printf("\n");
}
printf("\n");
/**********ṹ--***********/
qsort(stu, 4, 24, my_strcmp4); //
for (i = 0; i < 4; i++)
{
printf("%s ", stu[i].name);
printf("%d ", stu[i].age);
printf("\n");
}
printf("\n");
} |
C | #include<stdio.h>
#include "myStr.h"
#include "myMath.h"
void main()
{
char arr[4]="abba";
if(isPalindrome(arr,4) == 1)
{
printf("Palindrome\n");
}
else
{
printf("Not a palindrome\n");
}
int a=7;
int b=5;
if(isEqual(a,b) == 1)
{
printf("Equal\n");
}
else
{
printf("Not Equal\n");
}
swap(a,b);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#define FILE_NAME_BUF 12+4
#define MAX_COLOR_VAL 255
#define PIXELS_PER_LINE 2
#define X_BOUND 1024
#define Y_BOUND 1024
//usage: ./main outfile t-value func
typedef struct Pixel
{
uint8_t red;
uint8_t grn;
uint8_t blu;
} Pixel;
//this code is not mine
void mandelbrot(Pixel frame_buffer[X_BOUND][Y_BOUND],int x_bound,int y_bound,int t)
{
int max = 255;
Pixel colors[5] = {
(Pixel) {.red=255,.grn=255,.blu=255},
(Pixel) {.red=200,.grn=255,.blu=255},
(Pixel) {.red=150,.grn=255,.blu=255},
(Pixel) {.red=100,.grn=255,.blu=255},
(Pixel) {.red=50,.grn=255,.blu=255}};
for (int i=0;i<x_bound;i++) //i is row, x_bound is height
{
for (int j=0;j<y_bound;j++) //j is col, y_bound is width
{
double c_re = (j-y_bound)/2.0*4.0/y_bound;
double c_im = (i-x_bound)/2.0*4.0/y_bound;
double x=0;
double y=0;
int k = 0;
while (x*x+y*y<=4 && k<max)
{
double x_new = x*x-y*y +c_re;
y=2*x*y+c_im;
x=x_new;
k++;
}
if (k<max) frame_buffer[j][i] = colors[k%5];
else frame_buffer[j][i] = (Pixel) {.red=0,.grn=0,.blu=0};
}
}
}
void writeframebuffer(Pixel[X_BOUND][Y_BOUND],int,int);
void writeimageheader(FILE*);
void writepixel(FILE*,int,int,Pixel[X_BOUND][Y_BOUND]);
int main(int argc, char**argv)
{
//FILE *out = fopen(argv[1],"w");
Pixel (*fptr)(Pixel[X_BOUND][Y_BOUND],int,int,int) = NULL;
Pixel frame_buffer[X_BOUND][Y_BOUND];
//verify argc and argv stuff here
if (argc!=3)
{
printf("argc\n");
return EXIT_FAILURE;
}
mandelbrot(frame_buffer,X_BOUND,Y_BOUND,atoi(argv[2]));
writeframebuffer(frame_buffer,X_BOUND,Y_BOUND);
return EXIT_SUCCESS;
}
void writeimageheader(FILE* out)
{
fprintf(out,"P3\n");
fprintf(out,"%d %d\n",X_BOUND,Y_BOUND);
fprintf(out,"%d\n",MAX_COLOR_VAL);
}
void writepixel(FILE* out,int x,int y,Pixel frame_buffer[X_BOUND][Y_BOUND])
{
Pixel cur = frame_buffer[x][y];
fprintf(out,"%d %d %d ",cur.red,cur.grn,cur.blu);
}
void writeframebuffer(Pixel frame_buffer[X_BOUND][Y_BOUND],int x_bound,int y_bound)
{
static int frame = 0;
char framename[FILE_NAME_BUF] = {0};
sprintf(framename,"%d",frame); //convert frame no to string
strncat(framename,".ppm",4);
FILE *out = fopen(framename,"w");
writeimageheader(out);
int pixels = 0;
for (int i=0;i<X_BOUND;i++) //rows
{
for (int j=0;j<Y_BOUND;j++) //columns
{
writepixel(out,i,j,frame_buffer);
if (pixels==PIXELS_PER_LINE)
{
fprintf(out,"\n");
pixels=0;
}
else pixels++;
}
}
fclose(out);
}
|
C | #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <memory.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>
#include <stddef.h>
int s1;
struct sockaddr_in addr;
int secret, number;
int send_server();
void recv_server(char response[], size_t size_);
int main(int argc, char * argv){
int s = socket(AF_INET, SOCK_STREAM, 0);
if(s < 0){
perror("Error calling socket");
return 0;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(9006);
addr.sin_addr.s_addr = htonl(INADDR_ANY);// .
if(bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0){
perror("Error calling bind");
return 0;
}
if(listen(s, 5)){
perror("Error calling listen");
return 0;
}
s1 = accept(s, NULL, NULL);
if(s1 < 0){
perror("Error calling accept");
return 0;
}
srand(time(NULL));
int res;
secret = rand() % 10 + 1;
printf("Secret = %d \n", secret);
char response[] = "I am thinking 1-10::<guess> <argument>";
char response_more[] = "More";
char response_less[] = "Less";
char response_correct[] = "Correct";
char response_err[] = "Incorrect format";
recv_server(response, sizeof(response));
while(1){
res = send_server();
if(res == -1){
recv_server(response_err, sizeof(response_err));
}
if(number > secret)
recv_server(response_less, sizeof(response_less));
else if(number < secret)
recv_server(response_more, sizeof(response_more));
else if(number == secret)
recv_server(response_correct, sizeof(response_correct));
number = 0;
}
return 0;
}
int send_server(){/* */
char buffer[40], result[40];
int counter = 0, i, j = 0;
memset(buffer, 0, sizeof(char)*40);
memset(result, 0, sizeof(char)*40);
int rc = recv(s1, buffer, 39, 0);
printf("%s", buffer);
if(rc < 0){
if(errno == EINTR)
return 0;
perror("Can't receive data.");
return 0;
}
if(rc == 0)
return 0;
char srt[]="<guess>";
char *ptr = strstr(buffer, "<guess> <");
if(ptr!= NULL){
}else{
return -1;
}
for(i = 0; i<40; i++){
if(buffer[i]>='0' && buffer[i]<='9'){
result[j]=buffer[i];
j++;
}
}
result[j] = '\0';
number = atoi(result);
return 0;
}
void recv_server(char response[], size_t size_){
if(sendto( s1, response, size_, 0, (struct sockaddr *)&addr, sizeof(addr) ) < 0)
perror("Error sending response");
}
|
C | // Program treba spojit 2 stringa u 1.
#include <stdio.h>
int main()
{
char str1[50], str2[50], i, j;
printf("Unesi prvi string: ");
scanf("%s",str1);
printf("\nUnesi drugi string string: ");
scanf("%s",str2);
// Ova petlja ide kroz prvi string
for(i=0; str1[i]!='\0'; ++i);
// Ova petlja ce spojiti drugi string s prvim.
for(j=0; str2[j]!='\0'; ++j, ++i)
{
str1[i]=str2[j];
}
// \0 predstavlja kraj stringa.
str1[i]='\0';
printf("\nOutput: %s",str1);
return 0;
}
|
C | #include <stdio.h>
#include <math.h>
main(int argc, char *argv[])
{
double L; /* Srednji broj pokvarenih uredaja u liniji */
double Q; /* Srednji broj pokvarenih uredaja u sustavu */
double R; /* Srednje vrijeme zadrzavanja */
double S; /* Srednje vrijeme popravka */
double U; /* Ukupno srednja zaposlenost */
double rho; /* Zaposlenost po jednom spoluzitelju */
double W; /* Srednje vrijeme cekanja u repu */
double X; /* Srednja propusnost u sustavu */
double Z; /* Srednje vrijeme izmedu nastanka kvarova */
double p; /* Privremena varijabla za racunanje vjerojatnosti */
double p0; /* Vjerojatnost da nema kvarova */
long m;
long N;
long k;
if (argc < 5) {
printf("Uporaba: %s m S N Z\n", *argv);
printf(" m - Broj posluzitelja \n");
printf(" S - Srednje vrijeme posluzivanja \n");
printf(" N - Broj uredaja \n");
printf(" Z - Srednje vrijeme izmedu nastanka kvarova \n");
exit(1);
}
m = atol(*++argv);
S = atol(*++argv);
N = atol(*++argv);
Z = atol(*++argv);
p = p0 = 1;
L = 0;
for( k=1; k<=N; k++) {
p *= (N - k + 1) * S / Z;
if (k <= m) {
p /= k;
} else {
p /= m;
}
p0 += p;
if (k > m) {
L += p * (k - m);
}
}
p0 = 1.0 / p0;
L *= p0;
W = L * (S + Z) / (N - L);
R = W + S;
X = N / (R + Z);
U = X * S;
rho = U/m;
Q = X*R;
printf ("\n");
printf ("M/M/%ld/%ld/%ld Model\n", m, N, N);
printf ("---------------------------------------\n");
printf (" Broj uredaja: %5.0ld\n", N);
printf (" Vrijeme rada uredaja: %5.4lf\n", Z);
printf (" Vrijeme posluzivanja: %5.4lf\n", S);
printf (" Ucestalost kvarova: %5.4lf\n", 1 / Z);
printf (" Ucestalost posluzivanja: %5.4lf\n", 1 / S);
printf (" Zaposlenost sustava: %5.4lf\n", U);
printf (" Zaposlenost po pos.: %5.4lf\n", rho);
printf ("\n");
printf (" Broj uredaja u sustavu: %5.4lf\n", Q);
printf (" Broj popravaka: %5.4lf\n", U);
printf (" Broj uredaja u repu: %5.4lf\n", Q - U);
printf (" Vrijeme cekanja: %5.4lf\n", R - S);
printf (" Propusnost: %5.4lf\n", X);
printf (" Vrijeme odziva: %5.4lf\n", R);
printf (" Norm. vrijeme cek.: %5.4lf\n", R / S);
printf ("\n");
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sa_sb_ss_pa_pb.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abaranov <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/04/05 19:08:23 by abaranov #+# #+# */
/* Updated: 2017/04/05 19:08:24 by abaranov ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
void sa(t_ab **strc, t_ab *moves)
{
int t;
if ((*strc) != NULL && (*strc)->next != NULL)
{
t = (*strc)->next->num;
(*strc)->next->num = (*strc)->num;
(*strc)->num = t;
}
lst_add(&moves, 1);
}
void sb(t_ab **strc, t_ab *moves)
{
int t;
if ((*strc) != NULL && (*strc)->next != NULL)
{
t = (*strc)->next->num;
(*strc)->next->num = (*strc)->num;
(*strc)->num = t;
}
lst_add(&moves, 2);
}
void sa_ss(t_ab **strc)
{
int t;
if ((*strc) != NULL && (*strc)->next != NULL)
{
t = (*strc)->next->num;
(*strc)->next->num = (*strc)->num;
(*strc)->num = t;
}
}
void sb_ss(t_ab **strc)
{
int t;
if ((*strc) != NULL && (*strc)->next != NULL)
{
t = (*strc)->next->num;
(*strc)->next->num = (*strc)->num;
(*strc)->num = t;
}
}
void ss(t_ab *a, t_ab *b, t_ab *moves)
{
sa_ss(&a);
sb_ss(&b);
lst_add(&moves, 3);
}
|
C | #include "../inc/maze.h"
/**
* render_mini - Renders a minimap on the top right of the screen.
*
* @instance: Struct containing the SDL2 renderer and window.
* @maze: Struct containing a pointer to the layout of the maze.
* @status: Struct containing variables on camera position.
*/
void render_mini(SDL_Instance instance, map maze, player status)
{
SDL_Rect rect;
rect.x = WINDOW_WIDTH - 210;
rect.y = 0;
rect.w = 210;
rect.h = 210;
SDL_SetRenderDrawColor(instance.renderer, 0, 128, 0, 0);
SDL_RenderFillRect(instance.renderer, &rect);
render_mini_helper(instance, maze, status);
}
/**
* render_mini_helper - Helps renders the walls and player on the minimap.
*
* @instance: Struct containing the SDL2 renderer and window.
* @maze: Struct containing a pointer to the layout of the maze.
* @status: Struct containing variables on camera position.
*/
void render_mini_helper(SDL_Instance instance, map maze, player status)
{
SDL_Rect rect;
int start_x;
int end_x;
int start_y;
int end_y;
int i = 0;
int j = 0;
rect.w = 14;
rect.h = 14;
rect.x = WINDOW_WIDTH - 210;
rect.y = 0;
find_x(&start_x, &end_x, maze, status);
find_y(&start_y, &end_y, maze, status);
SDL_SetRenderDrawColor(instance.renderer, 200, 200, 200, 0);
for (i = start_y; i < end_y; i++)
{
rect.x = WINDOW_WIDTH - 210;
for (j = start_x; j < end_x; j++)
{
if (maze.layout[i][j] > '0')
{
SDL_RenderFillRect(instance.renderer, &rect);
}
else if (i == (int) status.pos_x && j == (int) status.pos_y)
{
SDL_SetRenderDrawColor(instance.renderer, 255, 0, 0, 0);
SDL_RenderFillRect(instance.renderer, &rect);
SDL_SetRenderDrawColor(instance.renderer, 200, 200, 200, 0);
}
rect.x += 14;
}
rect.y += 14;
}
}
/**
* find_x - Find the starting and ending x-coordinate on the map to render
* in the minimap.
*
* @start_x: Pointer to store the starting x-coordinate.
* @end_x: Pointer to store the ending x-coordinate.
* @maze: Struct containing a pointer to the layout of the maze.
* @status: Struct containing variables on camera position.
*/
void find_x(int *start_x, int *end_x, map maze, player status)
{
*start_x = (int) status.pos_y - 7;
*end_x = 0;
if (*start_x < 0)
{
*end_x = -(*start_x);
*start_x = 0;
}
*end_x += (int) status.pos_y + 8;
if (*end_x > (int) maze.width)
{
*end_x = (int) maze.width;
*start_x = (int) maze.width - 15;
}
}
/**
* find_y - Find the starting and ending y-coordinate on the map to render
* in the minimap.
*
* @start_y: Pointer to store the starting y-coordinate.
* @end_y: Pointer to store the ending y-coordinate.
* @maze: Struct containing a pointer to the layout of the maze.
* @status: Struct containing variables on camera position.
*/
void find_y(int *start_y, int *end_y, map maze, player status)
{
*start_y = (int) status.pos_x - 7;
*end_y = 0;
if (*start_y < 0)
{
*end_y = -(*start_y);
*start_y = 0;
}
*end_y += (int) status.pos_x + 8;
if (*end_y > (int) maze.height)
{
*end_y = (int) maze.height;
*start_y = (int) maze.height - 15;
}
}
|
C | bool binary_search(vector<int> list, int bot, int top, int target){
if (list.size() == 0) return false;
if (list.size() == 1) return true;
if (bot < top){
int m = bot + (top - bot) / 2;
if (list[m] == target) return true;
else if (list[m] < target) return binary_search(list, m + 1, top, target);
else return binary_search(list, bot, m - 1, target);
}
return false;
} |
C | #include <stdio.h>
struct exercise{
const char *discrpition;
float duration;
};
struct meal{
const char *ingredient;
float weight;
};
struct preference{
struct meal food;
struct exercise exercise;
};
struct fish{
const char *name;
const char *species;
int teeth;
int age;
struct preference care;
};
void label(struct fish a){
printf("이름: %s\n품종: %s\n이빨수: %i\n나이: %i\n", a.name, a.species, a.teeth, a.age);
printf("%2.2f파운드의 %s를 먹이고 %2.2f시간동안 %s하게 하세요!!\n",
a.care.food.weight, a.care.food.ingredient, a.care.exercise.duration, a.care.exercise.discrpition);
}
int main(){
struct fish snappy = {"snappy", "piranya", 48, 12, {{"meat", 0.2}, {"거품수족관에서 수영", 7.5}}};
label(snappy);
return 0;
}
|
C | // WAP To Create two sets and perform the Symmeteric set difference operation
#include<stdio.h>
int main (){
int n,m , set1[100] , set2[100];
printf("\n Enter the Elements of SET A ");
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&set1[i]);
}
printf("\n Enter the Elements of SET B ");
scanf("%d",&m);
for(int i=0;i<m;i++){
scanf("%d",&set2[i]);
}
int i = 0 , j = 0 , c[100] , k = 0 ;
printf("\n Symmetric Set Difference of two sets are ") ;
while (i < n && j < m) {
if (set1[i] < set2[j]) {
printf("%d ", set1[i]);
i++;
}
else if (set2[j] < set1[i]) {
printf("%d ", set2[j]);
j++;
}
else{
i++;
j++;
}
}
return 0 ;
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main()
{
int n1 = 0;
printf("Introduza o numero\n");
scanf("%d",&n1);
if((n1>=0) && (n1%2)==0){
printf("%d par",n1);
}else if((n1>=0) && (n1%2)==0){
printf("%d impar",n1);
}
return 0;
}
|
C | #include <stdio.h>
#include <string.h>
int main() {
const char *date = "18.07.2013w";
char c[10];
memset(c, 0, 10);
int y, m, d, i;
i = sscanf(date, "%d.%d.%4d%c", &d, &m, &y, c);
printf("date: %s; day %2d, month %2d, year %4d, extra: %c, %d\n", date, d, m,
y, c[0], i);
i = sscanf(date, "%d.%d.%3c", &d, &m, c);
printf("date: %s; day %2d, month %2d, year %4d, extra: %s, %d\n", date, d, m,
y, c, i);
{
const char *date = "18.07.2013";
char c;
int y, m, d, i;
if ((i = sscanf(date, "%d.%d.%4d%c", &d, &m, &y, &c)) == 3)
{
printf("date: %s; day %2d, month %2d, year %4d \n", date, d, m, y);
}
else
{
printf("Error in sscanf: actually parsed %d", i);
}
}
}
|
C | #include<stdio.h>
#include<string.h>
struct STR
{char num[10];int s;};
main()
{
struct STR t,*p;
t.num[0]="a";
t.num[0]="b";
t.num[0]="c";
p=&t;
//p->num[0]='\0';
//strcpy((*p).num,"");
//puts(t.num);
p->s=99;
printf("%d",(*p).s);
}
/*
void fun(char *a)
{
int i=0,j,k;
while(a[i]=='*')
++i;
for(j=i+1;*a;++j)
{
if(a[j]=='*')
{
for(k=j;*a;++k)
a[k]=a[k+1];
}
}
//a[j]='\0';
}
main()
{
char s[81];
gets(s);
fun(s);
puts(s);
}*/
|
C | /*############################################################################*\
# _ ___ _____ _ ___ ___ __ __ _ _ _ _ _____ ___ ___ #
# /_\ | _ \_ _/ | / __|_ _| \/ | | | | | /_\_ _/ _ \| _ \ #
# / _ \| / | | | | \__ \| || |\/| | |_| | |__ / _ \| || (_) | / #
# /_/ \_\_|_\ |_| |_| |___/___|_| |_|\___/|____/_/ \_\_| \___/|_|_\ #
# #
# by Mathieu FOURCROY #
# 2015 #
\*############################################################################*/
/**
* @file utils.c
* @author Mathieu Fourcroy
* @date June 2015
* @version 0.0.1
*
* This file contains the function which are used as general purpose, not for
* training or testing the network, not for I/O. They are mean to be used in any
* source file.
*/
/*=====| INCLUDES |===========================================================*/
#include <limits.h>
#include "utls.h"
#include "io.h"
#include "ccl_internal.h"
/*=====| FUNCTIONS |==========================================================*/
int cmpFun(const void *elem1, const void *elem2, CompareInfo *ExtraArgs){
return !(elem1 == elem2);
}
/** Check if a given pattern is in a given patterns set.
*
* @param[in] set The patterns set.
* @param[in] pat The pattern to check.
*/
ulong pat_in_set(Vector *set, Vector *pat){
ulong i;
ulong index = NOT_FOUND;
vec_set_cmp_fun(pat, cmpFun);
for(i = 0; i < vec_size(set); i++){
vec_set_cmp_fun(iVector.GetElement(set, i), cmpFun);
if(iVector.Equal(iVector.GetElement(set, i), pat)){
index = i;
break;
}
}
return index;
}
/** Check if a given pattern is in a cluster patterns set.
*
* @param[in] clusts The network clusters.
* @param[in] pat The pattern to check.
*
* @return The cluster index containing the pattern or NOT_FOUND if the pattern
* dosen't belongs to any cluster.
*/
ulong pat_in_clust_set(const Vector *clusts, ulong pat){
ulong i, j;
ulong prot_number = NOT_FOUND;
Vector *elem;
for(i = 0; i < iVector.Size(clusts); i++){
elem = get_pat_set(vec_get_as_clust(clusts, i));
for(j = 0; j < iVector.Size(elem); j++){
if(*(ulong *)iVector.GetElement(elem, j) == pat){
prot_number = i;
break;
}
}
if(prot_number != NOT_FOUND){
break;
}
}
return prot_number;
}
/** Push each pattern of a list of CSVLine structures into a vector.
*
* @param[in] lines The list of CSVLine structures.
*
* @return The created vector containing the patterns.
*/
void line_val_to_vec(Vector *res, List *lines){
ulong i;
for(i = 0; i < iList.Size(lines); i++){
vec_pushback(res, (*(CSVLine *)iList.GetElement(lines, i)).val);
}
}
/** Push each class variable of a list of CSVLine structures into a vector.
*
* @note The elements of the vector or of variable size so we must create the
* vector with sizeof(void *) and push a pointer to the elements.
*
* @param[in] lines The list of CSVLine structures.
*
* @return The created vector containing the classes names.
*/
void line_class_to_vec(Vector *res, List *lines){
ulong i;
for(i = 0; i < iList.Size(lines); i++){
vec_pushback(res, &(*(CSVLine *)iList.GetElement(lines, i)).class);
}
}
|
C | #include <stdio.h>
void main()
{
char chiffre;
do
{
printf("\nChoisir un chiffre :");
scanf(" %c",&chiffre);
switch(chiffre)
{
case '0':
printf("ZERO");
break;
case '1':
printf("UN");
break;
case '2':
printf("DEUX");
break;
case '3':
printf("TROIS");
break;
case '4':
printf("QUATRE");
break;
case '5':
printf("CINQ");
break;
case '6':
printf("SIX");
break;
case '7':
printf("SEPT");
break;
case '8':
printf("HUIT");
break;
case '9':
printf("NEUF");
break;
}
}while(chiffre!='#');
}
|
C | #pragma once
/* "kernel" utility things */
/* fprintf */
#define fprintf(fd, fmt, args...) dbg(DBG_TEST, fmt, ##args)
#define printf(fmt, args...) dbg(DBG_TEST, fmt, ##args)
/* errno */
#define errno (curthr->kt_errno)
/* malloc/free */
#define malloc kmalloc
#define free kfree
/* The "kernel" system calls */
#define ksyscall(name, formal, actual) \
static int ksys_##name formal { \
int ret = do_##name actual; \
if (ret < 0) { \
errno = -ret; \
return -1; \
} \
return ret; \
}
ksyscall(close, (int fd), (fd))
ksyscall(read, (int fd, void *buf, size_t nbytes), (fd, buf, nbytes))
ksyscall(write, (int fd, const void *buf, size_t nbytes), (fd, buf, nbytes))
ksyscall(dup, (int fd), (fd)) ksyscall(dup2, (int ofd, int nfd), (ofd, nfd))
ksyscall(mkdir, (const char *path), (path))
ksyscall(rmdir, (const char *path), (path))
ksyscall(link, (const char *old, const char *new), (old, new))
ksyscall(unlink, (const char *path), (path))
ksyscall(rename, (const char *oldname, const char *newname),
(oldname, newname)) ksyscall(chdir, (const char *path), (path))
ksyscall(lseek, (int fd, int offset, int whence), (fd, offset, whence))
ksyscall(getdent, (int fd, struct dirent *dirp), (fd, dirp))
ksyscall(stat, (const char *path, struct stat *uf), (path, uf))
ksyscall(open, (const char *filename, int flags), (filename, flags))
#define ksys_exit do_exit
int ksys_getdents(int fd, struct dirent *dirp, unsigned int count) {
size_t numbytesread = 0;
int nbr = 0;
dirent_t tempdirent;
if (count < sizeof(dirent_t)) {
curthr->kt_errno = EINVAL;
return -1;
}
while (numbytesread < count) {
if ((nbr = do_getdent(fd, &tempdirent)) < 0) {
curthr->kt_errno = -nbr;
return -1;
}
if (nbr == 0) {
return numbytesread;
}
memcpy(dirp, &tempdirent, sizeof(dirent_t));
KASSERT(nbr == sizeof(dirent_t));
dirp++;
numbytesread += nbr;
}
return numbytesread;
}
/*
* Redirect system calls to kernel system calls.
*/
#define mkdir(a, b) ksys_mkdir(a)
#define rmdir ksys_rmdir
#define mount ksys_mount
#define umount ksys_umount
#define open(a, b, c) ksys_open(a, b)
#define close ksys_close
#define link ksys_link
#define rename ksys_rename
#define unlink ksys_unlink
#define read ksys_read
#define write ksys_write
#define lseek ksys_lseek
#define dup ksys_dup
#define dup2 ksys_dup2
#define chdir ksys_chdir
#define stat(a, b) ksys_stat(a, b)
#define getdents(a, b, c) ksys_getdents(a, b, c)
#define exit(a) ksys_exit(a)
/* Random numbers */
/* Random int between lo and hi inclusive */
#define RAND_MAX INT_MAX
#define RANDOM(lo, hi) \
((lo) + \
(((hi) - (lo)+1) *(randseed = (randseed * 4096 + 150889) % 714025)) / \
714025)
static unsigned long long randseed = 123456L;
static int rand(void) {
randseed = (randseed * 4096 + 150889) % RAND_MAX;
return randseed;
}
static void srand(unsigned int seed) { randseed = seed; }
|
C | /** Handling for type tuple nodes
* @file
*
* This source file is part of the Cone Programming Language C compiler
* See Copyright Notice in conec.h
*/
#ifndef ttuple_h
#define ttuple_h
// A tuple is a comma-separated list of elements, each different.
// This structure supports both type tuples and tuple literals.
typedef struct {
ITypeNodeHdr;
Nodes *elems;
} TupleNode;
// Create a new type tuple node
TupleNode *newTupleNode(int cnt);
// Clone tuple
INode *cloneTupleNode(CloneState *cstate, TupleNode *node);
// Serialize a type tuple node
void ttuplePrint(TupleNode *tuple);
// Name resolution of type tuple node
void ttupleNameRes(NameResState *pstate, TupleNode *node);
// Type check type tuple node
void ttupleTypeCheck(TypeCheckState *pstate, TupleNode *node);
// Compare that two tuples are equivalent
int ttupleEqual(TupleNode *totype, TupleNode *fromtype);
#endif
|
C | /*
* This program can simulate the execution of a memory-bound task. Under the simulation,
* Each task writes its the residence time into /proc/buffer for each 3 seconds.
* When /proc/buffer is written, the guest OS indirectly writes the file storing data
* of each memory-bound task.
*/
#include "FixedAccMem.h"
#define PAGE_SIZE 4096
char *heapMem = NULL;
static struct timeval runth_s,runth_e;
/* import Timediff() and Timeadd() from other file */
extern void Timediff(struct timeval *src,struct timeval *des,int type);
extern void Timeadd(struct timeval *src,struct timeval *des);
/* set a callback function of signal sighup */
/* when a signal is sent to here, the task is allowed to exit the loop */
void sighup()
{
free(heapMem);
exit(0);
}
/* set a callback function of a timer */
/*
* When this function is called, it calculates its residence time and
* writes the residence time into /proc/buffer
*/
static void timer_handler()
{
int resultfd;
double rtime;
char output[30];
/* require for accessing /proc/buffer */
resultfd = open("/proc/buffer", O_RDWR);
if(resultfd < 0) {
perror("open");
return;
}
/* record the end time of each task */
gettimeofday(&runth_e,NULL);
/* calculate the residence time of each memory-bound task */
/*
* The residence time is the difference between the beginning time
* and the end time
*/
Timediff(&runth_s,&runth_e,2);
rtime=(double)runth_e.tv_sec+(double)runth_e.tv_usec/1000000;
/* write the residence time into /proc/buffer */
sprintf(output,"%d",(int)(rtime*1000));
write(resultfd, output, strlen(output) + 1);
close(resultfd);
}
/* The main function of this program */
int main(int argc, char *argv[])
{
int iter,mUsage,temp = temp;
struct itimerval timer;
struct sigaction sa;
double rtime = rtime;
char input = 'a';
/* set a callback function of a timer */
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &timer_handler;
sigaction(SIGALRM,&sa,NULL);
/* This is the period between now and the first timer interrupt. If zero, the alarm is disabled. */
timer.it_value.tv_sec = 3;
timer.it_value.tv_usec = 0;
/* This is the period between successive timer interrupts. If zero, the alarm will only be sent once. */
timer.it_interval.tv_sec = 3;
timer.it_interval.tv_usec = 0;
/* set a timer to periodically collect the data */
setitimer(ITIMER_REAL,&timer,NULL);
/* set a callback function to the function sighup */
signal(SIGHUP,sighup);
/* set the memory usage for each memor-bound task */
mUsage = 49152; /* This value is in kb unit */
/* The memory usage is fixed to mUsage via pre-allocating memory */
heapMem = (char*)malloc(mUsage*1024*sizeof(char));
/* Initialize the pre-allocated memory */
for (iter = 0; iter < mUsage/4;iter++)
heapMem[iter*4096] = 10;
/* set a infinite loop to prevent decrease of the number of tasks at same time */
/* if the boolean ready_to_exit is 0, the task jump out from this loop */
while(1)
{
/* record the beginning time of each task */
gettimeofday(&runth_s,NULL);
for(iter = 0;iter < iterInTask; iter++)
{
int pos;
/* random access */
input = input + (rand() % 26);
pos = (rand() % (mUsage/4));
if (iter%2 == 0)
heapMem[pos*4096] = input;
else
temp = heapMem[pos*4096];
temp = temp + ( rand() % 26 );
/* update the beginning time of each task */
gettimeofday(&runth_e,NULL);
}
Timediff(&runth_s,&runth_e,2);
}
return EXIT_SUCCESS;
}
|
C | #include <stdio.h>
// [man, dog, sheep, vegetable]
char impassable[6] = {0b0011, 0b0110, 0b0111, 0b1000, 0b1001, 0b1100};
char stack[15];
int top = 0;
int isPassable(char status) {
// check repeating
for (int i = 0; i < top; i++)
if (stack[i] == status) return 0;
// check impassable
for (int i = 0; i < 6; i++)
if (impassable[i] == status) return 0;
return 1;
}
int moveCounter(char cur, char next) {
int result = 0;
// get diff
cur ^= next;
// count diff
while (cur > 0) {
if (cur & 1) result++;
cur >>= 1;
}
return result;
}
void river(char status) {
stack[top] = status;
top++;
// basecase is status to 0b0000
if (status == 0b0000) {
// print stack
for (int i = 0; i < top - 1; i++) printf("%d => ", stack[i]);
printf("%d\n", stack[top - 1]);
} else {
for (char i = 0; i <= 15; i++) {
// man on the boat toggle
if ((status & 0b1000) != (i & 0b1000)) {
// only allowed change less than or equal to 2 bit
if (moveCounter(status, i) <= 2) {
// not repeating and impassable
if (isPassable(i)) river(i);
}
}
}
}
top--;
}
int main() {
river(0b1111);
return 0;
}
|
C | #include "lem_in.h"
void free_string_array(char **array)
{
size_t i;
if (array)
{
i = 0;
while (array[i] != NULL)
{
free(array[i]);
i++;
}
free(array);
}
}
void free_lemin(t_lemin *lemin, t_room *path)
{
t_room *tmp;
if (lemin)
{
while (lemin->room)
{
ft_strdel(&(lemin->room)->name);
if (lemin->room->connection)
{
free(lemin->room->connection);
}
tmp = lemin->room;
lemin->room = lemin->room->next;
free(tmp);
}
free_string_array(lemin->stdin);
free(lemin);
}
while (path)
{
tmp = path;
path = path->next;
free(tmp);
}
}
int print_error(const char *error)
{
ft_putendl_fd(error, STDERR_FILENO);
return (ERROR);
}
char **ft_realloc(char **array, size_t size)
{
char **new;
size_t i;
if ((array == NULL) || (new = ft_memalloc(sizeof(char *) * size)) == NULL)
{
return (NULL);
}
i = 0;
while (array[i] != NULL)
{
new[i] = array[i];
i++;
}
free(array);
return (new);
}
void free_rooms(t_room *r)
{
t_room *tmp;
while (r)
{
tmp = r;
r = r->next;
free(tmp);
}
}
|
C | #include<stdio.h>
#define min(a,b) (((a)<(b))?(a):(b))
typedef long long int lli;
int main() {
lli d1,d2,d3;
scanf("%lld %lld %lld", &d1, &d2, &d3);
lli dis1,dis2,dis3,dis4;
dis1=d1+d2+d3;
dis2=2*(d1+d2);
dis3=d1+d3+d3+d1;
dis4=d2+d3+d3+d2;
printf("%lld\n", min(dis1,min(dis2,min(dis3,dis4))));
return 0;
}
|
C | #ifndef _UNIT_H_
#define _UNIT_H_
#include <stdint.h>
#include <stdbool.h>
#define UNIT 1.0f
typedef double data_t;
/* unit conversion works as follows */
/* RATIO and OFFSET are used to convert the unit into terms of units[0] */
/* value[0] = RATIO[n] * value[n] + OFFSET[n]; */
/* this can then be converted to another unit with */
/* units[n] = (value[0] - OFFSET[n])/RATIO[n] */
struct unit_t {
const char* name;
const char* abbr;
data_t ratio; /* relative to first unit in array */
data_t offset;
data_t step;
data_t value;
bool negative;
};
#endif
|
C | #include <stdio.h>
#include <string.h>
int strrindex(char s[], char t[]);
int main(){
char s[] = "Hallo Test123 Hallo Test123 Hallo Test123 Hall";
char t[] = "Hallo";
printf("%d \n", strrindex(s,t));
}
int strrindex(char s[], char t[]){
int i, j, temp;
int final = -1;
for( i = 0; i < strlen(s); i++){
if(s[i] == t[0]){
temp = i;
for(j = 0; s[i] == t[j]; j++){
i++;
}
if( j == strlen(t))
final = temp;
}
}
return final;
}
|
C | /*********************************************************************
* Filename: ring.c
* Author: Prasad Maddumage <[email protected]>
* Created at: Wed Jul 16 22:48:34 2014
* Modified at: Mon Oct 2 23:55:25 2017
* Modified by: Prasad Maddumage <[email protected]>
* Version: $Revision: 1.1 $
* Description: Exchange data between nearest neighbors
* Original code, "mpi_ringtopo.c" by Blaise Barney
*https://computing.llnl.gov/tutorials/mpi/samples/C/mpi_ringtopo.c
********************************************************************/
#include "mpi.h"
#include <stdio.h>
main(int argc, char *argv[]) {
int numtasks, rank, next, prev, buf[2], tag1=1, tag2=2;
MPI_Request reqs[4];
MPI_Status stats[4];
//Initializing MPI
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
//Who are my neighbors (prev and next)?
prev = rank - 1;
next = rank + 1;
//Rank 0's "previous" neighbor is n-1
if (rank == 0) prev = numtasks - 1;
//Rank n-1's "next" neighbor is 0
if (rank == (numtasks - 1)) next = 0;
MPI_Irecv(&buf[0], 1, MPI_INT, prev, tag1, MPI_COMM_WORLD, &reqs[0]);
MPI_Irecv(&buf[1], 1, MPI_INT, next, tag2, MPI_COMM_WORLD, &reqs[1]);
MPI_Isend(&rank, 1, MPI_INT, prev, tag2, MPI_COMM_WORLD, &reqs[2]);
MPI_Isend(&rank, 1, MPI_INT, next, tag1, MPI_COMM_WORLD, &reqs[3]);
MPI_Waitall(4, reqs, stats);
printf("Data in rank %i : %i and %i \n", rank, buf[0], buf[1]);
MPI_Finalize();
}
|
C | /**
* Copyright (c) 2014-2019 Timothy Elliott
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "oil_resample.h"
#include <math.h>
#include <stdlib.h>
#include <limits.h>
/**
* When shrinking a 10 million pixel wide scanline down to a single pixel, we
* reach the limits of single-precision floats, and the xscaler will get stuck
* in an infinite loop. Limit input dimensions to one million by one million
* pixels to avoid this issue as well as overflow issues with 32-bit ints.
*/
#define MAX_DIMENSION 1000000
/**
* Bicubic interpolation. 2 base taps on either side.
*/
#define TAPS 4
/**
* Clamp a float between 0 and 1.
*/
static float clampf(float x) {
if (x > 1.0f) {
return 1.0f;
} else if (x < 0.0f) {
return 0.0f;
}
return x;
}
/**
* Convert a float to 8-bit integer.
*/
static int clamp8(float x)
{
return round(clampf(x) * 255.0f);
}
/**
* Map from the discreet dest coordinate pos to a continuous source coordinate.
* The resulting coordinate can range from -0.5 to the maximum of the
* destination image dimension.
*/
static double map(int dim_in, int dim_out, int pos)
{
return (pos + 0.5) * ((double)dim_in / dim_out) - 0.5;
}
/**
* Returns the mapped input position and put the sub-pixel remainder in rest.
*/
static int split_map(int dim_in, int dim_out, int pos, float *rest)
{
double smp;
int smp_i;
smp = map(dim_in, dim_out, pos);
smp_i = smp < 0 ? -1 : smp;
*rest = smp - smp_i;
return smp_i;
}
/**
* Given input and output dimension, calculate the total number of taps that
* will be needed to calculate an output sample.
*
* When we reduce an image by a factor of two, we need to scale our resampling
* function by two as well in order to avoid aliasing.
*/
static int calc_taps(int dim_in, int dim_out)
{
int tmp;
if (dim_out > dim_in) {
return TAPS;
}
tmp = TAPS * dim_in / dim_out;
return tmp - (tmp & 1);
}
/**
* Catmull-Rom interpolator.
*/
static float catrom(float x)
{
if (x>2) {
return 0;
}
if (x<1) {
return (1.5f*x - 2.5f)*x*x + 1;
}
return (((5 - x)*x - 8)*x + 4) / 2;
}
/**
* Given an offset tx, calculate taps coefficients.
*/
static void calc_coeffs(float *coeffs, float tx, int taps)
{
int i;
float tmp, tap_mult, fudge;
tap_mult = (float)taps / TAPS;
tx = 1 - tx - taps / 2;
fudge = 0.0f;
for (i=0; i<taps; i++) {
tmp = catrom(fabsf(tx) / tap_mult) / tap_mult;
fudge += tmp;
coeffs[i] = tmp;
tx += 1;
}
fudge = 1 / fudge;
for (i=0; i<taps; i++) {
coeffs[i] *= fudge;
}
}
/**
* Holds pre-calculated table of linear float to srgb char mappings.
* Initialized via build_l2s_rights();
*/
static float l2s_rights[256];
/**
* Populates l2s_rights.
*/
static void build_l2s_rights()
{
int i;
double srgb_f, tmp, val;
for (i=0; i<255; i++) {
srgb_f = (i + 0.5)/255.0;
if (srgb_f <= 0.0404482362771082) {
val = srgb_f / 12.92;
} else {
tmp = (srgb_f + 0.055)/1.055;
val = pow(tmp, 2.4);
}
l2s_rights[i] = val;
}
l2s_rights[i] = 256.0f;
}
/**
* Maps the given linear RGB float to sRGB integer.
*
* Performs a binary search on l2s_rights.
*/
static int linear_sample_to_srgb(float in)
{
int offs, i;
offs = 0;
for (i=128; i>0; i >>= 1) {
if (in > l2s_rights[offs + i]) {
offs += i;
}
}
return in > l2s_rights[offs] ? offs + 1 : offs;
}
/**
* Resizes a strip of RGBX scanlines to a single scanline.
*/
static void strip_scale_rgbx(float **in, int strip_height, int len,
unsigned char *out, float *coeffs)
{
int i, j;
double sum[3];
for (i=0; i<len; i+=4) {
sum[0] = sum[1] = sum[2] = 0;
for (j=0; j<strip_height; j++) {
sum[0] += coeffs[j] * in[j][i];
sum[1] += coeffs[j] * in[j][i + 1];
sum[2] += coeffs[j] * in[j][i + 2];
}
out[0] = linear_sample_to_srgb(sum[0]);
out[1] = linear_sample_to_srgb(sum[1]);
out[2] = linear_sample_to_srgb(sum[2]);
out[3] = 0;
out += 4;
}
}
/**
* Resizes a strip of RGB scanlines to a single scanline.
*/
static void strip_scale_rgb(float **in, int strip_height, int len,
unsigned char *out, float *coeffs)
{
int i, j;
double sum[3];
for (i=0; i<len; i+=3) {
sum[0] = sum[1] = sum[2] = 0;
for (j=0; j<strip_height; j++) {
sum[0] += coeffs[j] * in[j][i];
sum[1] += coeffs[j] * in[j][i + 1];
sum[2] += coeffs[j] * in[j][i + 2];
}
out[0] = linear_sample_to_srgb(sum[0]);
out[1] = linear_sample_to_srgb(sum[1]);
out[2] = linear_sample_to_srgb(sum[2]);
out += 3;
}
}
/**
* Resizes a strip of greyscale scanlines to a single scanline.
*/
static void strip_scale_g(float **in, int strip_height, int len,
unsigned char *out, float *coeffs)
{
int i, j;
double sum;
for (i=0; i<len; i++) {
sum = 0;
for (j=0; j<strip_height; j++) {
sum += coeffs[j] * in[j][i];
}
out[i] = clamp8(sum);
}
}
/**
* Resizes a strip of greyscale-alpha scanlines to a single scanline.
*/
static void strip_scale_ga(float **in, int strip_height, int len,
unsigned char *out, float *coeffs)
{
int i, j;
double sum[2], alpha;
for (i=0; i<len; i+=2) {
sum[0] = sum[1] = 0;
for (j=0; j<strip_height; j++) {
sum[0] += coeffs[j] * in[j][i];
sum[1] += coeffs[j] * in[j][i + 1];
}
alpha = clampf(sum[1]);
if (alpha != 0) {
sum[0] /= alpha;
}
out[0] = clamp8(sum[0]);
out[1] = round(alpha * 255.0f);
out += 2;
}
}
/**
* Resizes a strip of RGB-alpha scanlines to a single scanline.
*/
static void strip_scale_rgba(float **in, int strip_height, int len,
unsigned char *out, float *coeffs)
{
int i, j;
double sum[4], alpha;
for (i=0; i<len; i+=4) {
sum[0] = sum[1] = sum[2] = sum[3] = 0;
for (j=0; j<strip_height; j++) {
sum[0] += coeffs[j] * in[j][i];
sum[1] += coeffs[j] * in[j][i + 1];
sum[2] += coeffs[j] * in[j][i + 2];
sum[3] += coeffs[j] * in[j][i + 3];
}
alpha = clampf(sum[3]);
if (alpha != 0) {
sum[0] /= alpha;
sum[1] /= alpha;
sum[2] /= alpha;
}
out[0] = linear_sample_to_srgb(sum[0]);
out[1] = linear_sample_to_srgb(sum[1]);
out[2] = linear_sample_to_srgb(sum[2]);
out[3] = round(alpha * 255.0f);
out += 4;
}
}
/**
* Resizes a strip of CMYK scanlines to a single scanline.
*/
static void strip_scale_cmyk(float **in, int strip_height, int len,
unsigned char *out, float *coeffs)
{
int i, j;
double sum[4];
for (i=0; i<len; i+=4) {
sum[0] = sum[1] = sum[2] = sum[3] = 0;
for (j=0; j<strip_height; j++) {
sum[0] += coeffs[j] * in[j][i];
sum[1] += coeffs[j] * in[j][i + 1];
sum[2] += coeffs[j] * in[j][i + 2];
sum[3] += coeffs[j] * in[j][i + 3];
}
out[0] = clamp8(sum[0]);
out[1] = clamp8(sum[1]);
out[2] = clamp8(sum[2]);
out[3] = clamp8(sum[3]);
out += 4;
}
}
/**
* Scale a strip of scanlines. Branches to the correct interpolator using the
* given colorspace.
*/
static void strip_scale(float **in, int strip_height, int len,
unsigned char *out, float *coeffs, float ty, enum oil_colorspace cs)
{
calc_coeffs(coeffs, ty, strip_height);
switch(cs) {
case OIL_CS_G:
strip_scale_g(in, strip_height, len, out, coeffs);
break;
case OIL_CS_GA:
strip_scale_ga(in, strip_height, len, out, coeffs);
break;
case OIL_CS_RGB:
strip_scale_rgb(in, strip_height, len, out, coeffs);
break;
case OIL_CS_RGBX:
strip_scale_rgbx(in, strip_height, len, out, coeffs);
break;
case OIL_CS_RGBA:
strip_scale_rgba(in, strip_height, len, out, coeffs);
break;
case OIL_CS_CMYK:
strip_scale_cmyk(in, strip_height, len, out, coeffs);
break;
case OIL_CS_UNKNOWN:
break;
}
}
/* horizontal scaling */
/**
* Holds pre-calculated mapping of sRGB chars to linear RGB floating point
* values.
*/
static float s2l_map_f[256];
/**
* Populates s2l_map_f.
*/
static void build_s2l()
{
int input;
double in_f, tmp, val;
for (input=0; input<=255; input++) {
in_f = input / 255.0;
if (in_f <= 0.040448236277) {
val = in_f / 12.92;
} else {
tmp = ((in_f + 0.055)/1.055);
val = pow(tmp, 2.4);
}
s2l_map_f[input] = val;
}
}
/**
* Given input & output dimensions, populate a buffer of coefficients and
* border counters.
*
* This method assumes that in_width >= out_width.
*
* It generates 4 * in_width coefficients -- 4 for every input sample.
*
* It generates out_width border counters, these indicate how many input
* samples to process before the next output sample is finished.
*/
static void xscale_calc_coeffs(int in_width, int out_width, float *coeff_buf,
int *border_buf)
{
struct {
float tx;
float fudge;
float *center;
} out_s[4];
int i, j, out_pos, border, taps;
float tap_mult_f, tx;
out_pos = 0;
border = 0;
taps = calc_taps(in_width, out_width);
tap_mult_f = (float)TAPS / taps;
for (i=0; i<4; i++) {
out_s[i].tx = -1 * map(in_width, out_width, i) * tap_mult_f;
out_s[i].fudge = 1.0f;
}
for (i=0; i<in_width; i++) {
for (j=0; j<4; j++) {
tx = fabsf(out_s[j].tx);
coeff_buf[j] = catrom(tx) * tap_mult_f;
out_s[j].fudge -= coeff_buf[j];
if (tx < tap_mult_f) {
out_s[j].center = coeff_buf + j;
}
out_s[j].tx += tap_mult_f;
}
border++;
coeff_buf += 4;
if (out_s[0].tx >= 2.0f) {
out_s[0].center[0] += out_s[0].fudge;
out_s[0] = out_s[1];
out_s[1] = out_s[2];
out_s[2] = out_s[3];
out_s[3].tx = (i + 1 - map(in_width, out_width, out_pos + 4)) * tap_mult_f;
out_s[3].fudge = 1.0f;
border_buf[out_pos] = border;
border = 0;
out_pos++;
}
}
for (i=0; i + out_pos < out_width; i++) {
out_s[i].center[0] += out_s[i].fudge;
border_buf[i + out_pos] = border;
border = 0;
}
}
/**
* Takes an array of 4 floats and shifts them left. The rightmost element is
* set to 0.0.
*/
static void shift_left_f(float *f)
{
f[0] = f[1];
f[1] = f[2];
f[2] = f[3];
f[3] = 0.0f;
}
/**
* Takes a sample value, an array of 4 coefficients & 4 accumulators, and
* adds the product of sample * coeffs[n] to each accumulator.
*/
static void add_sample_to_sum_f(float sample, float *coeffs, float *sum)
{
int i;
for (i=0; i<4; i++) {
sum[i] += sample * coeffs[i];
}
}
/**
* Takes an array of n 4-element source arrays, writes the first element to the
* next n positions of the output address, and shifts the source arrays.
*/
static void dump_out(float *out, float sum[][4], int n)
{
int i;
for (i=0; i<n; i++) {
out[i] = sum[i][0];
shift_left_f(sum[i]);
}
}
static void xscale_down_rgbx(unsigned char *in, int in_width, float *out,
int out_width, float *coeff_buf, int *border_buf)
{
int i, j, k;
float sum[3][4] = {{ 0.0f }};
for (i=0; i<out_width; i++) {
for (j=border_buf[0]; j>0; j--) {
for (k=0; k<3; k++) {
add_sample_to_sum_f(s2l_map_f[in[k]], coeff_buf, sum[k]);
}
in += 4;
coeff_buf += 4;
}
dump_out(out, sum, 3);
out[3] = 0;
out += 4;
border_buf++;
}
}
static void xscale_down_rgb(unsigned char *in, int in_width, float *out,
int out_width, float *coeff_buf, int *border_buf)
{
int i, j, k;
float sum[3][4] = {{ 0.0f }};
for (i=0; i<out_width; i++) {
for (j=border_buf[0]; j>0; j--) {
for (k=0; k<3; k++) {
add_sample_to_sum_f(s2l_map_f[in[k]], coeff_buf, sum[k]);
}
in += 3;
coeff_buf += 4;
}
dump_out(out, sum, 3);
out += 3;
border_buf++;
}
}
static void xscale_down_g(unsigned char *in, int in_width, float *out,
int out_width, float *coeff_buf, int *border_buf)
{
int i, j;
float sum[4] = { 0.0f };
for (i=0; i<out_width; i++) {
for (j=border_buf[0]; j>0; j--) {
add_sample_to_sum_f(in[0] / 255.0f, coeff_buf, sum);
in += 1;
coeff_buf += 4;
}
out[0] = sum[0];
shift_left_f(sum);
out += 1;
border_buf++;
}
}
static void xscale_down_cmyk(unsigned char *in, int in_width, float *out,
int out_width, float *coeff_buf, int *border_buf)
{
int i, j, k;
float sum[4][4] = {{ 0.0f }};
for (i=0; i<out_width; i++) {
for (j=border_buf[0]; j>0; j--) {
for (k=0; k<4; k++) {
add_sample_to_sum_f(in[k] / 255.0f, coeff_buf, sum[k]);
}
in += 4;
coeff_buf += 4;
}
dump_out(out, sum, 4);
out += 4;
border_buf++;
}
}
static void xscale_down_rgba(unsigned char *in, int in_width, float *out,
int out_width, float *coeff_buf, int *border_buf)
{
int i, j, k;
float alpha, sum[4][4] = {{ 0.0f }};
for (i=0; i<out_width; i++) {
for (j=border_buf[0]; j>0; j--) {
alpha = in[3] / 255.0f;
for (k=0; k<3; k++) {
add_sample_to_sum_f(s2l_map_f[in[k]] * alpha, coeff_buf, sum[k]);
}
add_sample_to_sum_f(alpha, coeff_buf, sum[3]);
in += 4;
coeff_buf += 4;
}
dump_out(out, sum, 4);
out += 4;
border_buf++;
}
}
static void xscale_down_ga(unsigned char *in, int in_width, float *out,
int out_width, float *coeff_buf, int *border_buf)
{
int i, j;
float alpha, sum[2][4] = {{ 0.0f }};
for (i=0; i<out_width; i++) {
for (j=border_buf[0]; j>0; j--) {
alpha = in[1] / 255.0f;
add_sample_to_sum_f(in[0] * alpha, coeff_buf, sum[0]);
add_sample_to_sum_f(alpha, coeff_buf, sum[1]);
in += 2;
coeff_buf += 4;
}
dump_out(out, sum, 2);
out += 2;
border_buf++;
}
}
static void oil_xscale_down(unsigned char *in, int width_in, float *out,
int width_out, enum oil_colorspace cs_in, float *coeff_buf,
int *border_buf)
{
switch(cs_in) {
case OIL_CS_RGBX:
xscale_down_rgbx(in, width_in, out, width_out, coeff_buf, border_buf);
break;
case OIL_CS_RGB:
xscale_down_rgb(in, width_in, out, width_out, coeff_buf, border_buf);
break;
case OIL_CS_G:
xscale_down_g(in, width_in, out, width_out, coeff_buf, border_buf);
break;
case OIL_CS_CMYK:
xscale_down_cmyk(in, width_in, out, width_out, coeff_buf, border_buf);
break;
case OIL_CS_RGBA:
xscale_down_rgba(in, width_in, out, width_out, coeff_buf, border_buf);
break;
case OIL_CS_GA:
xscale_down_ga(in, width_in, out, width_out, coeff_buf, border_buf);
break;
case OIL_CS_UNKNOWN:
break;
}
}
static int dim_safe(int i, int max)
{
if (i < 0) {
return 0;
}
if (i > max) {
return max;
}
return i;
}
static void xscale_up_rgbx(unsigned char *in, int width_in, float *out,
int width_out)
{
int i, j, k, smp_i;
float coeffs[4], tx, sum[3];
unsigned char *in_pos;
for (i=0; i<width_out; i++) {
smp_i = split_map(width_in, width_out, i, &tx) - 1;
calc_coeffs(coeffs, tx, 4);
sum[0] = sum[1] = sum[2] = 0.0f;
for (j=0; j<4; j++) {
in_pos = in + dim_safe(smp_i + j, width_in - 1) * 4;
for (k=0; k<3; k++) {
sum[k] += s2l_map_f[in_pos[k]] * coeffs[j];
}
}
for (k=0; k<3; k++) {
out[k] = sum[k];
}
out[3] = 0.0f;
out += 4;
}
}
static void xscale_up_rgb(unsigned char *in, int width_in, float *out,
int width_out)
{
int i, j, k, smp_i;
float coeffs[4], tx, sum[3];
unsigned char *in_pos;
for (i=0; i<width_out; i++) {
smp_i = split_map(width_in, width_out, i, &tx) - 1;
calc_coeffs(coeffs, tx, 4);
sum[0] = sum[1] = sum[2] = 0.0f;
for (j=0; j<4; j++) {
in_pos = in + dim_safe(smp_i + j, width_in - 1) * 3;
for (k=0; k<3; k++) {
sum[k] += s2l_map_f[in_pos[k]] * coeffs[j];
}
}
for (k=0; k<3; k++) {
out[k] = sum[k];
}
out += 3;
}
}
static void xscale_up_cmyk(unsigned char *in, int width_in, float *out,
int width_out)
{
int i, j, k, smp_i;
float coeffs[4], tx, sum[4];
unsigned char *in_pos;
for (i=0; i<width_out; i++) {
smp_i = split_map(width_in, width_out, i, &tx) - 1;
calc_coeffs(coeffs, tx, 4);
sum[0] = sum[1] = sum[2] = sum[3] = 0.0f;
for (j=0; j<4; j++) {
in_pos = in + dim_safe(smp_i + j, width_in - 1) * 4;
for (k=0; k<4; k++) {
sum[k] += in_pos[k]/255.0f * coeffs[j];
}
}
for (k=0; k<4; k++) {
out[k] = sum[k];
}
out += 4;
}
}
static void xscale_up_rgba(unsigned char *in, int width_in, float *out,
int width_out)
{
int i, j, k, smp_i;
float alpha, coeffs[4], tx, sum[4];
unsigned char *in_pos;
for (i=0; i<width_out; i++) {
smp_i = split_map(width_in, width_out, i, &tx) - 1;
calc_coeffs(coeffs, tx, 4);
sum[0] = sum[1] = sum[2] = sum[3] = 0.0f;
for (j=0; j<4; j++) {
in_pos = in + dim_safe(smp_i + j, width_in - 1) * 4;
alpha = in_pos[3] / 255.0f;
for (k=0; k<3; k++) {
sum[k] += alpha * s2l_map_f[in_pos[k]] * coeffs[j];
}
sum[3] += alpha * coeffs[j];
}
for (k=0; k<4; k++) {
out[k] = sum[k];
}
out += 4;
}
}
static void xscale_up_ga(unsigned char *in, int width_in, float *out,
int width_out)
{
int i, j, k, smp_i;
float alpha, coeffs[4], tx, sum[2];
unsigned char *in_pos;
for (i=0; i<width_out; i++) {
smp_i = split_map(width_in, width_out, i, &tx) - 1;
calc_coeffs(coeffs, tx, 4);
sum[0] = sum[1] = 0.0f;
for (j=0; j<4; j++) {
in_pos = in + dim_safe(smp_i + j, width_in - 1) * 2;
alpha = in_pos[1] / 255.0f;
sum[0] += alpha * in_pos[0]/255.0f * coeffs[j];
sum[1] += alpha * coeffs[j];
}
for (k=0; k<2; k++) {
out[k] = sum[k];
}
out += 2;
}
}
static void xscale_up_g(unsigned char *in, int width_in, float *out,
int width_out)
{
int i, j, smp_i;
float coeffs[4], tx, sum;
unsigned char *in_pos;
for (i=0; i<width_out; i++) {
smp_i = split_map(width_in, width_out, i, &tx) - 1;
calc_coeffs(coeffs, tx, 4);
sum = 0.0f;
for (j=0; j<4; j++) {
in_pos = in + dim_safe(smp_i + j, width_in - 1);
sum += in_pos[0]/255.0f * coeffs[j];
}
out[0] = sum;
out += 1;
}
}
static void oil_xscale_up(unsigned char *in, int width_in, float *out,
int width_out, enum oil_colorspace cs_in)
{
switch(cs_in) {
case OIL_CS_RGBX:
xscale_up_rgbx(in, width_in, out, width_out);
break;
case OIL_CS_RGB:
xscale_up_rgb(in, width_in, out, width_out);
break;
case OIL_CS_G:
xscale_up_g(in, width_in, out, width_out);
break;
case OIL_CS_CMYK:
xscale_up_cmyk(in, width_in, out, width_out);
break;
case OIL_CS_RGBA:
xscale_up_rgba(in, width_in, out, width_out);
break;
case OIL_CS_GA:
xscale_up_ga(in, width_in, out, width_out);
break;
case OIL_CS_UNKNOWN:
break;
}
}
/* Global function helpers */
/**
* Given an oil_scale struct, map the next output scanline to a position &
* offset in the input image.
*/
static int yscaler_map_pos(struct oil_scale *ys, float *ty)
{
int target;
target = split_map(ys->in_height, ys->out_height, ys->out_pos, ty);
return target + ys->taps / 2;
}
/**
* Return the index of the buffered scanline to use for the tap at position
* pos.
*/
static int oil_yscaler_safe_idx(struct oil_scale *ys, int pos)
{
int ret, max_height;
max_height = ys->in_height - 1;
ret = ys->target - ys->taps + 1 + pos;
if (ret < 0) {
return 0;
} else if (ret > max_height) {
return max_height;
}
return ret;
}
/* Global functions */
void oil_global_init()
{
build_s2l();
build_l2s_rights();
}
int oil_scale_init(struct oil_scale *os, int in_height, int out_height,
int in_width, int out_width, enum oil_colorspace cs)
{
if (!os || in_height > MAX_DIMENSION || out_height > MAX_DIMENSION ||
in_height < 1 || out_height < 1 ||
in_width > MAX_DIMENSION || out_width > MAX_DIMENSION ||
in_width < 1 || out_width < 1) {
return -1;
}
/* Lazy perform global init */
if (!s2l_map_f[128]) {
oil_global_init();
}
os->in_height = in_height;
os->out_height = out_height;
os->in_width = in_width;
os->out_width = out_width;
os->cs = cs;
os->in_pos = 0;
os->out_pos = 0;
os->taps = calc_taps(in_height, out_height);
os->target = yscaler_map_pos(os, &os->ty);
os->sl_len = out_width * OIL_CMP(cs);
os->coeffs_y = NULL;
os->coeffs_x = NULL;
os->borders = NULL;
os->rb = NULL;
os->virt = NULL;
/**
* If we are horizontally shrinking, then allocate & pre-calculate
* coefficients.
*/
if (out_width <= in_width) {
os->coeffs_x = malloc(128 * in_width);
os->borders = malloc(sizeof(int) * out_width);
if (!os->coeffs_x || !os->borders) {
oil_scale_free(os);
return -2;
}
xscale_calc_coeffs(in_width, out_width, os->coeffs_x,
os->borders);
}
os->rb = malloc((long)os->sl_len * os->taps * sizeof(float));
os->virt = malloc(os->taps * sizeof(float*));
os->coeffs_y = malloc(os->taps * sizeof(float));
if (!os->rb || !os->virt || !os->coeffs_y) {
oil_scale_free(os);
return -2;
}
return 0;
}
void oil_scale_free(struct oil_scale *os)
{
if (!os) {
return;
}
if (os->virt) {
free(os->virt);
os->virt = NULL;
}
if (os->rb) {
free(os->rb);
os->rb = NULL;
}
if (os->coeffs_y) {
free(os->coeffs_y);
os->coeffs_y = NULL;
}
if (os->coeffs_x) {
free(os->coeffs_x);
os->coeffs_x = NULL;
}
if (os->borders) {
free(os->borders);
os->borders = NULL;
}
}
int oil_scale_slots(struct oil_scale *ys)
{
int tmp, safe_target;
tmp = ys->target + 1;
safe_target = tmp > ys->in_height ? ys->in_height : tmp;
return safe_target - ys->in_pos;
}
void oil_scale_in(struct oil_scale *os, unsigned char *in)
{
float *tmp;
tmp = os->rb + (os->in_pos % os->taps) * os->sl_len;
os->in_pos++;
if (os->coeffs_x) {
oil_xscale_down(in, os->in_width, tmp, os->out_width, os->cs,
os->coeffs_x, os->borders);
} else {
oil_xscale_up(in, os->in_width, tmp, os->out_width, os->cs);
}
}
void oil_scale_out(struct oil_scale *ys, unsigned char *out)
{
int i, idx;
if (!ys || !out) {
return;
}
for (i=0; i<ys->taps; i++) {
idx = oil_yscaler_safe_idx(ys, i);
ys->virt[i] = ys->rb + (idx % ys->taps) * ys->sl_len;
}
strip_scale(ys->virt, ys->taps, ys->sl_len, out, ys->coeffs_y, ys->ty,
ys->cs);
ys->out_pos++;
ys->target = yscaler_map_pos(ys, &ys->ty);
}
int oil_fix_ratio(int src_width, int src_height, int *out_width,
int *out_height)
{
double width_ratio, height_ratio, tmp;
int *adjust_dim;
if (src_width < 1 || src_height < 1 || *out_width < 1 || *out_height < 1) {
return -1; // bad argument
}
width_ratio = *out_width / (double)src_width;
height_ratio = *out_height / (double)src_height;
if (width_ratio < height_ratio) {
tmp = round(width_ratio * src_height);
adjust_dim = out_height;
} else {
tmp = round(height_ratio * src_width);
adjust_dim = out_width;
}
if (tmp > INT_MAX) {
return -2; // adjusted dimension out of range
}
*adjust_dim = tmp ? tmp : 1;
return 0;
}
|
C | #include "filesys/inode.h"
#include <list.h>
#include <debug.h>
#include <round.h>
#include <string.h>
#include "filesys/filesys.h"
#include "filesys/free-map.h"
#include "threads/malloc.h"
#include "threads/synch.h"
/* Identifies an inode. */
#define INODE_MAGIC 0x494e4f44
/* Number of direct blocks in inode_disk. */
#define DIRECT_BLOCKS 122
/* Number of block_sector_t entries in block */
#define RECORDS_IN_BLOCK (BLOCK_SECTOR_SIZE / sizeof(block_sector_t))
/* On-disk inode.
Must be exactly BLOCK_SECTOR_SIZE bytes long. */
struct inode_disk
{
block_sector_t end; /* Last + 1 data sector. */
off_t length; /* File size in bytes. */
block_sector_t direct[DIRECT_BLOCKS];
block_sector_t indirect;
block_sector_t doubly_indirect;
bool is_dir;
unsigned magic; /* Magic number. */
};
/* Returns the number of sectors to allocate for an inode SIZE
bytes long. */
static inline size_t
bytes_to_sectors (off_t size)
{
return DIV_ROUND_UP (size, BLOCK_SECTOR_SIZE);
}
struct lock inodes_lock;
/* In-memory inode. */
struct inode
{
struct list_elem elem; /* Element in inode list. */
block_sector_t sector; /* Sector number of disk location. */
int open_cnt; /* Number of openers. */
bool removed; /* True if deleted, false otherwise. */
int deny_write_cnt; /* 0: writes ok, >0: deny writes. */
struct lock lock;
struct inode_disk data; /* Inode content. */
};
static block_sector_t get_disk_sector (const struct inode_disk *disk_inode, block_sector_t file_sector) {
block_sector_t result = block_size (fs_device);
if (file_sector < DIRECT_BLOCKS) {
return disk_inode->direct[file_sector];
} else if (file_sector < DIRECT_BLOCKS + RECORDS_IN_BLOCK) {
block_sector_t indirect[RECORDS_IN_BLOCK];
cache_read (disk_inode->indirect, 0, 0, BLOCK_SECTOR_SIZE, indirect);
return indirect[file_sector - DIRECT_BLOCKS];
} else if (file_sector < DIRECT_BLOCKS + RECORDS_IN_BLOCK * RECORDS_IN_BLOCK) { /* Doubly Indirect */
block_sector_t dindirect[RECORDS_IN_BLOCK];
cache_read (disk_inode->doubly_indirect, 0, 0, BLOCK_SECTOR_SIZE, dindirect);
block_sector_t index = file_sector - DIRECT_BLOCKS - RECORDS_IN_BLOCK;
block_sector_t outer_index = index / RECORDS_IN_BLOCK;
cache_read (dindirect[outer_index], 0, 0, BLOCK_SECTOR_SIZE, dindirect);
block_sector_t inner_index = index % RECORDS_IN_BLOCK;
return dindirect[inner_index];
}
ASSERT(result != block_size (fs_device));
return result;
}
/* Returns the block device sector that contains byte offset POS
within INODE.
Returns -1 if INODE does not contain data for a byte at offset
POS. */
static block_sector_t
byte_to_sector (const struct inode *inode, off_t pos)
{
ASSERT (inode != NULL);
block_sector_t file_sector = pos / BLOCK_SECTOR_SIZE;
block_sector_t sector = get_disk_sector (&inode->data, file_sector);
return sector;
}
/* List of open inodes, so that opening a single inode twice
returns the same `struct inode'. */
static struct list open_inodes;
/* Initializes the inode module. */
void
inode_init (void)
{
list_init (&open_inodes);
lock_init (&inodes_lock);
}
static void inode_destroy (struct inode_disk *disk_inode) {
block_sector_t index = 0;
block_sector_t *records = NULL;
while (index < DIRECT_BLOCKS && index < disk_inode->end) {
free_map_release (disk_inode->direct[index], 1);
index++;
}
if (index == disk_inode->end) return;
index -= DIRECT_BLOCKS;
records = malloc (BLOCK_SECTOR_SIZE);
cache_read (disk_inode->indirect, 0, 0, BLOCK_SECTOR_SIZE, records);
while (index < RECORDS_IN_BLOCK && index + DIRECT_BLOCKS < disk_inode->end) {
free_map_release (records[index], 1);
index++;
}
free (records);
free_map_release (disk_inode->indirect, 1);
if (index + DIRECT_BLOCKS == disk_inode->end) return;
index -= RECORDS_IN_BLOCK;
records = malloc (BLOCK_SECTOR_SIZE);
cache_read (disk_inode->doubly_indirect, 0, 0, BLOCK_SECTOR_SIZE, records);
block_sector_t outer_index = index / RECORDS_IN_BLOCK;
block_sector_t inner_index = index % RECORDS_IN_BLOCK;
while (outer_index < RECORDS_IN_BLOCK) {
block_sector_t inner_records[RECORDS_IN_BLOCK];
cache_read (records[outer_index], 0, 0, BLOCK_SECTOR_SIZE, inner_records);
while (inner_index < RECORDS_IN_BLOCK
&& inner_index + (outer_index + 1) * RECORDS_IN_BLOCK + DIRECT_BLOCKS < disk_inode->end) {
free_map_release (inner_records[inner_index], 1);
inner_index++;
}
free_map_release (records[outer_index], 1);
if (inner_index + (outer_index + 1) * RECORDS_IN_BLOCK + DIRECT_BLOCKS == disk_inode->end) {
free_map_release (disk_inode->doubly_indirect, 1);
free (records);
return;
}
outer_index++;
inner_index %= RECORDS_IN_BLOCK;
}
free_map_release (disk_inode->doubly_indirect, 1);
free (records);
}
static bool inode_grow (struct inode_disk *disk_inode, size_t sectors) {
static char zeros[BLOCK_SECTOR_SIZE];
block_sector_t index = disk_inode->end;
block_sector_t *records = NULL;
while (index < DIRECT_BLOCKS && sectors > 0) {
if (!free_map_allocate (1, &disk_inode->direct[index]))
return false;
cache_write (disk_inode->direct[index], 0, 0, BLOCK_SECTOR_SIZE, zeros);
disk_inode->end++;
index++;
sectors--;
}
if (sectors == 0) return true;
if (index == DIRECT_BLOCKS) {
if (!free_map_allocate(1, &disk_inode->indirect)) return false;
}
index -= DIRECT_BLOCKS;
records = malloc (BLOCK_SECTOR_SIZE);
cache_read (disk_inode->indirect, 0, 0, BLOCK_SECTOR_SIZE, records);
while (index < RECORDS_IN_BLOCK && sectors > 0) {
if (!free_map_allocate (1, &records[index])) {
if (index == 0) free_map_release (disk_inode->indirect, 1);
else cache_write (disk_inode->indirect, 0, 0, BLOCK_SECTOR_SIZE, records);
return false;
}
cache_write (records[index], 0, 0, BLOCK_SECTOR_SIZE, zeros);
disk_inode->end++;
index++;
sectors--;
}
cache_write (disk_inode->indirect, 0, 0, BLOCK_SECTOR_SIZE, records);
free (records);
if (sectors == 0) return true;
if (index == RECORDS_IN_BLOCK) {
if (!free_map_allocate(1, &disk_inode->doubly_indirect)) return false;
}
index -= RECORDS_IN_BLOCK;
records = malloc (BLOCK_SECTOR_SIZE);
cache_read (disk_inode->doubly_indirect, 0, 0, BLOCK_SECTOR_SIZE, records);
block_sector_t outer_index = index / RECORDS_IN_BLOCK;
block_sector_t inner_index = index % RECORDS_IN_BLOCK;
while (outer_index < RECORDS_IN_BLOCK && sectors > 0) {
if (inner_index == 0 && !free_map_allocate (1, &records[outer_index])) {
if (outer_index == 0) free_map_release (disk_inode->doubly_indirect, 1);
else cache_write (disk_inode->doubly_indirect, 0, 0, BLOCK_SECTOR_SIZE, records);
return false;
}
block_sector_t inner_records[RECORDS_IN_BLOCK];
cache_read (records[outer_index], 0, 0, BLOCK_SECTOR_SIZE, inner_records);
while (inner_index < RECORDS_IN_BLOCK && sectors > 0) {
if (!free_map_allocate (1, &inner_records[inner_index])) {
if (inner_index == 0) {
free_map_release (records[outer_index], 1);
if (outer_index == 0) free_map_release (disk_inode->doubly_indirect, 1);
else cache_write (disk_inode->doubly_indirect, 0, 0, BLOCK_SECTOR_SIZE, records);
}
else cache_write (records[outer_index], 0, 0, BLOCK_SECTOR_SIZE, inner_records);
return false;
}
cache_write (inner_records[inner_index], 0, 0, BLOCK_SECTOR_SIZE, zeros);
disk_inode->end++;
inner_index++;
sectors--;
}
cache_write (records[outer_index], 0, 0, BLOCK_SECTOR_SIZE, inner_records);
outer_index++;
inner_index %= RECORDS_IN_BLOCK;
}
cache_write (disk_inode->doubly_indirect, 0, 0, BLOCK_SECTOR_SIZE, records);
free (records);
if (sectors == 0) return true;
return false;
}
/* Initializes an inode with LENGTH bytes of data and
writes the new inode to sector SECTOR on the file system
device.
Returns true if successful.
Returns false if memory or disk allocation fails. */
bool
inode_create (block_sector_t sector, off_t length, bool is_dir)
{
struct inode_disk *disk_inode = NULL;
bool success = false;
ASSERT (length >= 0);
/* If this assertion fails, the inode structure is not exactly
one sector in size, and you should fix that. */
ASSERT (sizeof *disk_inode == BLOCK_SECTOR_SIZE);
disk_inode = calloc (1, sizeof *disk_inode);
if (disk_inode != NULL)
{
size_t sectors = bytes_to_sectors (length);
disk_inode->end = 0;
disk_inode->length = length;
disk_inode->magic = INODE_MAGIC;
disk_inode->is_dir = is_dir;
if (!inode_grow(disk_inode, sectors)) {
inode_destroy (disk_inode);
} else {
cache_write (sector, 0, 0, BLOCK_SECTOR_SIZE, disk_inode);
success = true;
}
free (disk_inode);
}
return success;
}
/* Reads an inode from SECTOR
and returns a `struct inode' that contains it.
Returns a null pointer if memory allocation fails. */
struct inode *
inode_open (block_sector_t sector)
{
struct list_elem *e;
struct inode *inode;
lock_acquire (&inodes_lock);
/* Check whether this inode is already open. */
for (e = list_begin (&open_inodes); e != list_end (&open_inodes);
e = list_next (e))
{
inode = list_entry (e, struct inode, elem);
if (inode->sector == sector)
{
inode_reopen (inode);
lock_release (&inodes_lock);
return inode;
}
}
/* Allocate memory. */
inode = malloc (sizeof *inode);
if (inode == NULL) {
lock_release (&inodes_lock);
return NULL;
}
/* Initialize. */
list_push_front (&open_inodes, &inode->elem);
inode->sector = sector;
inode->open_cnt = 1;
inode->deny_write_cnt = 0;
inode->removed = false;
lock_init (&inode->lock);
cache_read (inode->sector, 0, 0, BLOCK_SECTOR_SIZE, &inode->data);
lock_release (&inodes_lock);
return inode;
}
/* Reopens and returns INODE. */
struct inode *
inode_reopen (struct inode *inode)
{
if (inode != NULL) {
lock_acquire(&inode->lock);
inode->open_cnt++;
lock_release(&inode->lock);
}
return inode;
}
/* Returns INODE's inode number. */
block_sector_t
inode_get_inumber (const struct inode *inode)
{
return inode->sector;
}
/* Closes INODE and writes it to disk.
If this was the last reference to INODE, frees its memory.
If INODE was also a removed inode, frees its blocks. */
void
inode_close (struct inode *inode)
{
/* Ignore null pointer. */
if (inode == NULL)
return;
lock_acquire (&inodes_lock);
/* Release resources if this was the last opener. */
if (--inode->open_cnt == 0)
{
/* Remove from inode list and release lock. */
list_remove (&inode->elem);
lock_release (&inodes_lock);
/* Deallocate blocks if removed. */
if (inode->removed)
{
free_map_release (inode->sector, 1);
inode_destroy (&inode->data);
}
free (inode);
} else
lock_release (&inodes_lock);
}
/* Marks INODE to be deleted when it is closed by the last caller who
has it open. */
void
inode_remove (struct inode *inode)
{
ASSERT (inode != NULL);
inode->removed = true;
}
/* Reads SIZE bytes from INODE into BUFFER, starting at position OFFSET.
Returns the number of bytes actually read, which may be less
than SIZE if an error occurs or end of file is reached. */
off_t
inode_read_at (struct inode *inode, void *buffer_, off_t size, off_t offset)
{
uint8_t *buffer = buffer_;
off_t bytes_read = 0;
lock_acquire (&inode->lock);
while (size > 0)
{
/* Disk sector to read, starting byte offset within sector. */
block_sector_t sector_idx = byte_to_sector (inode, offset);
int sector_ofs = offset % BLOCK_SECTOR_SIZE;
/* Bytes left in inode, bytes left in sector, lesser of the two. */
off_t inode_left = inode_length (inode) - offset;
int sector_left = BLOCK_SECTOR_SIZE - sector_ofs;
int min_left = inode_left < sector_left ? inode_left : sector_left;
/* Number of bytes to actually copy out of this sector. */
int chunk_size = size < min_left ? size : min_left;
if (chunk_size <= 0)
break;
cache_read (sector_idx, sector_ofs, bytes_read, chunk_size, buffer);
/* Advance. */
size -= chunk_size;
offset += chunk_size;
bytes_read += chunk_size;
}
lock_release (&inode->lock);
return bytes_read;
}
/* Writes SIZE bytes from BUFFER into INODE, starting at OFFSET.
Returns the number of bytes actually written, which may be
less than SIZE if end of file is reached or an error occurs.
(Normally a write at end of file would extend the inode, but
growth is not yet implemented.) */
off_t
inode_write_at (struct inode *inode, const void *buffer_, off_t size,
off_t offset)
{
const uint8_t *buffer = buffer_;
off_t bytes_written = 0;
lock_acquire (&inode->lock);
if (inode->deny_write_cnt) {
lock_release (&inode->lock);
return 0;
}
off_t new_size = offset + size;
if (new_size > inode->data.length) {
size_t needed_sectors = DIV_ROUND_UP(new_size, BLOCK_SECTOR_SIZE) - inode->data.end;
if (inode_grow(&inode->data, needed_sectors)) {
inode->data.length = new_size;
cache_write (inode->sector, 0, 0, BLOCK_SECTOR_SIZE, &inode->data);
}
}
while (size > 0)
{
/* Sector to write, starting byte offset within sector. */
block_sector_t sector_idx = byte_to_sector (inode, offset);
int sector_ofs = offset % BLOCK_SECTOR_SIZE;
/* Bytes left in inode, bytes left in sector, lesser of the two. */
off_t inode_left = inode_length (inode) - offset;
int sector_left = BLOCK_SECTOR_SIZE - sector_ofs;
int min_left = inode_left < sector_left ? inode_left : sector_left;
/* Number of bytes to actually write into this sector. */
int chunk_size = size < min_left ? size : min_left;
if (chunk_size <= 0)
break;
cache_write (sector_idx, sector_ofs, bytes_written, chunk_size, buffer);
/* Advance. */
size -= chunk_size;
offset += chunk_size;
bytes_written += chunk_size;
}
lock_release (&inode->lock);
return bytes_written;
}
/* Disables writes to INODE.
May be called at most once per inode opener. */
void
inode_deny_write (struct inode *inode)
{
lock_acquire (&inode->lock);
inode->deny_write_cnt++;
lock_release (&inode->lock);
ASSERT (inode->deny_write_cnt <= inode->open_cnt);
}
/* Re-enables writes to INODE.
Must be called once by each inode opener who has called
inode_deny_write() on the inode, before closing the inode. */
void
inode_allow_write (struct inode *inode)
{
ASSERT (inode->deny_write_cnt > 0);
ASSERT (inode->deny_write_cnt <= inode->open_cnt);
lock_acquire (&inode->lock);
inode->deny_write_cnt--;
lock_release (&inode->lock);
}
/* Returns the length, in bytes, of INODE's data. */
off_t
inode_length (const struct inode *inode)
{
off_t length = inode->data.length;
return length;
}
/* Returns if the inode is directory or not. */
bool
inode_is_dir (const struct inode *inode)
{
if (inode == NULL)
return false;
return inode->data.is_dir;
} |
C | #include <stdio.h>
#include <stdlib.h>
/**
*main - print out all the arguments it recieves
*@argc: argument count
*@argv: argument array type char
*Return: 0 multiple or -1 if less than 2 arguments
*/
int main(int argc, char **argv)
{
int i, multiple = 1;
if (argc <= 2)
{
printf("Error\n");
return (-1);
}
for (i = 1; i < argc; i++)
{
multiple *= atoi(argv[i]);
}
printf("%d\n", multiple);
return (0);
}
|
C | #include<stdio.h>
void swap(int *a, int *b)
{
// simple function to swap numbers
int temp = *a;
*a = *b;
*b = temp;
}
void printArray(int arr[], int size)
{
// simple function to print an array
for (int i=0; i < size; i++) printf("%d ", arr[i]);
printf("\n");
}
void insertion_sort(int arr[], int n) {
for (int i = 1; i < n; i++) {
// hold first position in temp
// use the postion before it as starting iterator
int tmp = arr[i], j = i-1;
// iterating from last to first
// check whether the starting number is smaller or not
// shift till the position is found
while (tmp < arr[j] && j >= 0) {
arr[j + 1] = arr[j];
--j;
}
// place the number at its sorted position
arr[j + 1] = tmp;
}
}
int main(void)
{
// take input from user for numbers
int arr[1000];
int n;
printf("Enter the number of elements: (MAX 1000) \n");
scanf("%d",&n);
// checking if the number is beyond the limit or less than ZERO
while(n>1000 || n<= 0){
printf("Please enter the number b/w 0 & 1000: \n");
scanf("%d",&n);
}
// Start taking input and store it in arr
printf("Start entering number:\n");
for (int i =0; i<n; i++){
scanf("%d", &arr[i]);
}
printf("Array: \n");
printArray(arr, n);
// calling function
insertion_sort(arr, n);
printf("Sorted Array: \n");
printArray(arr, n);
return 0;
} |
C | #include <unistd.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <poll.h>
#include <fcntl.h>
#include <math.h>
#include <time.h>
#include <pthread.h>
#include <ctype.h>
#include <mraa.h>
#include <mraa/aio.h>
int period = 1;
int scale = 'F';
int logfd = -1;
const int B = 4275; // B value of the thermistor
const int R0 = 100000; // R0 = 100k
const int bufferSize = 32;
mraa_aio_context temperature_Pin;
mraa_gpio_context button_Pin;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int input_found = 0;
int button_State = 0;
int report_opt = 1;
int on_opt = 1;
int prs = 0;
void press();
void check_arg(int argc, char* argv[]);
void* run_thread();
void clear(char* array, int size);
int main(int argc, char* argv[]){
check_arg(argc, argv);
temperature_Pin = mraa_aio_init(1);
button_Pin = mraa_gpio_init(62);
float current_Temp;
time_t readtime = time(NULL);
struct tm* readtimePTR;
char buffer[bufferSize];
int buffCount = 0;
mraa_gpio_isr(button_Pin, MRAA_GPIO_EDGE_RISING, &press, NULL);
char input_buff[2048];
int input_Count = 0;
pthread_t* tid = (pthread_t*)malloc(sizeof(pthread_t));
if(pthread_create(&tid[0], NULL, run_thread, NULL) < 0){
fprintf(stderr, "Error: Thread create failure\n");
exit(1);
}
while(1){
current_Temp = mraa_aio_read(temperature_Pin);
mraa_gpio_dir(button_Pin, MRAA_GPIO_IN);
readtime = time(NULL);
readtimePTR = localtime(&readtime);
float R = 1023.0/current_Temp-1.0;
R = R0*R;
float temperature = 1.0/(log(R/R0)/B+1/298.15)-273.15; // convert to temperature via datasheet
if (scale == 'F'){
temperature = temperature*(1.8) + 32; //convert to F
}
if ((button_State == 1) | (on_opt == 0)){
buffCount = sprintf(buffer, "%.2d:%.2d:%.2d SHUTDOWN\n", readtimePTR->tm_hour, readtimePTR->tm_min, readtimePTR->tm_sec);
write(1, buffer, buffCount);
if (logfd >= 0){
write(logfd, buffer, buffCount);
}
exit(0);
}
if (report_opt == 1){
buffCount = sprintf(buffer, "%.2d:%.2d:%.2d %0.1f\n", readtimePTR->tm_hour, readtimePTR->tm_min, readtimePTR->tm_sec, temperature);
write(1, buffer, buffCount);
if (logfd >= 0){
write(logfd, buffer, buffCount);
}
}
char tbuf[16];
clear(tbuf, 16);
int index = 0;
int tbuf_pos = 0;
if(prs > 0){
pthread_mutex_lock(&lock);
input_Count = read(0, input_buff, 2048);
index = 0;
tbuf_pos = 0;
pthread_mutex_unlock(&lock);
while(index < input_Count){
tbuf[tbuf_pos] = input_buff[index];
if((tbuf[tbuf_pos] == '=')|(tbuf[tbuf_pos] == '\n')){
if (strcmp(tbuf, "SCALE=") == 0){
tbuf_pos++;
index++;
tbuf[tbuf_pos] = input_buff[index];
tbuf_pos++;
index++;
tbuf[tbuf_pos] = input_buff[index];
if (strcmp(tbuf, "SCALE=F\n") == 0){
scale = 'F';
write(1, "SCALE=F\n", 8);
if (logfd >= 0){
write(logfd, "SCALE=F\n", 8);
}
}
else if (strcmp(tbuf, "SCALE=C\n") == 0){
scale = 'C';
write(1, "SCALE=C\n", 8);
if (logfd >= 0){
write(logfd, "SCALE=C\n", 8);
}
}
}
else if (strcmp(tbuf, "PERIOD=") == 0){
char temp_num[2] = {' ',' '};
int temp_num_indx = 0;
while(tbuf[tbuf_pos] != '\n'){
tbuf[tbuf_pos] = input_buff[index];
if (isdigit(tbuf[tbuf_pos]) > 0)
{
temp_num[temp_num_indx] = tbuf[tbuf_pos];
temp_num_indx++;
}
tbuf_pos++;
index++;
}
tbuf_pos++;
if (temp_num_indx >= 1){
write(1, "PERIOD=", 7);
write(1, temp_num, temp_num_indx);
write(1, "\n", 1);
if (logfd >= 0){
write(logfd, "PERIOD=", 7);
write(logfd, temp_num, temp_num_indx);
write(logfd, "\n", 1);
}
period = atoi(temp_num);
}
else{
write(1, "Incorrect Command\n", 18);
clear(tbuf, 16);
}
}
else if (strcmp(tbuf, "STOP\n") == 0){
report_opt = 0;
write(1, "STOP\n", 5);
if (logfd >= 0){
write(logfd, "STOP\n", 5);
}
}
else if (strcmp(tbuf, "START\n") == 0){
report_opt = 1;
write(1, "START\n", 6);
if (logfd >= 0){
write(logfd, "START\n", 6);
}
}
else if (strcmp(tbuf, "OFF\n") == 0){
on_opt = 0;
write(1, "OFF\n", 4);
if (logfd >= 0){
write(logfd, "OFF\n", 4);
}
break;
}
else{
write(1, "Incorrect Command\n", 18);
clear(tbuf, 16);
}
tbuf_pos = -1;
}
}
pthread_mutex_lock(&lock);
input_found = 0;
prs = 0;
clear(tbuf, 16);
pthread_mutex_unlock(&lock);
}
sleep(period);
}
}
void* run_thread(){
struct pollfd pfd[1];
pfd[0].fd = 0;
pfd[0].events = POLLIN;
while(1){
while(!input_found){
pthread_mutex_lock(&lock);
prs = poll(pfd, 2, -1);
if(prs > 0){
input_found = 1;
}
pthread_mutex_unlock(&lock);
}
}
return NULL;
}
void press(){
button_State = 1;
}
void clear(char* array, int size){
int i = 0;
for (i=0; i < size; i++){
array[i] = 0;
}
}
void check_arg(int argc, char* argv[]){
int opt;
int option_index=0;
char *string = "a::b:c:d";
static struct option long_options[] = {
{"period", required_argument, NULL,'p'},
{"scale", required_argument, NULL,'s'},
{"log", required_argument, NULL,'l'},
{0,0,0,0},
};
int is_right = 0;
while((opt=getopt_long(argc,argv,string,long_options,&option_index))!= -1){
/*
printf("opt = %c\t\t", opt);
printf("optarg = %s\t\t",optarg);
printf("optind = %d\t\t",optind);
printf("argv[optind] =%s\t\t", argv[optind-1]);
printf("option_index = %d\n",option_index);*/ //for debug use
if(opt == 'p'){
period = atoi(optarg);
}
else if(opt == 'l'){
logfd = open(optarg, O_RDWR|O_CREAT, 0666);
if (logfd < 0){
fprintf(stderr, "Error creating file\n");
exit(1);
}
}
else if(opt == 's'){
if ((optarg[0] != 'F') & (optarg[0] != 'C')){
fprintf(stderr, "Unrecognized Scale, correct usage includes: --scale=[C|F]\n");
exit(1);
}
scale = optarg[0];
}
else{
is_right++;
}
}
if(is_right > 0){
fprintf(stderr,"Invalid Arugments, correct usage: ./lab4b [--period=#], [--scale=] [--log=filename]\n");
exit(1);
}
}
|
C | //Read formatted time (in HH:MM:SS) through scanf in C program
#include <stdio.h>
void main()
{
int h, m, s;
printf("\n Enter Time (in HH:MM:SS)");
scanf("%02d:%02d:%02d", &h, &m, &s);
printf("Entered time is %02d:%02d:%02d\n", h, m, s);
} |
C | #include "ei_decode.h"
#include "process_manager.h"
/**
* Decode the arguments into a new_process
*
* @params
* {Cmd::string(), [Option]}
* Option = {env, Strings} | {cd, Dir} | {do_before, Cmd} | {do_after, Cmd} | {nice, int()}
**/
const char* babysitter_action_strings[] = {"run", "exec", "list", "status", "kill", NULL};
enum BabysitterActionT ei_decode_command_call_into_process(char *buf, process_t **ptr)
{
int err_code = -1;
// Instantiate a new process
if (pm_new_process(ptr)) return err_code--;
int arity, index, version, size;
int i = 0, tuple_size, type;
long transId;
// Reset the index, so that ei functions can decode terms from the
// beginning of the buffer
index = 0;
/* Ensure that we are receiving the binary term by reading and
* stripping the version byte */
if (ei_decode_version(buf, &index, &version) < 0) return err_code--;
// Decode the tuple header and make sure that the arity is 2
// as the tuple spec requires it to contain a tuple: {TransId, {Cmd::atom(), Arg1, Arg2, ...}}
if (ei_decode_tuple_header(buf, &index, &arity) < 0) return err_code--;; // decode the tuple and capture the arity
if (ei_decode_long(buf, &index, &transId) < 0) return err_code--;; // Get the transId
if ((ei_decode_tuple_header(buf, &index, &arity)) < 0) return err_code--;;
process_t *process = *ptr;
process->transId = transId;
// Get the outer tuple
// The first command is an atom
// {Cmd::atom(), Command::string(), Options::list()}
ei_get_type(buf, &index, &type, &size);
char *action = NULL; if ((action = (char*) calloc(sizeof(char*), size + 1)) == NULL) return err_code--;
// Get the command
if (ei_decode_atom(buf, &index, action)) return err_code--;
int ret = -1;
if ((int)(ret = (enum BabysitterActionT)string_index(babysitter_action_strings, action)) < 0) return err_code--;
switch(ret) {
case BS_STATUS:
case BS_KILL: {
ei_get_type(buf, &index, &type, &size);
long lval;
ei_decode_long(buf, &index, &lval);
process->pid = (pid_t)lval;
}
break;
case BS_LIST:
break;
default:
// Get the next string
ei_get_type(buf, &index, &type, &size);
char *command = NULL; if ((command = (char*) calloc(sizeof(char*), size + 1)) == NULL) return err_code--;
// Get the command
if (ei_decode_string(buf, &index, command) < 0) return err_code--;
pm_malloc_and_set_attribute(&process->command, command);
// The second element of the tuple is a list of options
if (ei_decode_list_header(buf, &index, &size) < 0) return err_code--;
enum OptionT { CD, ENV, NICE, DO_BEFORE, DO_AFTER, T_STDOUT, T_STDERR } opt;
const char* options[] = {"cd", "env", "nice", "do_before", "do_after", "stdout", "stderr", NULL};
for (i = 0; i < size; i++) {
// Decode the tuple of the form {atom, string()|int()};
if (ei_decode_tuple_header(buf, &index, &tuple_size) < 0) return err_code--;
if ((int)(opt = (enum OptionT)decode_atom_index(buf, &index, options)) < 0) return err_code--;
switch (opt) {
case CD:
case DO_BEFORE:
case DO_AFTER:
case T_STDOUT:
case T_STDERR:
case ENV: {
int size;
ei_get_type(buf, &index, &type, &size);
char *value = NULL;
if ((value = (char*) calloc(sizeof(char*), size + 1)) == NULL) return err_code--;
if (ei_decode_string(buf, &index, value) < 0) {
fprintf(stderr, "ei_decode_string error: %d\n", errno);
free(value);
return err_code--;
}
if (strlen(value) > 0) {
if (opt == CD)
pm_malloc_and_set_attribute(&process->cd, value);
else if (opt == ENV)
pm_add_env(&process, value);
else if (opt == DO_BEFORE)
pm_malloc_and_set_attribute(&process->before, value);
else if (opt == DO_AFTER)
pm_malloc_and_set_attribute(&process->after, value);
else if (opt == T_STDOUT)
pm_malloc_and_set_attribute(&process->stdout, value);
else if (opt == T_STDERR)
pm_malloc_and_set_attribute(&process->stderr, value);
}
free(value);
}
break;
case NICE: {
long lval;
ei_decode_long(buf, &index, &lval);
process->nice = lval;
}
break;
default:
return err_code--;
break;
}
}
break;
}
*ptr = process;
return ret;
}
/**
* Basic read off the buffer. Extract the length from the header
**/
int read_cmd(int fd, unsigned char **bufr, int *size)
{
unsigned char *buf = *bufr;
int header_len = 2;
if ((read_exact(fd, buf, header_len)) != header_len) return -1;
int len = 0;
int i = 0;
for(i = 0; i < header_len; i++) len |= buf[i] << (8*(header_len-i-1));
if (len > *size) {
unsigned char* tmp = (unsigned char *) realloc(buf, len);
if (tmp == NULL)
return -1;
else
buf = tmp;
*size = len;
}
int ret = read_exact(fd, buf, len);
*bufr = buf;
return ret;
}
int ei_read(int fd, unsigned char** bufr)
{
int size = MAX_BUFFER_SZ;
unsigned char *buf;
if ((buf = (unsigned char *) malloc(sizeof(unsigned char) * size)) == NULL) {
fprintf(stderr, "Could not create an erlang buffer: %s\n", strerror(errno));
return -1;
}
int ret = read_cmd(fd, &buf, &size);
if (ret > 0) *bufr = buf;
return ret;
}
/**
* Data marshalling functions
**/
int encode_header(ei_x_buff *result, int transId, int next_tuple_len)
{
if (ei_x_new_with_version(result)) return -1;
if (ei_x_encode_tuple_header(result, 2)) return -1;
if (ei_x_encode_long(result, transId)) return -2;
if (ei_x_encode_tuple_header(result, next_tuple_len)) return -2;
return 0;
}
/**
* ei_write_atom
* @params
* fd - File descriptor to write to
* transId - TransID
* first - the atom to send
* fmt, ... - The string to write out
* @returns
* {transId, {Atom::atom(), Result::string()}}
**/
int ei_write_atom(int fd, int transId, const char* first, const char* fmt, ...)
{
ei_x_buff result;
if (encode_header(&result, transId, 2)) return -1;
if (ei_x_encode_atom(&result, first) < 0) return -3;
// Encode string
char str[MAX_BUFFER_SZ];
va_list vargs;
va_start(vargs, fmt);
vsnprintf(str, MAX_BUFFER_SZ, fmt, vargs);
va_end(vargs);
if (ei_x_encode_string_len(&result, str, strlen(str))) return -4;
write_cmd(fd, &result);
ei_x_free(&result);
return 0;
}
int ei_pid_ok(int fd, int transId, pid_t pid)
{
ei_x_buff result;
if (encode_header(&result, transId, 2)) return -1;
if (ei_x_encode_atom(&result, "ok") ) return -3;
// Encode pid
if (ei_x_encode_long(&result, (int)pid)) return -5;
if (write_cmd(fd, &result) < 0) return -5;
ei_x_free(&result);
return 0;
}
/**
* Send a list of pids
* {transId, [Pid::integer()]}
**/
int ei_send_pid_list(int fd, int transId, process_struct *hd, int size)
{
ei_x_buff result;
process_struct *ps;
if (encode_header(&result, transId, 2)) return -1;
if (ei_x_encode_atom(&result, "ok") ) return -2;
if (ei_x_encode_list_header(&result, size)) return -3;
for( ps = hd; ps != NULL; ps = ps->hh.next ) ei_x_encode_long(&result, ps->pid);
if (ei_x_encode_empty_list(&result)) return -4;
if (write_cmd(fd, &result) < 0) return -5;
ei_x_free(&result);
return 0;
}
int ei_pid_status_header(int fd, int transId, pid_t pid, int status, const char* header)
{
ei_x_buff result;
if (encode_header(&result, transId, 3)) return -1;
if (ei_x_encode_atom(&result, header) ) return -4;
// Encode pid
if (ei_x_encode_long(&result, (int)pid)) return -5;
if (ei_x_encode_long(&result, (int)status)) return -5;
if (write_cmd(fd, &result) < 0) {
return -5;
}
ei_x_free(&result);
return 0;
}
int ei_pid_status(int fd, int transId, pid_t pid, int status)
{
return ei_pid_status_header(fd, transId, pid, status, "ok");
}
/**
* Write the process back according to the state
*
**/
int ei_process_error_status(int fd, int transId, pid_t pid, int status, enum ProcessReturnState state, char* out, char* err)
{
ei_x_buff result;
if (encode_header(&result, transId, 6)) return -1;
if (ei_x_encode_atom(&result, "error") ) return -4;
switch(state) {
case PRS_BEFORE:
if (ei_x_encode_atom(&result, "before_command") ) return -4;
break;
case PRS_COMMAND:
if (ei_x_encode_atom(&result, "command") ) return -4;
break;
case PRS_AFTER:
if (ei_x_encode_atom(&result, "after_command") ) return -4;
break;
default:
if (ei_x_encode_atom(&result, "unknown") ) return -4;
break;
}
// Encode pid
if (ei_x_encode_long(&result, (int)pid)) return -5;
if (ei_x_encode_long(&result, (int)status)) return -5;
write_str_to_result(&result, out, "");
write_str_to_result(&result, err, strerror(errno));
if (write_cmd(fd, &result) < 0) {
return -5;
}
ei_x_free(&result);
return 0;
}
int ei_return_process_status(int fd, int transId, process_return_t *p)
{
if(p->stage == PRS_OKAY)
return ei_pid_status(fd, transId, p->pid, p->exit_status);
else
return ei_process_error_status(fd, transId, p->pid, p->exit_status, p->stage, p->stdout, p->stderr);
}
int ei_pid_status_term(int fd, int transId, pid_t pid, int status)
{
return ei_pid_status_header(fd, transId, pid, status, "exit_status");
}
int ei_ok(int fd, int transId, const char* fmt, ...)
{
va_list *vargs = NULL;
return ei_write_atom(fd, transId, "ok", fmt, *vargs);
}
int ei_error(int fd, int transId, const char* fmt, ...){
va_list *vargs = NULL;
return ei_write_atom(fd, transId, "error", fmt, *vargs);
}
int decode_atom_index(char* buf, int *index, const char* cmds[])
{
int type, size;
ei_get_type(buf, index, &type, &size);
char *atom_name = NULL;
if ((atom_name = (char*) calloc(sizeof(char), size)) == NULL) return -1;
if (ei_decode_atom(buf, index, atom_name)) return -1;
int ret = string_index(cmds, atom_name);
free(atom_name);
return ret;
}
/**
* Data i/o
**/
int write_cmd(int fd, ei_x_buff *buff)
{
unsigned char li;
li = (buff->index >> 8) & 0xff;
write_exact(fd, &li, 1);
li = buff->index & 0xff;
write_exact(fd, &li, 1);
return write_exact(fd, (unsigned char*)buff->buff, buff->index);
}
int read_exact(int fd, unsigned char *buf, int len)
{
int i, got=0;
do {
if ((i = read(fd, buf+got, len-got)) <= 0)
return i;
got += i;
} while (got<len);
return len;
}
int write_exact(int fd, unsigned char *buf, int len)
{
int i, wrote = 0;
do {
if ((i = write(fd, buf+wrote, len-wrote)) <= 0)
return i;
wrote += i;
} while (wrote<len);
return len;
}
int write_str_to_result(ei_x_buff *result, char *str, char *else_str)
{
if (str) {
if (ei_x_encode_string_len(result, str, strlen(str))) return -1;
} else {
if (ei_x_encode_string_len(result, else_str, strlen(else_str))) return -1;
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#define MAXLINE 100
#define YES 1
#define NO 0
#define TAB 8
void esetab(int argc, char *argv[], char *tab);
void entab(char *tab);
main(int argc, char *argv[])
{
char tab[MAXLINE+1];
esetab(argc, argv, tab);
entab(tab);
return 0;
}
void esetab(int argc, char *argv[], char *tab)
{
int pos, inc, i;
if (argc <= 1) {
for (i = 1; i < MAXLINE;i++) {
if (i%TAB == 0)
tab[i] = YES;
else
tab[i] = NO;
}
}
else if (argc == 3 && *argv[1] == '-' && *argv[2] == '+') {
pos = atoi(&(*++argv)[1]);
inc = atoi(&(*++argv)[1]);
for (i = 1; i < MAXLINE;i++) {
if (i == pos){
tab[i] = YES;
pos += inc;
}
else
tab[i] = NO;
}
}
else {
pos = atoi(*++argv);
for (i = 1; i < MAXLINE;i++) {
if (i%pos == 0)
tab[i] = YES;
else
tab[i] = NO;
}
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
/*Considerando o registro de um produto de uma loja contendo as seguintes
informações: descrições, valor
Fazer um programa que, dado o registro de 50 produtos, exiba-os na oredem
inversa em que foram digitados.*/
struct produtoLoja{
char descricao[50];
float valor;
int ID;
};
void receberProdutos(struct produtoLoja p[]){
int i = 0;
do {
p[i].ID = i+1;
printf("\nID: %d", i);
printf("\nInsira a descrição do Produto: \n");
scanf("%s", &p[i].descricao);
printf("\nValor do Produto: ");
scanf("%f", &p[i].valor);
system("clear");
i++;
} while(i<3);
}
void exibirProdutos(struct produtoLoja p[]){
int i;
for(i=0;i<3;i++){
printf("\nID: ", p[i].ID);
printf("\nDescrição: %s", p[i].descricao);
printf("\nValor: %.2f", p[i].valor);
}
}
void exibirdeOrdemInversa(struct produtoLoja p[]){
int i=0;
for(i=3-1;i>=0;i--){
printf("\nID: ", p[i].ID);
printf("\nProduto: %s", p[i].descricao);
printf("\nValor: %.2f\n\n", p[i].valor);
printf("___________________");
}
}
int main()
{
struct produtoLoja produto[3];
receberProdutos(produto);
exibirProdutos(produto);
exibirdeOrdemInversa(produto);
return 0;
}
|
C | #include <stdio.h>
int main() {
int broj, cifra, c1, novibroj=0, c2, broj1=0 ,broj2;
do {
printf("Unesite broj: ");
scanf("%d" ,&broj); }
while(broj<0);
do {
printf("Unesite cifru: ");
scanf("%d" ,&cifra); }
while (cifra<0);
do {
c1=broj%10;
broj=broj/10;
if( c1 != cifra){
novibroj=novibroj*10+c1;
}
else
novibroj=novibroj+0;
} while (broj!=0);
do {
c2=novibroj%10;
novibroj=novibroj/10;
broj1=broj1*10+c2;
} while(novibroj!=0);
printf("Nakon izbacivanja broj glasi %d.\n", broj1);
broj2=broj1*2;
printf("Broj pomnozen sa dva glasi %d." ,broj2);
return 0;
}
|
C | #include "Stack.h"
void StackInit(ST* ps)
{
assert(ps);
ps->a = (STDataType*)malloc(sizeof(STDataType) * 4);
if (ps->a == NULL)
{
printf("malloc fail\n");
exit(-1);
}
ps->capacity = 4;
ps->top = 0;
}
void StackDestory(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
// ջ
void StackPush(ST* ps, STDataType x)
{
assert(ps);
// -
if (ps->top == ps->capacity)
{
STDataType* tmp = (STDataType*)realloc(ps->a, ps->capacity * 2 * sizeof(STDataType));
if (tmp == NULL)
{
printf("realloc fail\n");
exit(-1);
}
else
{
ps->a = tmp;
ps->capacity *= 2;
}
}
ps->a[ps->top] = x;
ps->top++;
}
// ջ
void StackPop(ST* ps)
{
assert(ps);
// ջˣPopֱֹ
assert(ps->top > 0);
//ps->a[ps->top - 1] = 0;
ps->top--;
}
STDataType StackTop(ST* ps)
{
assert(ps);
// ջˣTopֱֹ
assert(ps->top > 0);
return ps->a[ps->top - 1];
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
struct stack {
unsigned int size;
int * data;
};
int push_stack(struct stack * s_ptr, int * top, int new_element);
int pop_stack(struct stack * s_ptr, int * top);
int top_stack(struct stack s, int top);
int size_stack(struct stack s, int top);
int is_empty(struct stack s, int top);
int is_full(struct stack s, int top);
int create(struct stack * s_ptr, unsigned int max_size);
int main()
{
int ch;
int top;
int status;
int top_element;
int new_element;
int pop_element;
int flag;
int size;
unsigned int max_size;
struct stack s;
s.size = 100;
top = -1;
do {
printf("\t\tMenu\n");
printf("1. Push : Insert a new element\n");
printf("2. Pop : Removes the top element\n");
printf("3. Top : Last element inserted into the stack\n");
printf("4. Size : No. of elements in the stack\n");
printf("5. Is the stack empty?\n");
printf("6. Is the stack full?\n");
printf("7. Exit\n");
printf("Enter choice: ");
scanf("%d", &ch);
switch (ch) {
case 1: printf("Enter the maximum size of stack you need: ");
scanf("%d", &max_size);
flag = create(&s, max_size);
if (flag == 0) {
printf("Stack creation unsuccessful! Try Again!\n\n");
} else {
printf("Enter new value to be pushed: ");
scanf("%d", &new_element);
status = push_stack(&s, &top, new_element);
if (status == 1) {
printf("%d pushed onto the stack!\n\n", new_element);
}
}
break;
case 2: pop_element = pop_stack(&s, &top);
if (pop_element != -9999) {
printf("\n%d removed from stack!\n\n", pop_element);
}
break;
case 3: top_element = top_stack(s, top);
if (top_element == -9999) {
printf("Stack empty!\n");
} else {
printf("%d is the top element in the stack!\n\n", top_element);
}
break;
case 4: size = size_stack(s, top);
printf("%d elements are present in the stack!\n\n", size);
break;
case 5: flag = is_empty(s, top);
if (flag == 0) {
printf("Stack is not empty!\n\n");
} else {
printf("Stack is empty!\n\n");
}
break;
case 6: flag = is_full(s, top);
if (flag == 0) {
printf("Stack is not full!\n\n");
} else {
printf("Stack is full!\n\n");
}
break;
default: continue;
}
} while (ch != 7);
return 0;
}
int push_stack(struct stack * s_ptr, int * top, int new_element)
{
if (*top == (s_ptr->size-1)) {
printf("Stack Overflow!\n\n");
return 0;
} else {
*top = *top + 1;
s_ptr->data[*top] = new_element;
return 1;
}
}
int pop_stack(struct stack * s_ptr, int * top)
{
int pop_element;
if (*top == -1) {
printf("Stack Underflow!\n\n");
return -9999;
} else if (*top == 0) {
pop_element = s_ptr->data[*top];
*top = -1;
return pop_element;
} else {
pop_element = s_ptr->data[*top];
*top = *top - 1;
return pop_element;
}
}
int top_stack(struct stack s, int top)
{
if (top == -1) {
return -9999;
} else {
return s.data[top];
}
}
int size_stack(struct stack s, int top)
{
int size;
size = 0;
if (top == -1) {
return 0;
} else {
for (size = 1; size <= top; size++);
return size;
}
}
int is_empty(struct stack s, int top)
{
if (top == -1) {
return 1;
} else {
return 0;
}
}
int is_full(struct stack s, int top)
{
if (top == s.size) {
return 1;
} else {
return 0;
}
}
int create(struct stack * s_ptr, unsigned int max_size)
{
s_ptr->data = (int *) malloc(max_size * sizeof(int));
if (s_ptr->data == NULL) {
return 0;
} else {
s_ptr->size = max_size;
return 1;
}
}
|
C | #include <stdio.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include "1-pty_master_open.h"
#include "2-pty_fork.h"
#include "tty_functions.h"
#define MAX_SNAME 1000
#define BUF_SIZE 256
struct termios ttyOrig;
static void ttyReset(void){
if(tcsetattr(STDIN_FILENO,TCSANOW,&ttyOrig) == -1){
fprintf(stderr,"tcsetattr\n");
exit(EXIT_FAILURE);
}
}
int main(int argc,char *argv[]){
struct winsize ws;
int mfd,scriptFd;
pid_t childPid;
char slaveName[MAX_SNAME];
char *shell;
fd_set readsets;
char buf[BUF_SIZE];
ssize_t numRead;
if(tcgetattr(STDIN_FILENO,&ttyOrig) == -1){
fprintf(stderr,"tcgetattr\n");
exit(EXIT_FAILURE);
}
if(ioctl(STDIN_FILENO,TIOCGWINSZ,&ws) == -1){
fprintf(stderr,"ioctl\n");
exit(EXIT_FAILURE);
}
childPid = ptyFork(&mfd,slaveName,MAX_SNAME,&ttyOrig,&ws);
if(childPid == -1){
fprintf(stderr,"ptyFork\n");
exit(EXIT_FAILURE);
}
if(childPid == 0){
shell = getenv("SHELL");
if(shell == NULL || *shell == '\0'){
shell = "/bin/sh";
}
execlp(shell,shell,(char *)NULL);
exit(EXIT_FAILURE);
}
scriptFd = open((argc > 1) ? argv[1] : "typescript",O_WRONLY | O_CREAT | O_TRUNC,0666);
if(scriptFd == -1){
fprintf(stderr,"open\n");
exit(EXIT_FAILURE);
}
ttySetRaw(STDIN_FILENO,&ttyOrig);
if(atexit(ttyReset) != 0){
fprintf(stderr,"atexit\n");
exit(EXIT_FAILURE);
}
while(1){
FD_ZERO(&readsets);
FD_SET(mfd,&readsets);
FD_SET(STDIN_FILENO,&readsets);
if(select(mfd + 1,&readsets,NULL,NULL,NULL) == -1){
fprintf(stderr,"select\n");
exit(EXIT_FAILURE);
}
if(FD_ISSET(mfd,&readsets)){
numRead = read(mfd,buf,BUF_SIZE);
if(numRead <= 0){
fprintf(stderr,"read-1\n");
exit(EXIT_FAILURE);
}
if(write(scriptFd,buf,numRead) != numRead){
fprintf(stderr,"write\n");
exit(EXIT_FAILURE);
}
if(write(STDOUT_FILENO,buf,numRead) != numRead){
fprintf(stderr,"write\n");
exit(EXIT_FAILURE);
}
}
if(FD_ISSET(STDIN_FILENO,&readsets)){
numRead = read(STDIN_FILENO,buf,BUF_SIZE);
if(numRead <= 0){
fprintf(stderr,"read-2\n");
exit(EXIT_FAILURE);
}
if(write(mfd,buf,numRead) != numRead){
fprintf(stderr,"write\n");
exit(EXIT_FAILURE);
}
}
}
return 0;
}
|
C | # include <stdio.h>
#include "hstcal.h"
# include "hstio.h"
# include "xtables.h"
# include <time.h>
# include "acs.h"
# include "hstcalerr.h"
typedef struct {
IRAFPointer tp; /* pointer to table descriptor */
IRAFPointer cp_date; /* column descriptors */
IRAFPointer cp_shiftx;
IRAFPointer cp_shifty;
int nrows; /* number of rows in table */
} TblInfo;
typedef struct {
char date[ACS_CBUF]; /* date for shift */
time_t dtime;
float shiftx;
float shifty;
} TblRow;
static int OpenSpotTab (char *, TblInfo *);
static int ReadSpotTab (TblInfo *, int, TblRow *);
static int CloseSpotTab (TblInfo *);
/* This routine gets information from the SPOTFLAT shift table.
The SPOTFLAT shift table should contain the following:
floating point header parameter:
none needed
and the following columns:
DATE: (char *) date in form of 'dd/mm/yy'
SHIFTX: (float) shift of spots in X direction (pixels)
SHIFTY: (float) shift of spots in Y direction (pixels)
The table is read to find the row that comes closest to the observation
date, and that row is read to obtain the shifts in X and Y.
Input date will be in form of seconds since 1970 as produced by mktime().
*/
int GetSpotTab (char *spottab, time_t date, float *shiftx, float *shifty) {
/* arguments:
ACS2dInfo *acs2d io: calibration switches, etc
*/
extern int status;
TblInfo tabinfo; /* pointer to table descriptor, etc */
TblRow tabrow; /* values read from a table row */
int row; /* loop index */
int min_row;
time_t delta_date, delta;
/* Open the SPOT shift table and find columns. */
if (OpenSpotTab (spottab, &tabinfo))
return (status);
/* Check each row for a match with detector, and get the info
from the matching row.
*/
delta_date = 9999999999;
min_row = tabinfo.nrows;
for (row = 1; row <= tabinfo.nrows; row++) {
/* Read the current row into tabrow. */
if (ReadSpotTab (&tabinfo, row, &tabrow))
return (status);
delta = abs(date - tabrow.dtime);
if (delta < delta_date) {
min_row = row;
delta_date = delta;
}
}
/* Now that we have determined which row has the date closest
to the observation date, read in that row as the final result.
*/
ReadSpotTab (&tabinfo, min_row, &tabrow);
*shiftx = tabrow.shiftx;
*shifty = tabrow.shifty;
if (CloseSpotTab (&tabinfo)) /* close the table */
return (status);
return (status);
}
/* This routine opens the MAMA linearity table, finds the columns that we
need, gets one header keyword, and gets the total number of rows in the
table. The columns are DETECTOR, GLOBAL_LIMIT, LOCAL_LIMIT, and TAU.
*/
static int OpenSpotTab (char *tname, TblInfo *tabinfo) {
extern int status;
tabinfo->tp = c_tbtopn (tname, IRAF_READ_ONLY, 0);
if (c_iraferr()) {
sprintf (MsgText, "SPOTTAB `%s' not found.", tname);
trlerror (MsgText);
return (status = OPEN_FAILED);
}
tabinfo->nrows = c_tbpsta (tabinfo->tp, TBL_NROWS);
/* Find the columns. */
c_tbcfnd1 (tabinfo->tp, "DATE", &tabinfo->cp_date);
c_tbcfnd1 (tabinfo->tp, "SHIFTX", &tabinfo->cp_shiftx);
c_tbcfnd1 (tabinfo->tp, "SHIFTY", &tabinfo->cp_shifty);
if (tabinfo->cp_date == 0 ||
tabinfo->cp_shiftx == 0 ||
tabinfo->cp_shifty == 0 ) {
trlerror ("Column not found in SPOTTAB.");
c_tbtclo (tabinfo->tp);
return (status = COLUMN_NOT_FOUND);
}
return (status);
}
/* This routine reads the relevant data from one row. The date,
shiftx, shifty are read.
*/
static int ReadSpotTab (TblInfo *tabinfo, int row, TblRow *tabrow) {
extern int status;
int parseTabDate(char *, time_t *);
c_tbegtt (tabinfo->tp, tabinfo->cp_date, row,
tabrow->date, ACS_CBUF-1);
if (c_iraferr())
return (status = TABLE_ERROR);
/* Convert the date read in from the row into
time in seconds for comparison with the DATE-OBS value */
status = parseTabDate(tabrow->date, &tabrow->dtime);
c_tbegtr (tabinfo->tp, tabinfo->cp_shiftx, row, &tabrow->shiftx);
if (c_iraferr())
return (status = TABLE_ERROR);
c_tbegtr (tabinfo->tp, tabinfo->cp_shifty, row, &tabrow->shifty);
if (c_iraferr())
return (status = TABLE_ERROR);
return (status);
}
/* This routine closes the mlintab table. */
static int CloseSpotTab (TblInfo *tabinfo) {
extern int status;
c_tbtclo (tabinfo->tp);
if (c_iraferr())
return (status = TABLE_ERROR);
return (status);
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main(void){
int *x = malloc(sizeof(int));
int *y = malloc(sizeof(int));
*x = 1;
*y = 2;
printf("*x is %d\n", *x);
printf("*y is %d\n", *y);
// free(x);
// x = y;
printf("x now points to y\n");
printf("*x is %d\n", *x);
printf("*y is %d\n", *y);
free(x);
}
|
C | #include <stdio.h>
int main()
{
freopen("301.txt", "w", stdout);
int n, op, i;
long long a1, b1;
double a2, b2;
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
scanf("%d", &op);
if (op == 1 || op == 2)
{
scanf("%lld%lld", &a1, &b1);
printf("%lld", a1 + b1);
}
else
{
scanf("%lf%lf", &a2, &b2);
printf("%.4f", a2 + b2);
}
if (i != n)
printf("\n");
}
return 0;
} |
C | #include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
unsigned int j = 0,i = 0;
void prompt_info(int signo)
{
i++;
}
void init_sigaction(void)
{
struct sigaction act;
act.sa_handler = prompt_info;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGPROF,&act,NULL);
}
void init_timer()
{
struct itimerval value;
value.it_value.tv_sec=0;
value.it_value.tv_usec=1000;
value.it_interval=value.it_value;
setitimer(ITIMER_PROF,&value,NULL);
}
int main()
{
init_sigaction();
init_timer();
while(1)
{
if(i == 1000)
{
i=0;
j++;
printf("Timer %d\n",j);
}
}
exit(0);
}
|
C | // TEAM APPLE!
#include "esos_lcd_menu.h"
// ******** G L O B A L S ***************
#define LM60_OFFSET 0xA5A0 // 424 * 100
#define LM60_CELSIUS_CONSTANT 0x0271 // 6.25 *100
volatile menu st_menu; // the structure which holds the values
/****************************************************************
** P U B L I C F U N C T I O N S
****************************************************************/
// sets the number of items in the menu
void esos_create_menu(int8_t i8_numMenuItems) {
st_menu.i8_menuItems = i8_numMenuItems;
}
bool esos_getSetLM60(void){
return st_menu.b_setLM60;
}
void esos_setSetLM60(bool b_status){
st_menu.b_setLM60 = b_status;
}
void clearNewTeam(void){
st_menu.b_newTeam = FALSE;
}
bool newTeam(void){
return st_menu.b_newTeam;
}
// set the menu title, the title type, where the title will be displayed in the menu and the subtitle type
void esos_insert_menu_title(int8_t i8_titleNumber, uint8_t u8_titleType,
uint8_t u8_subTitleType, char *psz_title, char c_id) {
if(i8_titleNumber > 0 && i8_titleNumber <= st_menu.i8_menuItems) {
st_menu.psz_titles[i8_titleNumber - 1] = psz_title;
st_menu.u8_titleType[i8_titleNumber - 1] = u8_titleType;
st_menu.u8_subTitleType[i8_titleNumber - 1] = u8_subTitleType;
st_menu.c_id[i8_titleNumber - 1] = c_id;
}
}
// set the LCD to display the current title selected
void esos_setTitle(int8_t i8_titleNumber) {
esos_lcd_clearScreen(); // clears any data off screen
static char *psz_title; // creates a temp value to print to screen
esos_lcd_setCursor(ROW_ONE, 1 ); // sets cursor to home
if(st_menu.u8_titleType[i8_titleNumber - 1] == SET) {
if(i8_titleNumber != 1){
ESOS_TASK_WAIT_LCD_WRITE_DATA(st_menu.c_id[i8_titleNumber - 1]);
ESOS_TASK_WAIT_LCD_WRITE_DATA(' ');
}
ESOS_TASK_WAIT_LCD_WRITE_DATA('S');
ESOS_TASK_WAIT_LCD_WRITE_DATA('e');
ESOS_TASK_WAIT_LCD_WRITE_DATA('t');
}
else if(st_menu.u8_titleType[i8_titleNumber - 1] == READ) {
ESOS_TASK_WAIT_LCD_WRITE_DATA(st_menu.c_id[i8_titleNumber - 1]);
ESOS_TASK_WAIT_LCD_WRITE_DATA(' ');
ESOS_TASK_WAIT_LCD_WRITE_DATA('R');
ESOS_TASK_WAIT_LCD_WRITE_DATA('e');
ESOS_TASK_WAIT_LCD_WRITE_DATA('a');
ESOS_TASK_WAIT_LCD_WRITE_DATA('d');
}
esos_lcd_setCursor(ROW_TWO, 1 ); // sets cursor to home
psz_title = st_menu.psz_titles[i8_titleNumber - 1];
while(*psz_title) { // print the value to the screen
ESOS_TASK_WAIT_LCD_WRITE_DATA(*psz_title);
psz_title++;
}
}
// sets the line info for a static menu sub item
void esos_setStaticInfo(int8_t i8_titleNumber, char *psz_lineOneInfo,
char *psz_lineTwoInfo) {
if(i8_titleNumber > 0 && i8_titleNumber <= st_menu.i8_menuItems) {
st_menu.psz_lineOneInfo[i8_titleNumber - 1] = psz_lineOneInfo;
st_menu.psz_lineTwoInfo[i8_titleNumber - 1] = psz_lineTwoInfo;
}
}
// sets readout for single value two choice
void esos_setSV2C(int8_t i8_titleNumber, char *psz_valueOne,
char *psz_valueTwo) {
if(i8_titleNumber > 0 && i8_titleNumber <= st_menu.i8_menuItems) {
st_menu.psz_valueOne[i8_titleNumber - 1] = psz_valueOne;
st_menu.psz_valueTwo[i8_titleNumber - 1] = psz_valueTwo;
}
}
// sets readout for single value three choice
void esos_setSV3C(int8_t i8_titleNumber, char *psz_valueOne, char *psz_valueTwo,
char *psz_valueThree) {
if(i8_titleNumber > 0 && i8_titleNumber <= st_menu.i8_menuItems) {
st_menu.psz_valueOne[i8_titleNumber - 1] = psz_valueOne;
st_menu.psz_valueTwo[i8_titleNumber - 1] = psz_valueTwo;
st_menu.psz_valueThree[i8_titleNumber - 1] = psz_valueThree;
}
}
// returns the value of the single value two choice selection
bool esos_getSV2CValue(int8_t i8_titleNumber) {
return st_menu.b_SV2C[i8_titleNumber - 1];
}
// returns the value of the single value three choice selection 1st selection is 0x00
uint8_t esos_getSV3CValue(int8_t i8_titleNumber) {
return st_menu.u8_SV3C[i8_titleNumber - 1];
}
void esos_setSV3C_VALUE(int8_t i8_titleNumber, uint8_t u8_value){
st_menu.u8_SV3C[i8_titleNumber - 1] = u8_value;
}
// need to finish this
// void esos_setDVNUM(int8_t i8_titleNumber, char *psz_valueOne,
// char *psz_valueTwo, uint16_t u16_lowerBound, uint16_t u16_upperBound){
// if(i8_titleNumber > 0 && i8_titleNumber <= st_menu.i8_menuItems) {
// st_menu.psz_valueOne[i8_titleNumber - 1] = psz_valueOne;
// st_menu.psz_valueTwo[i8_titleNumber - 1] = psz_valueTwo;
// st_menu.u16_lowerBound[i8_titleNumber - 1] = u16_lowerBound;
// st_menu.u16_upperBound[i8_titleNumber - 1] = u16_upperBound;
// st_menu.u16_value[i8_titleNumber - 1] = u16_lowerBound;
// }
// }
// sets lower and upper bounds to a single value data title
void esos_setSVDATA(int8_t i8_titleNumber, uint16_t u16_lowerBound,
uint16_t u16_upperBound, bool b_extend, bool b_binary) {
if(i8_titleNumber > 0 && i8_titleNumber <= st_menu.i8_menuItems) {
st_menu.u16_lowerBound[i8_titleNumber - 1] = u16_lowerBound;
st_menu.u16_upperBound[i8_titleNumber - 1] = u16_upperBound;
st_menu.u16_value[i8_titleNumber - 1] = u16_lowerBound;
st_menu.b_extend[i8_titleNumber - 1] = b_extend;
st_menu.b_binary[i8_titleNumber - 1] = b_binary;
}
}
// set a default value to a single value data
void esos_setSVDATAValue(int8_t i8_titleNumber, uint16_t u16_value) {
if(i8_titleNumber > 0 && i8_titleNumber <= st_menu.i8_menuItems) {
st_menu.u16_value[i8_titleNumber - 1] = u16_value;
}
}
// returns the data value of a title
uint16_t esos_getValue(int8_t i8_titleNumber) {
return st_menu.u16_value[i8_titleNumber - 1];
}
// hides a title in the menu
void esos_hideMenuTitle(int8_t i8_titleNumber, bool b_hide) {
st_menu.b_titleHidden[i8_titleNumber - 1] = b_hide;
}
// sets the ADC sensor channel
void esos_setSensorReading(int8_t i8_titleNumber, uint8_t u8_ADCChannel, uint16_t u16_direct) {
if(i8_titleNumber > 0 && i8_titleNumber <= st_menu.i8_menuItems) {
st_menu.u8_ADCChannel[i8_titleNumber - 1] = u8_ADCChannel;
st_menu.u16_directValue[i8_titleNumber - 1] = u16_direct;
}
}
/****************************************************************
** P R I V A T E F U N C T I O N S
****************************************************************/
// set LCD static out info
void __lineStaticInfo(int8_t i8_titleNumber) {
static char *psz_info;
psz_info = st_menu.psz_lineOneInfo[i8_titleNumber - 1];
esos_lcd_setCursor(ROW_ONE, 1 );
while(*psz_info) { // print the value to the screen
ESOS_TASK_WAIT_LCD_WRITE_DATA(*psz_info);
psz_info++;
}
psz_info = st_menu.psz_lineTwoInfo[i8_titleNumber - 1];
esos_lcd_setCursor(ROW_TWO, 1 );
while(*psz_info) { // print the value to the screen
ESOS_TASK_WAIT_LCD_WRITE_DATA(*psz_info);
psz_info++;
}
}
// set LCD SV2 out info
void __lineSV2CInfo(int8_t i8_titleNumber) {
static char *psz_info;
psz_info = st_menu.psz_valueOne[i8_titleNumber - 1];
esos_lcd_setCursor(ROW_ONE, 1 );
while(*psz_info) { // print the value to the screen
ESOS_TASK_WAIT_LCD_WRITE_DATA(*psz_info);
psz_info++;
}
psz_info = st_menu.psz_valueTwo[i8_titleNumber - 1];
esos_lcd_setCursor(ROW_TWO, 1 );
while(*psz_info) { // print the value to the screen
ESOS_TASK_WAIT_LCD_WRITE_DATA(*psz_info);
psz_info++;
}
}
// set SV3C LCD out info
void __lineSV3CInfo(int8_t i8_titleNumber, uint8_t u8_value) {
static char *psz_info;;
psz_info = st_menu.psz_titles[i8_titleNumber - 1];
esos_lcd_setCursor(ROW_ONE, 1 );
while(*psz_info) { // print the value to the screen
ESOS_TASK_WAIT_LCD_WRITE_DATA(*psz_info);
psz_info++;
}
if(u8_value == 1) {
psz_info = st_menu.psz_valueOne[i8_titleNumber - 1];
}
else if(u8_value == 2) {
psz_info = st_menu.psz_valueTwo[i8_titleNumber - 1];
}
else {
psz_info = st_menu.psz_valueThree[i8_titleNumber - 1];
}
esos_lcd_setCursor(ROW_TWO, 1 );
while(*psz_info) { // print the value to the screen
ESOS_TASK_WAIT_LCD_WRITE_DATA(*psz_info);
psz_info++;
}
}
// set DVNUM LCD out info
void __lineDVNUMInfo(int8_t i8_titleNumber) {
static char *psz_info;
psz_info = st_menu.psz_valueOne[i8_titleNumber - 1];
esos_lcd_setCursor(ROW_ONE, 1 );
while(*psz_info) { // print the value to the screen
ESOS_TASK_WAIT_LCD_WRITE_DATA(*psz_info);
psz_info++;
}
psz_info = st_menu.psz_valueTwo[i8_titleNumber - 1];
esos_lcd_setCursor(ROW_TWO, 1 );
while(*psz_info) { // print the value to the screen
ESOS_TASK_WAIT_LCD_WRITE_DATA(*psz_info);
psz_info++;
}
}
// set SVDATA LCD out info
void __lineSVDATAInfo(int8_t i8_titleNumber) {
static char *psz_info;;
psz_info = st_menu.psz_titles[i8_titleNumber - 1];
esos_lcd_setCursor(ROW_ONE, 1 );
while(*psz_info) { // print the value to the screen
ESOS_TASK_WAIT_LCD_WRITE_DATA(*psz_info);
psz_info++;
}
}
// converts the hex to a char
char __u8_hexToChar(uint8_t u8_char) {
if(u8_char == 0x0) {
return '0';
}
else if(u8_char == 0x1) {
return '1';
}
else if(u8_char == 0x2) {
return '2';
}
else if(u8_char == 0x3) {
return '3';
}
else if(u8_char == 0x4) {
return '4';
}
else if(u8_char == 0x5) {
return '5';
}
else if(u8_char == 0x6) {
return '6';
}
else if(u8_char == 0x7) {
return '7';
}
else if(u8_char == 0x8) {
return '8';
}
return '9';
}
// overflow happens at 10000!!!!
// only handles from 0 - 9999
uint16_t __hexToValue(uint16_t u16_value) {
uint16_t u16_count;
uint16_t u16_check;
u16_count = 0x00;
while(u16_value > 0x0A) {
u16_count = u16_count + 0x10;
u16_value = u16_value - 0x0A;
if(u16_count == 0xA0) {
u16_count = 0x100;
}
// *******************************
// need to roll over from F0 to 60
u16_check = u16_count & 0x00F0;
if(u16_check == 0x00F0) {
u16_count = u16_count + 0x060;
}
// *******************************
// need to roll over from F00 to 600
u16_check = u16_count & 0x0F00;
if(u16_check == 0x0F00) {
u16_count = u16_count + 0x0600;
}
}
u16_count = u16_count + u16_value;
// ************************************************
// CONVERT 0xA
u16_check = u16_count & 0x0F;
if(u16_check == 0x0A) {
u16_count = u16_count + 0x0010;
u16_count = u16_count & 0xFFF0;
}
// ************************************************
// ************************************************
// CONVERT 0xA0 - 0xF0
// Handles from 200 - 999
u16_check = u16_count & 0x00F0;
if(u16_check == 0x00A0) {
u16_count = u16_count + 0x0100;
u16_count = u16_count & 0xFF0F;
}
else if(u16_check == 0x00B0) {
u16_count = u16_count + 0x0100;
u16_count = u16_count & 0xFF0F;
u16_count = u16_count + 0x0010;
}
else if(u16_check == 0x00C0) {
u16_count = u16_count + 0x0100;
u16_count = u16_count & 0xFF0F;
u16_count = u16_count + 0x0020;
}
else if(u16_check == 0x00D0) {
u16_count = u16_count + 0x0100;
u16_count = u16_count & 0xFF0F;
u16_count = u16_count + 0x0030;
}
else if(u16_check == 0x00E0) {
u16_count = u16_count + 0x0100;
u16_count = u16_count & 0xFF0F;
u16_count = u16_count + 0x0040;
}
else if(u16_check == 0x00F0) {
u16_count = u16_count + 0x0100;
u16_count = u16_count & 0xFF0F;
u16_count = u16_count + 0x0050;
}
// ************************************************
// CONVERT 0xA00 - 0xF00
// Handles from 1000 - 9999
u16_check = u16_count & 0x0F00;
if(u16_check == 0x0A00) {
u16_count = u16_count + 0x1000;
u16_count = u16_count & 0xF0FF;
}
else if(u16_check == 0x0B00) {
u16_count = u16_count + 0x1000;
u16_count = u16_count & 0xF0FF;
u16_count = u16_count + 0x0100;
}
else if(u16_check == 0x0C00) {
u16_count = u16_count + 0x1000;
u16_count = u16_count & 0xF0FF;
u16_count = u16_count + 0x0200;
}
else if(u16_check == 0x0D00) {
u16_count = u16_count + 0x1000;
u16_count = u16_count & 0xF0FF;
u16_count = u16_count + 0x0300;
}
else if(u16_check == 0x0E00) {
u16_count = u16_count + 0x1000;
u16_count = u16_count & 0xF0FF;
u16_count = u16_count + 0x0400;
}
else if(u16_check == 0x0F00) {
u16_count = u16_count + 0x1000;
u16_count = u16_count & 0xF0FF;
u16_count = u16_count + 0x0500;
}
return u16_count;
}
// returns the hex value representation of the temperature (for LCD purpose)
// might be able to use the other function. Have not tried it yet
uint8_t __u8_hexToTemp(uint8_t u8_upper, uint8_t u8_lower, bool b_fahrenheit) {
uint8_t u8_data;
u8_upper = u8_upper * 16;
u8_data = u8_upper + u8_lower;
if(u8_data <= 20) {
if(b_fahrenheit) {
return 0x68;
}
return 0x20;
}
else if(u8_data == 0x15) {
if(b_fahrenheit) {
return 0x69;
}
return 0x21;
}
else if(u8_data == 0x16) {
if(b_fahrenheit) {
return 0x72;
}
return 0x22;
}
else if(u8_data == 0x17) {
if(b_fahrenheit) {
return 0x73;
}
return 0x23;
}
else if(u8_data == 0x18) {
if(b_fahrenheit) {
return 0x75;
}
return 0x24;
}
else if(u8_data == 0x19) {
if(b_fahrenheit) {
return 0x77;
}
return 0x25;
}
else if(u8_data == 0x1a) {
if(b_fahrenheit) {
return 0x79;
}
return 0x26;
}
else if(u8_data == 0x1b) {
if(b_fahrenheit) {
return 0x81;
}
return 0x27;
}
else if(u8_data == 0x1c) {
if(b_fahrenheit) {
return 0x82;
}
return 0x28;
}
else if(u8_data == 0x1d) {
if(b_fahrenheit) {
return 0x84;
}
return 0x29;
}
else if(u8_data == 0x1e) {
if(b_fahrenheit) {
return 0x86;
}
return 0x30;
}
else if(u8_data == 0x1f) {
if(b_fahrenheit) {
return 0x88;
}
return 0x31;
}
else if(u8_data == 0x20) {
if(b_fahrenheit) {
return 0x90;
}
return 0x32;
}
else if(u8_data == 0x21) {
if(b_fahrenheit) {
return 0x91;
}
return 0x33;
}
else if(u8_data == 0x22) {
if(b_fahrenheit) {
return 0x93;
}
return 0x34;
}
if(b_fahrenheit) {
return 0x95;
}
return 0x35;
}
// sets the read title LCD child task constants
void __lineREADInfo(int8_t i8_titleNumber) {
static char *psz_info;;
psz_info = st_menu.psz_titles[i8_titleNumber - 1];
esos_lcd_setCursor(ROW_ONE, 1 );
while(*psz_info) { // print the value to the screen
ESOS_TASK_WAIT_LCD_WRITE_DATA(*psz_info);
psz_info++;
}
}
/****************************************************************
** E S O S T A S K
****************************************************************/
// STATIC DISPLAY
ESOS_CHILD_TASK(staticDisplay, int8_t i8_titleNumber) {
ESOS_TASK_BEGIN();
static bool b_stay = TRUE; // determains the need to keep child task runing
esos_lcd_clearScreen(); // clear the screen
__lineStaticInfo(i8_titleNumber); // set the static output
while(b_stay) {
if(f15ui_isRpgTurningCW()) { // Scroll Right
ESOS_TASK_WAIT_LCD_WRITE_COMMAND(0x18);
}
else if(f15ui_isRpgTurningCCW()) { // Scroll Left
ESOS_TASK_WAIT_LCD_WRITE_COMMAND(0x1C);
}
if(f15ui_isSW3Pressed()) { // see if need to break out of child task
b_stay = false;
}
ESOS_TASK_WAIT_TICKS(20);
}
b_stay = TRUE; // make sure we set this back to true so we can return if needed
ESOS_TASK_END();
}
// SINGLE VALUE DOUBLE SELECT
ESOS_CHILD_TASK(sv2c, int8_t i8_titleNumber) {
ESOS_TASK_BEGIN();
static bool b_stay = TRUE; // determains the need to keep child running
static bool b_selection; // keeps up with the selection to return to the user
esos_lcd_clearScreen(); // clear the screen
esos_lcd_setCursor(ROW_ONE, 8 ); // print an initial selection arrow
ESOS_TASK_WAIT_LCD_WRITE_DATA(SELECT);
__lineSV2CInfo(i8_titleNumber); // print the selections choices
while(b_stay) {
// logic for scrolling and making the selection
// choice two is a true
if(f15ui_isRpgTurningCW() || f15ui_isSW1Pressed()) {
esos_lcd_setCursor(ROW_ONE, 8 );
ESOS_TASK_WAIT_LCD_WRITE_DATA(SELECT);
esos_lcd_setCursor(ROW_TWO, 8 );
ESOS_TASK_WAIT_LCD_WRITE_DATA(' ');
b_selection = FALSE;
}
else if(f15ui_isRpgTurningCCW() || f15ui_isSW2Pressed()) {
esos_lcd_setCursor(ROW_ONE, 8 );
ESOS_TASK_WAIT_LCD_WRITE_DATA(' ');
esos_lcd_setCursor(ROW_TWO, 8 );
ESOS_TASK_WAIT_LCD_WRITE_DATA(SELECT);
b_selection = TRUE;
}
if(f15ui_isSW3Pressed()) { // see if we need to break out of child task
b_stay = false;
st_menu.b_SV2C[i8_titleNumber - 1] = b_selection; // set the selection
}
ESOS_TASK_WAIT_TICKS(20);
}
b_stay = TRUE; // make sure we set this back to true so we can return if needed
ESOS_TASK_END();
}
// SINGLE VALUE TRIPLE SELECT
ESOS_CHILD_TASK(sv3c, int8_t i8_titleNumber) {
ESOS_TASK_BEGIN();
static bool b_stay = TRUE; // check to see if the child loops
static bool b_update; // for updating arrows
static uint8_t u8_value; // set initial value
u8_value = st_menu.u8_SV3C[i8_titleNumber - 1];
esos_lcd_clearScreen(); // clear the screen of artifacts
__lineSV3CInfo(i8_titleNumber, u8_value);
esos_lcd_setCursor(ROW_TWO, 7);
ESOS_TASK_WAIT_LCD_WRITE_DATA(' ');
ESOS_TASK_WAIT_LCD_WRITE_DATA(DOWN);
while(b_stay) {
// handles the logic for scrolling though sub menu and
// setting value of user selection
if(f15ui_isSW1Pressed() || f15ui_isRpgTurningCCW()) {
if(u8_value > 1) {
u8_value--;
__lineSV3CInfo(i8_titleNumber, u8_value);
u8_value = u8_value;
b_update = TRUE;
}
}
else if(f15ui_isSW2Pressed() || f15ui_isRpgTurningCW()) {
if(u8_value < 3) {
u8_value++;
__lineSV3CInfo(i8_titleNumber, u8_value);
u8_value = u8_value;
b_update = TRUE;
}
}
// if an update has happen, make sure to update the arrows appropriately
if(b_update) {
if(u8_value == 1) {
esos_lcd_setCursor(ROW_ONE, 8);
ESOS_TASK_WAIT_LCD_WRITE_DATA(' ');
esos_lcd_setCursor(ROW_TWO, 7);
ESOS_TASK_WAIT_LCD_WRITE_DATA(' ');
ESOS_TASK_WAIT_LCD_WRITE_DATA(DOWN);
}
else if(u8_value == 2) {
esos_lcd_setCursor(ROW_ONE, 8);
ESOS_TASK_WAIT_LCD_WRITE_DATA(UP);
esos_lcd_setCursor(ROW_TWO, 7);
ESOS_TASK_WAIT_LCD_WRITE_DATA(' ');
ESOS_TASK_WAIT_LCD_WRITE_DATA(DOWN);
}
else {
esos_lcd_setCursor(ROW_ONE, 8);
ESOS_TASK_WAIT_LCD_WRITE_DATA(UP);
esos_lcd_setCursor(ROW_TWO, 8);
ESOS_TASK_WAIT_LCD_WRITE_DATA(' ');
}
}
if(f15ui_isSW3Pressed()) { // see if we need to break out of child task
b_stay = false; // break out of child task
st_menu.u8_SV3C[i8_titleNumber - 1] = u8_value; // set the value
if(i8_titleNumber == 1){
st_menu.b_newTeam = TRUE;
ESOS_TASK_WAIT_UNTIL(st_menu.b_newTeam == FALSE);
}
}
ESOS_TASK_WAIT_TICKS(20);
}
b_stay = TRUE; // make sure we set this back to true so we can return if needed
ESOS_TASK_END();
}
// single value data task
ESOS_CHILD_TASK(svdata, int8_t i8_titleNumber) {
ESOS_TASK_BEGIN();
static bool b_stay = TRUE; // determains the need to keep child task runing
static uint16_t u16_value;
static uint16_t u16_lcdValue;
static uint8_t u8_upper1; // 0xF000
static uint8_t u8_upper2; // 0x0F00
static uint8_t u8_lower1; // 0x00F0
static uint8_t u8_lower2; // 0x000F
u16_value = st_menu.u16_value[i8_titleNumber - 1];
esos_lcd_clearScreen(); // clear the screen
__lineSVDATAInfo(i8_titleNumber); // set the static output
while(b_stay) {
// make sure the limits are not broken
if(f15ui_isSW1Pressed()) {
if(u16_value < st_menu.u16_upperBound[i8_titleNumber - 1]) {
u16_value++;
}
}
else if(f15ui_isSW2Pressed()) {
if(u16_value > st_menu.u16_lowerBound[i8_titleNumber - 1]) {
u16_value--;
}
}
// for fast tuning the value
if(f15ui_isRpgTurningCW()) {
if(u16_value < st_menu.u16_upperBound[i8_titleNumber - 1]) {
u16_value = u16_value + 50;
if(u16_value > st_menu.u16_upperBound[i8_titleNumber - 1]) {
u16_value = st_menu.u16_upperBound[i8_titleNumber - 1];
}
}
}
else if(f15ui_isRpgTurningCCW()) { // Scroll Left
if(u16_value > st_menu.u16_lowerBound[i8_titleNumber - 1]) {
u16_value = u16_value - 50;
if(u16_value < st_menu.u16_lowerBound[i8_titleNumber - 1]) {
u16_value = st_menu.u16_lowerBound[i8_titleNumber - 1];
}
}
}
u16_lcdValue = __hexToValue(u16_value);
u8_upper1 = u16_lcdValue >> 12;
u8_upper1 = u8_upper1 & 0x0F;
u8_upper2 = u16_lcdValue >> 8;
u8_upper2 = u8_upper2 & 0x0F;
u8_lower1 = (uint8_t)u16_lcdValue >> 4;
u8_lower1 = u8_lower1 & 0x0F;
u8_lower2 = (uint8_t)u16_lcdValue & 0x0F;
// ************* B I N A R Y O U T P U T ***********************************
// This will only work for upper 3 bits
// The instructions for how the LED's should work does not make sense
// when compared to the other sections of single data entry values.
// It seems it would be easier to have a dedicated binary menu input option
// then trying to do it this way.
if(st_menu.b_binary[i8_titleNumber - 1]) {
if(u8_lower2 == 0x02) {
u8_lower1 = 0x0;
u8_upper2 = 0x1;
u8_upper1 = 0x0;
u16_value = 0x02;
}
else if(u8_lower2 == 0x03) {
u8_lower1 = 0x1;
u8_upper2 = 0x1;
u8_upper1 = 0x0;
u16_value = 0x03;
}
else if(u8_lower2 == 0x04) {
u8_lower1 = 0x0;
u8_upper2 = 0x0;
u8_upper1 = 0x1;
u16_value = 0x04;
}
else if(u8_lower2 == 0x05) {
u8_lower1 = 0x1;
u8_upper2 = 0x0;
u8_upper1 = 0x1;
u16_value = 0x05;
}
else if(u8_lower2 == 0x06) {
u8_lower1 = 0x0;
u8_upper2 = 0x1;
u8_upper1 = 0x1;
u16_value = 0x06;
}
else if(u8_lower2 == 0x07) {
u8_lower1 = 0x1;
u8_upper2 = 0x1;
u8_upper1 = 0x1;
u16_value = 0x07;
}
else if(u8_lower2 == 0x01 || u16_value > 0x00) {
u8_lower1 = 0x1;
u8_upper2 = 0x0;
u8_upper1 = 0x0;
u16_value = 0x01;
}
u8_lower2 = 0;
}
esos_lcd_setCursor(ROW_TWO, 1 ); // move cursor to upper byte position
ESOS_TASK_WAIT_LCD_WRITE_DATA(__u8_hexToChar(u8_upper1)); // write upper byte
ESOS_TASK_WAIT_LCD_WRITE_DATA(__u8_hexToChar(u8_upper2)); // write middle byte
ESOS_TASK_WAIT_LCD_WRITE_DATA(__u8_hexToChar(u8_lower1)); // write lower byte
ESOS_TASK_WAIT_LCD_WRITE_DATA(__u8_hexToChar(u8_lower2)); // write lower byte
// *************************for later use ************************
if(st_menu.b_extend[i8_titleNumber - 1]) {
ESOS_TASK_WAIT_LCD_WRITE_DATA('0');
ESOS_TASK_WAIT_LCD_WRITE_DATA('0');
ESOS_TASK_WAIT_LCD_WRITE_DATA('0');
ESOS_TASK_WAIT_LCD_WRITE_DATA('0');
}
// ************* B I N A R Y O U T P U T ***********************************
if(f15ui_isSW3Pressed()) { // see if need to break out of child task
b_stay = false;
}
ESOS_TASK_WAIT_TICKS(35);
}
st_menu.u16_value[i8_titleNumber - 1] = u16_value;
b_stay = TRUE; // make sure we set this back to true so we can return if needed
ESOS_TASK_END();
}
// THIS IS ONLY CODED FOR ADC SENSOR 3 RIGHT NOW
// NEED TO ADD CODE FOR OTHER CHANNELS IF NEEDED
ESOS_CHILD_TASK(read, int8_t i8_titleNumber) {
ESOS_TASK_BEGIN();
static bool b_stay = TRUE; // determains the need to keep child task runing
static bool b_changeFormat = FALSE;
static uint16_t u16_data;
static uint8_t u8_temp;
static uint8_t u8_slider;
static uint8_t u8_oldtemp;
static uint8_t u8_upper;
static uint8_t u8_lower;
esos_lcd_clearScreen(); // clear the screen
__lineREADInfo(i8_titleNumber); // set the static output
while(b_stay) {
// FOR LM60 READING
if(st_menu.u8_ADCChannel[i8_titleNumber - 1] == ESOS_SENSOR_CH03) {
ESOS_TASK_WAIT_ON_AVAILABLE_SENSOR(st_menu.u8_ADCChannel[i8_titleNumber - 1],
ESOS_SENSOR_VREF_3V3);
ESOS_USE_ADC_12_BIT(TRUE);
ESOS_TASK_WAIT_SENSOR_READ(u16_data, ESOS_SENSOR_AVG64,
ESOS_SENSOR_FORMAT_VOLTAGE); // get the ADC reading
ESOS_TASK_WAIT_UNTIL(ESOS_SENSOR_CLOSE());
u16_data = (u16_data * 10) - LM60_OFFSET;
u16_data = u16_data / LM60_CELSIUS_CONSTANT;
// first we need to separate the powers
u8_upper = (uint8_t)u16_data & 0xF0;
u8_upper = u8_upper >> 4;
u8_lower = (uint8_t)u16_data & 0x0F;
// next convert it to a hex decimal representation
u8_temp = __u8_hexToTemp(u8_upper,u8_lower, b_changeFormat);
// so the slider code does not have to be changed use this
u8_slider = __u8_hexToTemp(u8_upper,u8_lower, FALSE);
u8_upper = (uint8_t)u8_temp & 0xF0;
u8_upper = u8_upper >> 4;
u8_lower = (uint8_t)u8_temp & 0x0F;
}
else{
u16_data = (st_menu.u16_directValue[5] * 10) - LM60_OFFSET;
u16_data = u16_data / LM60_CELSIUS_CONSTANT;
u8_upper = (uint8_t)u16_data & 0xF0;
u8_upper = u8_upper >> 4;
u8_lower = (uint8_t)u16_data & 0x0F;
// next convert it to a hex decimal representation
u8_temp = __u8_hexToTemp(u8_upper,u8_lower, b_changeFormat);
// so the slider code does not have to be changed use this
u8_slider = __u8_hexToTemp(u8_upper,u8_lower, FALSE);
u8_upper = (uint8_t)u8_temp & 0xF0;
u8_upper = u8_upper >> 4;
u8_lower = (uint8_t)u8_temp & 0x0F;
}
esos_lcd_setCursor(ROW_TWO, 1 ); // move cursor to upper byte position
ESOS_TASK_WAIT_LCD_WRITE_DATA(__u8_hexToChar(u8_upper)); // write upper byte
esos_lcd_setCursor(ROW_TWO, 2 ); // move cursor to upper byte position
ESOS_TASK_WAIT_LCD_WRITE_DATA(__u8_hexToChar(u8_lower)); // write upper byte
esos_lcd_setCursor(ROW_TWO, 3 ); // move cursor to upper byte position
if(b_changeFormat) {
ESOS_TASK_WAIT_LCD_WRITE_DATA('F');
}
else {
ESOS_TASK_WAIT_LCD_WRITE_DATA('C');
}
// ********** S L I D E R *******************************
if(u8_oldtemp != u8_slider) {
// the temp is in a hex representation of C
// so need to compare the hex value
// 27C == 0x27 (this is for LCD printing purpose)
if(u8_slider >= 0x26) {
// if >= 27 row two will be full
esos_lcd_setCursor(ROW_TWO, 8 );
ESOS_TASK_WAIT_LCD_WRITE_DATA(0xFF);
esos_lcd_setCursor(ROW_ONE, 8 );
ESOS_TASK_WAIT_LCD_WRITE_DATA(' ');
esos_lcd_setCursor(ROW_ONE, 8 );
// check to see what needs to be put into row one
if(u8_slider >= 0x34) {
ESOS_TASK_WAIT_LCD_WRITE_DATA(0xFF);
}
else if(u8_slider >= 0x32) {
ESOS_TASK_WAIT_LCD_WRITE_DATA(0x03);
}
else if(u8_slider >= 0x30) {
ESOS_TASK_WAIT_LCD_WRITE_DATA(0x04);
}
else if(u8_slider >= 0x28) {
ESOS_TASK_WAIT_LCD_WRITE_DATA(0x05);
}
}
else {
// if < 27 row one will be blank
esos_lcd_setCursor(ROW_ONE, 8 );
ESOS_TASK_WAIT_LCD_WRITE_DATA(' ');
esos_lcd_setCursor(ROW_TWO, 8 );
// check to see what needs to be put into row two
if(u8_slider <= 0x21) {
ESOS_TASK_WAIT_LCD_WRITE_DATA(0x05);
}
else if(u8_slider <= 0x23) {
ESOS_TASK_WAIT_LCD_WRITE_DATA(0x04);
}
else if(u8_slider <= 0x25) {
ESOS_TASK_WAIT_LCD_WRITE_DATA(0x03);
}
}
u8_oldtemp = u8_slider; // reset old temp
}
// ****************************************************
// ADD CODE HERE FOR OTHER READINGS
// else{
// }
// changes the output format for the sensor reading
// for example C to F
if(f15ui_isRpgTurningCW() || f15ui_isSW1Pressed() || f15ui_isSW2Pressed()) {
b_changeFormat = !b_changeFormat;
ESOS_TASK_F15UI_WAIT_UNTIL_SW2_RELEASED();
ESOS_TASK_F15UI_WAIT_UNTIL_SW1_RELEASED();
}
if(f15ui_isSW3Pressed()) { // see if need to break out of child task
b_stay = false;
u8_oldtemp = 0x00;
}
ESOS_TASK_WAIT_TICKS(100);
}
b_stay = TRUE; // make sure we set this back to true so we can return if needed
ESOS_TASK_END();
}
ESOS_USER_TASK(MENU) {
ESOS_TASK_BEGIN();
static uint8_t pu8_tempLow[8] = {0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x1F, 0x1F};
static uint8_t pu8_tempMed[8] = {0x20, 0x20, 0x20, 0x20, 0x1F, 0x1F, 0x1F, 0x1F};
static uint8_t pu8_tempHig[8] = {0x20, 0x20, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F};
esos_lcd_setCustomChar(0x58, pu8_tempHig);
esos_lcd_setCustomChar(0x60, pu8_tempMed);
esos_lcd_setCustomChar(0x68, pu8_tempLow);
static int i8_counter = 1;
static bool b_update = TRUE;
static ESOS_TASK_HANDLE th_child;
while (TRUE) {
// ***************************************************************
// HANDLES SCROLLING THOUGH MENU
if(f15ui_isRpgTurningCCW() || f15ui_isSW2Pressed()) { // menu goes up
i8_counter++;
// if the menu item is hidden skip over it
if(st_menu.b_titleHidden[i8_counter - 1]){
i8_counter++;
}
b_update = TRUE; // update the screen
// if counter is going over item count, don't update
if(i8_counter > st_menu.i8_menuItems) {
i8_counter = st_menu.i8_menuItems;
b_update = FALSE;
}
}
else if(f15ui_isRpgTurningCW() || f15ui_isSW1Pressed()) { // menu goes down
i8_counter--;
// if the menu item is hidden skip over it
if(st_menu.b_titleHidden[i8_counter - 1]){
i8_counter--;
}
b_update = TRUE;
// if counter is going under item count, don't update
if(i8_counter < 1) {
i8_counter = 1;
b_update = FALSE;
}
}
// ***************************************************************
// HANDLES UPDATING MENU IF SCROLLING
if(b_update) {
ESOS_TASK_WAIT_DISPLAY_TITLE(i8_counter);
// if the menu is at the top display on the down arrow
if(i8_counter == 1) {
esos_lcd_setCursor(ROW_ONE, 8 );
ESOS_TASK_WAIT_LCD_WRITE_DATA(' ');
esos_lcd_setCursor(ROW_TWO, 8 );
ESOS_TASK_WAIT_LCD_WRITE_DATA(DOWN);
}
// if the menu is at the bottom display only the up arrow
else if(i8_counter == st_menu.i8_menuItems) {
esos_lcd_setCursor(ROW_ONE, 8 );
ESOS_TASK_WAIT_LCD_WRITE_DATA(UP);
esos_lcd_setCursor(ROW_TWO, 8 );
ESOS_TASK_WAIT_LCD_WRITE_DATA(' ');
}
// otherwise display them both
else {
esos_lcd_setCursor(ROW_ONE, 8 );
ESOS_TASK_WAIT_LCD_WRITE_DATA(UP);
esos_lcd_setCursor(ROW_TWO, 8 );
ESOS_TASK_WAIT_LCD_WRITE_DATA(DOWN);
}
b_update = FALSE;
}
// ***************************************************************
if(f15ui_isSW3Pressed()) {
ESOS_ALLOCATE_CHILD_TASK(th_child);
ESOS_TASK_F15UI_WAIT_UNTIL_SW3_RELEASED(); // wait until the SW3 is released until we continue
if(st_menu.u8_titleType[i8_counter - 1] == STATIC) {
ESOS_TASK_SPAWN_AND_WAIT(th_child, staticDisplay, i8_counter);
}
else if(st_menu.u8_subTitleType[i8_counter - 1] == SV2C) {
ESOS_TASK_SPAWN_AND_WAIT(th_child, sv2c, i8_counter);
}
else if(st_menu.u8_subTitleType[i8_counter - 1] == SV3C) {
ESOS_TASK_SPAWN_AND_WAIT(th_child, sv3c, i8_counter);
}
else if(st_menu.u8_subTitleType[i8_counter - 1] == SVDATA) {
ESOS_TASK_SPAWN_AND_WAIT(th_child, svdata, i8_counter);
}
else if(st_menu.u8_titleType[i8_counter - 1] == READ) {
ESOS_TASK_SPAWN_AND_WAIT(th_child, read, i8_counter);
}
b_update =
TRUE; // make sure the menu is going to update upon coming out of child task
ESOS_TASK_F15UI_WAIT_UNTIL_SW3_RELEASED(); // wait until the SW3 is released until we continue
}
ESOS_TASK_WAIT_TICKS(25);
} // endof while(TRUE)
ESOS_TASK_END();
} // end upper_case()
/****************************************************************
** I N I T F U N C T I O N
****************************************************************/
void esos_init_menu(void) {
config_esos_f15ui(); // setup UI for heartbeat
esos_lcd_configDisplay(); // config LCD hardware
esos_lcd_init(); // initilize the LCD
static uint8_t pu8_selectArrow[8] = { 0x02, 0x06, 0x0E, 0x1E, 0x0E, 0x06, 0x02, 0x20};
static uint8_t pu8_upArrow[8] = { 0x20, 0x04, 0x0E, 0x1f, 0x20, 0x20, 0x20, 0x20};
static uint8_t pu8_downArrow[8] = { 0x20, 0x20, 0x20, 0x20, 0x1f, 0x0E, 0x04, 0x20};
esos_lcd_setCustomChar(0x40, pu8_selectArrow);
esos_lcd_setCustomChar(0x48, pu8_upArrow);
esos_lcd_setCustomChar(0x50, pu8_downArrow);
esos_RegisterTask(MENU);
} |
C | #include <stdio.h>
#include <string.h>
#define R_ENV "OLDPWD"
int main(int argc, const char *argv[])
{
extern char **environ ;
printf("environ = %s\n",*environ) ;
printf("environ addr = %p\n", environ) ;
char** env = environ;
while( *env != NULL)
{
printf("%s\n", *env++) ;
}
/*读指定的 环境变量的值*/
printf("**********************************************\n") ;
printf("**********************************************\n") ;
printf("**********************************************\n") ;
printf("**********************************************\n") ;
char* value = NULL ;
env = environ ;
while( *env != NULL)
{
char* str = *env++ ;
if( strncmp(str , R_ENV, strlen(R_ENV)) == 0)
{
value = str ;
break ;
}
}
if( NULL != value)
{
printf("%s\n", value) ;
}else{
printf("null ===\n") ;
}
return 0;
}
|
C | #include "rt_hist.h"
#include <string.h>
#include <stdlib.h>
#include <assert.h>
void
hist_init (hist_head_t* list) {
memset(list, 0, sizeof(hist_head_t));
}
/* Push to the front */
void
hist_push (hist_head_t* list, int c) {
hist_t* hist;
hist = malloc(sizeof(hist_t));
assert(hist);
hist->c = c;
hist->prev = NULL;
if (!list->tail) {
list->tail = hist;
}
hist->next = list->head;
list->head = hist;
if (hist->next) {
hist->next->prev = hist;
}
list->size += 1;
}
/* Pop from back */
void
hist_remv (hist_head_t* list) {
hist_t* hist;
if (!list->tail) {
return;
}
hist = list->tail;
list->tail = hist->prev;
if (list->tail) {
list->tail->next = NULL;
} else {
list->head = NULL;
}
free(hist);
list->size -= 1;
}
void
hist_gc (hist_head_t* list, int sz) {
while (list->size > sz) {
hist_remv(list);
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX(A,B) (((A) > (B))? (A) : (B))
void show_vector(int* ,int );
void initialize_right_LCS_vector(int* , int );
int* lLCS(char*, int, char*, int);
char* get_string();
int main(){
char *word1 = NULL;
char *word2 = NULL;
word1 = get_string();
word2 = get_string();
int word1_lenght = (unsigned)strlen(word1);
int word2_lenght = (unsigned)strlen(word2);
int *L;
L = lLCS(word1, word1_lenght, word2, word2_lenght);
show_vector(L,(unsigned)strlen(word1));
printf("\n");
free(L);
free(word1);
free(word2);
return 0;
}
void show_vector(int* v,int n){
int i;
printf("\nL = [");
for(i = 1; i <= n; i++){ printf(" %d",v[i]); }
printf(" ]\n");
}
void initialize_right_LCS_vector(int* right_v, int m){
int i;
for(i = 0; i < m; i++){ right_v[i] = 0; }
}
int* lLCS(char* x, int n, char* y, int m){
int i,j;
int a,b,c;
int r;
int *L = malloc((n+1)*sizeof(int));
int *right_v = malloc((m+1)*sizeof(int));
initialize_right_LCS_vector(right_v, n);
L[0] = 0;
for(i = n - 1; i >= 0; i--){
a = 0;
b = 0;
for(j = m - 1; j >= 0; j--){
c = right_v[j];
if(x[i] == y[j]){
a = b + 1;
}else{
a = MAX(a, c);
}
b = c;
right_v[j] = a;
}
right_v[j+1] = a;
L[i+1] = right_v[j+1];
}
free(right_v);
return L;
}
char* get_string(char* str){
size_t len = 0;
ssize_t read;
printf("Insira uma sequencia de caracteres : ");
if(getline(&str, &len, stdin) != -1){
size_t ln = strlen(str);
if (ln > 0 && str[ln-1] == '\n') {str[--ln] = '\0';}
printf("Palavra lida : %s\n",str);
return str;
}else{
printf("Erro! Programa Abortado\n");
exit(EXIT_FAILURE);
}
} |
C | #include <stdio.h>
int main(void)
{
int ch;
ch = 97;
// 변환 코드: %c, %d
printf("ch: %c, %d \n", ch, ch); // a, 97
return 0;
}
|
C | #include <stdio.h>
int main()
{
unsigned int num=0x7fd00;
unsigned int i;
for(i=256;i<512;i++){
if(i%8==0)
printf("\n");
printf("0x%x, ", num/i);
}
return 0;
} |
C | #include <stdio.h> /* printf */
#include <stdlib.h> /* malloc, free */
/* global functions and variables */
int s_count;
void print_count()
{
printf("s_count: %d\n", s_count);
}
void print_info()
{
print_count();
}
/* PublicTrasport */
void PTdisplayVT(void* PT);
struct PTvtable
{
void (*display)(void*);
} PTvtable = {&PTdisplayVT};
typedef struct
{
void* vptr;
int m_license_plate;
} PublicTransport;
void PTctor(PublicTransport* PT)
{
(void*)PT = &PTvtable;
++s_count;
PT->m_license_plate = s_count;
printf("PublicTransport::Ctor()%d\n", PT->m_license_plate);
}
void PTdtor(PublicTransport* PT)
{
(void*)PT = &PTvtable;
--s_count;
printf("PublicTransport::Dtor()%d\n", PT->m_license_plate);
}
void PTcctor(PublicTransport* PT, const PublicTransport* other)
{
(void*)PT = &PTvtable;
++s_count;
PT->m_license_plate = s_count;
printf("PublicTransport::CCtor() %d\n", PT->m_license_plate);
}
void PTdisplayVT(void* PT)
{
printf("PublicTransport::display(): %d\n", ((PublicTransport*)PT)->m_license_plate);
}
int get_ID(PublicTransport* PT)
{
return PT->m_license_plate;
}
void print_info_PT(PublicTransport* PT)
{
((struct PTvtable*)(PT->vptr))->display(PT);
}
/* Minibus */
void MBdisplayVT(void* MB);
void MBwashVT(void* MB, int minutes);
struct MBvtable
{
void (*display)(void*);
void (*wash)(void*, int minutes);
} MBvtable = {&MBdisplayVT, &MBwashVT};
typedef struct
{
PublicTransport PT;
int m_numSeats;
} Minibus;
void MBctor(Minibus* MB)
{
PTctor(&MB->PT);
(void*)MB = &MBvtable;
MB->m_numSeats = 20;
printf("Minibus::Ctor()\n");
}
void MBdtor(Minibus* MB)
{
(void*)MB = &MBvtable;
printf("Minibus::Dtor()\n");
PTdtor(&MB->PT);
}
void MBcctor(Minibus* MB, const Minibus* other)
{
PTcctor(&MB->PT, &other->PT);
MB->m_numSeats = other->m_numSeats;
(void*)MB = &MBvtable;
printf("Minibus::CCtor()\n");
}
void MBdisplayVT(void* MB)
{
printf("Minibus::display() ID:%d", get_ID(&((Minibus*)MB)->PT));
printf(" num seats:%d\n", ((Minibus*)MB)->m_numSeats);
}
void MBwashVT(void* MB, int minutes)
{
printf("Minibus::wash(%d) ID:%d\n", minutes, get_ID(&((Minibus*)MB)->PT));
}
void print_info_MB(Minibus* MB)
{
((struct MBvtable*)(MB->PT.vptr))->wash(MB, 3);
}
void print_info_INT_and_cpy(int i, PublicTransport* to_cpy_to)
{
Minibus ret;
MBctor(&ret);
printf("print_info(int i)\n");
((struct MBvtable*)(ret.PT.vptr))->display(&ret);
PTcctor(to_cpy_to, &ret.PT);
MBdtor(&ret);
}
/* Taxi */
void TXdisplayVT(void* TX);
struct TXvtable
{
void (*display)(void*);
} TXvtable = {&TXdisplayVT};
typedef struct
{
PublicTransport PT;
} Taxi;
void TXctor(Taxi* TX)
{
PTctor(&TX->PT);
(void*)TX = &TXvtable;
printf("Taxi::Ctor()\n");
}
void TXdtor(Taxi* TX)
{
(void*)TX = &TXvtable;
printf("Taxi::Dtor()\n");
PTdtor(&TX->PT);
}
void TXcctor(Taxi* TX, const Taxi* other)
{
PTcctor(&TX->PT, &other->PT);
(void*)TX = &TXvtable;
printf("Taxi::CCtor()\n");
}
void TXdisplayVT(void* TX)
{
printf("Taxi::display() ID:%d\n", get_ID(&((Taxi*)TX)->PT));
}
void taxi_display(Taxi s)
{
((struct TXvtable*)(s.PT.vptr))->display(&s);
}
/* special taxi */
void STXdisplayVT(void* STX);
struct STXvtable
{
void (*display)(void*);
} STXvtable = {&STXdisplayVT};
typedef struct
{
Taxi TX;
} SpecialTaxi;
void STXctor(SpecialTaxi* STX)
{
TXctor(&STX->TX);
(void*)STX = &STXvtable;
printf("SpecialTaxi::Ctor()\n");
}
void STXdtor(SpecialTaxi* STX)
{
(void*)STX = &STXvtable;
printf("SpecialTaxi::Dtor()\n");
TXdtor(&STX->TX);
}
void STXcctor(SpecialTaxi* STX, const SpecialTaxi* other)
{
TXcctor(&STX->TX, &other->TX);
(void*)STX = &STXvtable;
printf("SpecialTaxi::CCtor()\n");
}
void STXdisplayVT(void* STX)
{
printf("SpecialTaxi::display() ID:%d", get_ID(&((SpecialTaxi*)STX)->TX.PT));
}
/* public convoy */
void PCdisplayVT(void* PC);
struct PCvtable
{
void (*display)(void*);
} PCvtable = {&PCdisplayVT};
typedef struct
{
PublicTransport PT;
PublicTransport* m_pt1;
PublicTransport* m_pt2;
Minibus m_m;
Taxi m_t;
} PublicConvoy;
void PCctor(PublicConvoy* PC)
{
PTctor(&PC->PT);
(void*)PC = &PCvtable;
PC->m_pt1 = malloc(sizeof(Minibus));
MBctor((Minibus*)PC->m_pt1);
PC->m_pt2= malloc(sizeof(Taxi));
TXctor((Taxi*)PC->m_pt2);
MBctor(&PC->m_m);
TXctor(&PC->m_t);
}
void PCcctor(PublicConvoy* PC, const PublicConvoy* other)
{
PTcctor(&PC->PT, &other->PT);
PC->m_pt1 = other->m_pt1;
PC->m_pt2 = other->m_pt2;
MBcctor(&PC->m_m, &other->m_m);
TXcctor(&PC->m_t, &other->m_t);
(void*)PC = &PCvtable;
}
void PCdtor(PublicConvoy* PC)
{
(void*)PC = &PCvtable;
MBdtor((Minibus*)PC->m_pt1);
free(PC->m_pt1);
TXdtor((Taxi*)PC->m_pt2);
free(PC->m_pt2);
TXdtor(&PC->m_t);
MBdtor(&PC->m_m);
PTdtor(&PC->PT);
}
void PCdisplayVT(void* PC)
{
((struct MBvtable*)(((PublicConvoy*)PC)->m_pt1->vptr))->display(((PublicConvoy*)PC)->m_pt1);
((struct TXvtable*)(((PublicConvoy*)PC)->m_pt2->vptr))->display(((PublicConvoy*)PC)->m_pt2);
((struct MBvtable*)(((PublicConvoy*)PC)->m_m.PT.vptr))->display(&((PublicConvoy*)PC)->m_m);
((struct TXvtable*)(((PublicConvoy*)PC)->m_t.PT.vptr))->display(&((PublicConvoy*)PC)->m_t);
}
/* main */
int main()
{
Minibus m;
MBctor(&m);
print_info_MB(&m);
{
PublicTransport tmp;
print_info_INT_and_cpy(3, &tmp);
((struct PTvtable*)(tmp.vptr))->display(&tmp);
PTdtor(&tmp);
}
PublicTransport* array[3];
array[0] = (PublicTransport*)malloc(sizeof(Minibus));
MBctor((Minibus*)array[0]);
array[1] = (PublicTransport*)malloc(sizeof(Taxi));
TXctor((Taxi*)array[1]);
array[2] = (PublicTransport*)malloc(sizeof(Minibus));
MBctor((Minibus*)array[2]);
((struct MBvtable*)(array[0]->vptr))->display(array[0]);
((struct TXvtable*)(array[1]->vptr))->display(array[1]);
((struct MBvtable*)(array[2]->vptr))->display(array[2]);
MBdtor((Minibus*)array[0]);
free(array[0]);
TXdtor((Taxi*)array[1]);
free(array[1]);
MBdtor((Minibus*)array[2]);
free(array[2]);
PublicTransport arr2[3];
{
Minibus tmp2;
MBctor(&tmp2);
PTcctor(&arr2[0], &tmp2.PT);
MBdtor(&tmp2);
}
{
Taxi tmp3;
TXctor(&tmp3);
PTcctor(&arr2[1], &tmp3.PT);
TXdtor(&tmp3);
}
PTctor(&arr2[2]);
((struct PTvtable*)(arr2[0].vptr))->display(&arr2[0]);
((struct PTvtable*)(arr2[1].vptr))->display(&arr2[1]);
((struct PTvtable*)(arr2[2].vptr))->display(&arr2[2]);
print_info_PT(&arr2[0]);
print_count();
Minibus m2;
MBctor(&m2);
print_count();
Minibus arr3[4];
for (int i = 0; i < 4; ++i)
{
MBctor(&arr3[i]);
}
Taxi* arr4 = (Taxi*)malloc(sizeof(Taxi) * 4);
for (int i = 0; i < 4; ++i)
{
TXctor(&arr4[i]);
}
for (int i = 3; i >= 0; --i)
{
TXdtor(&arr4[i]);
}
free(arr4);
printf("%d\n", ((1 > 2) ? (1) : (2)));
printf("%d\n", ((1 > (int(2.0f)) ? (1) : (int(2.0f))));
SpecialTaxi st;
STXctor(&st);
{
Taxi tmp4;
TXcctor(&tmp4, &st.TX);
taxi_display(tmp4);
TXdtor(&tmp4);
}
PublicConvoy* ts1 = malloc(sizeof(PublicConvoy));
PCctor(ts1);
PublicConvoy* ts2 = malloc(sizeof(PublicConvoy));
PCcctor(ts2, ts1);
((struct PCvtable*)(ts1->PT.vptr))->display(ts1);
((struct PCvtable*)(ts2->PT.vptr))->display(ts2);
PCdtor(ts1);
free(ts1);
((struct PCvtable*)(ts2->PT.vptr))->display(ts2);
PCdtor(ts2);
free(ts2);
STXdtor(&st);
for (int i = 4; i >= 0; --i)
{
MBdtor(&arr3[i]);
}
MBdtor(&m2);
for (int i = 4; i >= 0; --i)
{
PTdtor(&arr2[i]);
}
MBdtor(&m);
return 0;
}
|
C | /**
* @file chacha20_poly1305.c
* @brief ChaCha20Poly1305 AEAD
*
* @section License
*
* Copyright (C) 2010-2017 Oryx Embedded SARL. All rights reserved.
*
* This file is part of CycloneCrypto Open.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @author Oryx Embedded SARL (www.oryx-embedded.com)
* @version 1.8.0
**/
//Switch to the appropriate trace level
#define TRACE_LEVEL CRYPTO_TRACE_LEVEL
//Dependencies
#include "crypto.h"
#include "chacha.h"
#include "poly1305.h"
#include "aead/chacha20_poly1305.h"
#include "debug.h"
//Check crypto library configuration
#if (CHACHA20_POLY1305_SUPPORT == ENABLED)
/**
* @brief Authenticated encryption using ChaCha20Poly1305
* @param[in] k key
* @param[in] kLen Length of the key
* @param[in] n Nonce
* @param[in] nLen Length of the nonce
* @param[in] a Additional authenticated data
* @param[in] aLen Length of the additional data
* @param[in] p Plaintext to be encrypted
* @param[out] c Ciphertext resulting from the encryption
* @param[in] length Total number of data bytes to be encrypted
* @param[out] t MAC resulting from the encryption process
* @param[in] tLen Length of the MAC
* @return Error code
**/
error_t chacha20Poly1305Encrypt(const uint8_t *k, size_t kLen,
const uint8_t *n, size_t nLen, const uint8_t *a, size_t aLen,
const uint8_t *p, uint8_t *c, size_t length, uint8_t *t, size_t tLen)
{
error_t error;
size_t paddingLen;
ChachaContext chachaContext;
Poly1305Context poly1305Context;
uint8_t temp[32];
//Check the length of the message-authentication code
if(tLen != 16)
return ERROR_INVALID_LENGTH;
//Initialize ChaCha20 context
error = chachaInit(&chachaContext, 20, k, kLen, n, nLen);
//Any error to report?
if(error)
return error;
//First, a Poly1305 one-time key is generated from the 256-bit key
//and nonce
chachaCipher(&chachaContext, NULL, temp, 32);
//The other 256 bits of the Chacha20 block are discarded
chachaCipher(&chachaContext, NULL, NULL, 32);
//Next, the ChaCha20 encryption function is called to encrypt the
//plaintext, using the same key and nonce
chachaCipher(&chachaContext, p, c, length);
//Initialize the Poly1305 function with the key calculated above
poly1305Init(&poly1305Context, temp);
//Compute MAC over the AAD
poly1305Update(&poly1305Context, a, aLen);
//If the length of the AAD is not an integral multiple of 16 bytes,
//then padding is required
if((aLen % 16) != 0)
{
//Compute the number of padding bytes
paddingLen = 16 - (aLen % 16);
//The padding is up to 15 zero bytes, and it brings the total
//length so far to an integral multiple of 16
cryptoMemset(temp, 0, paddingLen);
//Compute MAC over the padding
poly1305Update(&poly1305Context, temp, paddingLen);
}
//Compute MAC over the ciphertext
poly1305Update(&poly1305Context, c, length);
//If the length of the ciphertext is not an integral multiple of 16 bytes,
//then padding is required
if((length % 16) != 0)
{
//Compute the number of padding bytes
paddingLen = 16 - (length % 16);
//The padding is up to 15 zero bytes, and it brings the total
//length so far to an integral multiple of 16
cryptoMemset(temp, 0, paddingLen);
//Compute MAC over the padding
poly1305Update(&poly1305Context, temp, paddingLen);
}
//Encode the length of the AAD as a 64-bit little-endian integer
STORE64LE(aLen, temp);
//Compute MAC over the length field
poly1305Update(&poly1305Context, temp, sizeof(uint64_t));
//Encode the length of the ciphertext as a 64-bit little-endian integer
STORE64LE(length, temp);
//Compute MAC over the length field
poly1305Update(&poly1305Context, temp, sizeof(uint64_t));
//Compute message-authentication code
poly1305Final(&poly1305Context, t);
//Successful encryption
return NO_ERROR;
}
/**
* @brief Authenticated decryption using ChaCha20Poly1305
* @param[in] k key
* @param[in] kLen Length of the key
* @param[in] n Nonce
* @param[in] nLen Length of the nonce
* @param[in] a Additional authenticated data
* @param[in] aLen Length of the additional data
* @param[in] c Ciphertext to be decrypted
* @param[out] p Plaintext resulting from the decryption
* @param[in] length Total number of data bytes to be decrypted
* @param[in] t MAC to be verified
* @param[in] tLen Length of the MAC
* @return Error code
**/
error_t chacha20Poly1305Decrypt(const uint8_t *k, size_t kLen,
const uint8_t *n, size_t nLen, const uint8_t *a, size_t aLen,
const uint8_t *c, uint8_t *p, size_t length, const uint8_t *t, size_t tLen)
{
error_t error;
size_t paddingLen;
ChachaContext chachaContext;
Poly1305Context poly1305Context;
uint8_t temp[32];
//Check the length of the message-authentication code
if(tLen != 16)
return ERROR_INVALID_LENGTH;
//Initialize ChaCha20 context
error = chachaInit(&chachaContext, 20, k, kLen, n, nLen);
//Any error to report?
if(error)
return error;
//First, a Poly1305 one-time key is generated from the 256-bit key
//and nonce
chachaCipher(&chachaContext, NULL, temp, 32);
//The other 256 bits of the Chacha20 block are discarded
chachaCipher(&chachaContext, NULL, NULL, 32);
//Initialize the Poly1305 function with the key calculated above
poly1305Init(&poly1305Context, temp);
//Compute MAC over the AAD
poly1305Update(&poly1305Context, a, aLen);
//If the length of the AAD is not an integral multiple of 16 bytes,
//then padding is required
if((aLen % 16) != 0)
{
//Compute the number of padding bytes
paddingLen = 16 - (aLen % 16);
//The padding is up to 15 zero bytes, and it brings the total
//length so far to an integral multiple of 16
cryptoMemset(temp, 0, paddingLen);
//Compute MAC over the padding
poly1305Update(&poly1305Context, temp, paddingLen);
}
//Compute MAC over the ciphertext
poly1305Update(&poly1305Context, c, length);
//If the length of the ciphertext is not an integral multiple of 16 bytes,
//then padding is required
if((length % 16) != 0)
{
//Compute the number of padding bytes
paddingLen = 16 - (length % 16);
//The padding is up to 15 zero bytes, and it brings the total
//length so far to an integral multiple of 16
cryptoMemset(temp, 0, paddingLen);
//Compute MAC over the padding
poly1305Update(&poly1305Context, temp, paddingLen);
}
//Encode the length of the AAD as a 64-bit little-endian integer
STORE64LE(aLen, temp);
//Compute MAC over the length field
poly1305Update(&poly1305Context, temp, sizeof(uint64_t));
//Encode the length of the ciphertext as a 64-bit little-endian integer
STORE64LE(length, temp);
//Compute MAC over the length field
poly1305Update(&poly1305Context, temp, sizeof(uint64_t));
//Compute message-authentication code
poly1305Final(&poly1305Context, temp);
//Finally, we decrypt the ciphertext
chachaCipher(&chachaContext, c, p, length);
//The calculated tag is bitwise compared to the received tag. The
//message is authenticated if and only if the tags match
if(cryptoMemcmp(temp, t, tLen))
return ERROR_FAILURE;
//Successful encryption
return NO_ERROR;
}
#endif
|
C | #include <stdio.h>
int main(void){
printf("input the kuatuo water:\n");
int kuatuo;
scanf("%d", &kuatuo);
double waters = 0;
waters = kuatuo * 950 / (3.0e-23);
printf("%d kuatuo is %e waters\n", kuatuo, waters);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(const char *msg) { perror(msg); exit(2); } // Error function used for reporting issues
int main(int argc, char const *argv[])
{
// checks if too few arguments were given
if (argc < 4)
{
fprintf(stderr, "Not enough arguments\n");
exit(1);
}
// opens files to read
int fdCipherText = open(argv[1], O_RDONLY);
int fdKey = open(argv[2], O_RDONLY);
// checks if both files were opened properly
if (fdCipherText == -1 || fdKey == -1)
{
fprintf(stderr, "Failed to open files\n");
exit(1);
}
// variables to store data from files
char cipherText[80000];
char key[80000];
memset(cipherText, '\0', sizeof(cipherText));
memset(key, '\0', sizeof(key));
// read cipher text
if (read(fdCipherText, cipherText, sizeof(cipherText)) == -1)
{
fprintf(stderr, "Failed to read plain text\n");
exit(1);
}
// read key text
if (read(fdKey, key, sizeof(key)) == -1)
{
fprintf(stderr, "Failed to read plain text\n");
exit(1);
}
// get rid of extra newlines at the end of strings
cipherText[strlen(cipherText) - 1] = '\0';
key[strlen(key) - 1] = '\0';
// get length of strings and check if key is shorter than cipher
int cipherTextLength = strlen(cipherText);
int keyLength = strlen(key);
if (cipherTextLength > keyLength)
{
fprintf(stderr, "Key is shorter than plain text\n");
exit(1);
}
// checks if cipher has only valid characters
char c;
int i;
for (i = 0; i < cipherTextLength; ++i)
{
c = cipherText[i];
if (isupper(c) || isspace(c))
{
// do nothing
}
else
{
fprintf(stderr, "Invalid characters in cipher text\n");
exit(1);
}
}
// checks if key has only valid characters
for (i = 0; i < keyLength; ++i)
{
c = key[i];
if (isupper(c) || isspace(c))
{
// do nothing
}
else
{
fprintf(stderr, "Invalid characters in key\n");
exit(1);
}
}
// creates signature for server to identify who client is
char signature[] = "otp_dec";
// variable to hold message to send
char message[200000];
memset(message, '\0', sizeof(message));
// combines all strings into one string to send
sprintf(message, "%s$%s$%s", cipherText, key, signature);
// client network stuff
int socketFD, portNumber, charsWritten, charsRead;
struct sockaddr_in serverAddress;
struct hostent* serverHostInfo;
char buffer[80000];
// Set up the server address struct
memset((char*)&serverAddress, '\0', sizeof(serverAddress)); // Clear out the address struct
portNumber = atoi(argv[3]); // Get the port number, convert to an integer from a string
serverAddress.sin_family = AF_INET; // Create a network-capable socket
serverAddress.sin_port = htons(portNumber); // Store the port number
serverHostInfo = gethostbyname("localhost"); // Convert the machine name into a special form of address
if (serverHostInfo == NULL) { fprintf(stderr, "CLIENT: ERROR, no such host\n"); exit(0); }
memcpy((char*)&serverAddress.sin_addr.s_addr, (char*)serverHostInfo->h_addr, serverHostInfo->h_length); // Copy in the address
// Set up the socket
socketFD = socket(AF_INET, SOCK_STREAM, 0); // Create the socket
if (socketFD < 0) error("CLIENT: ERROR opening socket");
// Connect to server
if (connect(socketFD, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) < 0) // Connect socket to address
error("CLIENT: ERROR connecting");
// send message to server
charsWritten = 0;
int charsSentThisPass = 0;
do
{
charsSentThisPass = send(socketFD, &message, strlen(message), 0);
if (charsSentThisPass < 0)
{
fprintf(stderr, "Error writing to socket\n");
exit(1);
}
charsWritten += charsSentThisPass;
} while (charsWritten < strlen(message));
// receive message from server
memset(message, '\0', sizeof(message));
do
{
memset(buffer, '\0', sizeof(buffer));
charsRead = recv(socketFD, buffer, sizeof(buffer), 0); // Read the client's message from the socket
if (charsRead < 0) error("ERROR reading from socket");
strcat(message, buffer);
} while (message[strlen(message)-1] != '\n');
// checks if response from from correct server
if (message[0] == '\n')
{
fprintf(stderr, "Tried connecting to wrong server\n");
exit(2);
}
else
{
printf("%s", message); // prints out cipher text
}
close(socketFD); // Close the socket
return 0;
} |
C | #include <stdio.h>
int AB[26];
int T,a,b;
char s1[1<<20];
void build(int a,int b){
int temp=0;
for (int i=0;i<26; i++){
temp = (a*i+b)%26;
AB[i] =temp;
}
}
int main()
{
freopen("data.txt","r",stdin);
scanf("%d", &T) ;
for (int i = T; i; i--){
scanf("%d %d",&a,&b);
scanf("%s",s1);
build(a,b);
for (int j=0;s1[j]; j++){
s1[j]= (a*(s1[j]-'A')+b)%26 + 'A';
}
puts(s1);
}
} |
C | // Number of pictures to take
#define shots 1000
// How far to advance between shots
// 128 steps == 1 mark on the fine control == 1 micron
#define MICRON 128L
#define distance (100 * MICRON)
//Declare pin functions on Arduino
#define stp 2
#define dir 3
#define fire 13
void setup() {
pinMode(stp, OUTPUT);
pinMode(dir, OUTPUT);
pinMode(fire, OUTPUT);
digitalWrite(stp, LOW);
digitalWrite(dir, HIGH);
Serial.begin(9600); //Open Serial connection for debugging
}
//Main loop
void loop() {
long int i, j;
char input;
Serial.println("Press Enter to start");
do {
input = Serial.read();
} while (input != '\n');
for (i = 0; i < shots; i++) {
trigger();
for (j = 0; j < distance; j++) {
step();
}
}
}
// Power on the IR trigger circuit to fire the camera
void trigger()
{
delay(1000); // wait for vibration to settle
digitalWrite(fire, HIGH); // take the picture
delay(1000); // wait for that to happen
digitalWrite(fire, LOW); // disable the IR circuit again
}
// Advance the motor by one step
void step()
{
digitalWrite(stp, HIGH); //Trigger one step forward
delayMicroseconds(25);
digitalWrite(stp, LOW); //Pull step pin low so it can be triggered again
delayMicroseconds(25);
}
|
C | /*
* ported the V7 rm
*
* cmd/rm/rm.c
* Changed: <2022-01-06 16:38:16 curt>
*/
int errcode = 0;
#include <stdio.h>
#include <types.h>
#include <sys/fs.h>
#include <sys/stat.h>
#include <sys/dir.h>
char *sprintf();
main(argc, argv)
char *argv[];
{
register char *arg;
int fflg, iflg, rflg;
fflg = 0;
if (isatty(0) == 0)
fflg++;
iflg = 0;
rflg = 0;
if (argc > 1 && argv[1][0] == '-') {
arg = *++argv;
argc--;
while (*++arg != '\0')
switch (*arg) {
case 'f':
fflg++;
break;
case 'i':
iflg++;
break;
case 'r':
rflg++;
break;
default:
printf("rm: unknown option %s\n", *argv);
exit(1);
}
}
while (--argc > 0) {
if (!strcmp(*++argv, "..")) {
fprintf(stderr, "rm: cannot remove `..'\n");
continue;
}
rm(*argv, fflg, rflg, iflg, 0);
}
exit(errcode);
}
rm(arg, fflg, rflg, iflg, level)
char arg[];
{
struct stat buf;
struct dir direct;
char name[100];
int d;
if (stat(arg, &buf)) {
if (fflg == 0) {
printf("rm: %s nonexistent\n", arg);
++errcode;
}
return;
}
if ((buf.st_mode & S_IFMT) == S_IFDIR) {
if (rflg) {
if (access(arg, 02) < 0) {
if (fflg == 0)
printf("%s not changed\n", arg);
errcode++;
return;
}
if (iflg && level != 0) {
printf("directory %s: ", arg);
if (!yes())
return;
}
if ((d = open(arg, 0)) < 0) {
printf("rm: %s: cannot read\n", arg);
exit(1);
}
while (read(d, (char *) &direct,
sizeof(direct)) == sizeof(direct)) {
if (direct.ino != 0 && !dotname(direct.name)) {
sprintf(name, "%s/%.14s", arg, direct.name);
rm(name, fflg, rflg, iflg, level + 1);
}
}
close(d);
errcode += rmdir(arg, iflg);
return;
}
printf("rm: %s directory\n", arg);
++errcode;
return;
}
if (iflg) {
printf("%s: ", arg);
if (!yes())
return;
} else if (!fflg) {
if (access(arg, 02) < 0) {
printf("rm: %s %o mode ", arg, buf.st_mode & 0777);
if (!yes())
return;
}
}
if (unlink(arg) && (fflg == 0 || iflg)) {
printf("rm: %s not removed\n", arg);
++errcode;
}
}
dotname(s)
char *s;
{
if (s[0] == '.')
if (s[1] == '.')
if (s[2] == '\0')
return (1);
else
return (0);
else if (s[1] == '\0')
return (1);
return (0);
}
rmdir(f, iflg)
char *f;
{
int status, i;
char namebuf[100];
sprintf(namebuf, "%s/..", f);
status = 0;
if (dotname(f))
return (0);
if (iflg) {
printf("%s: ", f);
if (!yes())
return (0);
}
status += unlink(namebuf);
i = strlen(namebuf);
namebuf[i] = '\0';
status += unlink(namebuf);
status += unlink(f);
return status;
}
yes()
{
int i, b;
i = b = getchar();
while (b != '\n' && b != EOF)
b = getchar();
return (i == 'y');
}
/*
* vim: tabstop=4 shiftwidth=4 expandtab:
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.