language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
int main(void) {
int i, j,k;
int n1,n2,n3,cnt=0;
scanf("%d %d %d", &n1,&n2,&n3);
for(i=0; i< n1; i++){
for(j=0; j< n2; j++){
for(k=0; k< n3; k++) {
printf("%d %d %d\n",i,j,k);
cnt++;
}
}
}
printf("%d",cnt);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: avivien <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/15 18:24:00 by avivien #+# #+# */
/* Updated: 2020/11/15 18:24:03 by avivien ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
#include <stdio.h>
int ft_printcontent(t_print *new, va_list ap)
{
if (new->targ == 'c')
return (ft_print_c(new, ap));
if (new->targ == 's')
return (ft_print_s(new, ap));
if (new->targ == 'p')
return (ft_print_p(new, ap));
if (new->targ == 'u')
return (ft_print_u(new, ap));
if (new->targ == '%')
return (ft_print_proc(new));
if (new->targ == 'd' || new->targ == 'i')
return (ft_print_di(new, ap));
if (new->targ == 'x' || new->targ == 'X')
return (ft_print_xx(new, ap));
return (-1);
}
int parser_2(const char *s, t_print *new, va_list ap, int i)
{
if (s[i] == '.')
{
i++;
new->toch = 0;
while (s[i] >= '0' && s[i] <= '9')
new->toch = new->toch * 10 + (s[i++] - '0');
if (s[i] == '*')
{
new->toch = va_arg(ap, int);
i++;
}
}
if (s[i] == 'c' || s[i] == 's' || s[i] == 'p' || s[i] == 'd' ||
s[i] == 'i' || s[i] == 'u' || s[i] == 'x' || s[i] == 'X' || s[i] == '%')
new->targ = s[i++];
return (i);
}
void addnew(t_print *new)
{
new->flag = '!';
new->shir = 0;
new->toch = -1;
}
int parser(const char *s, va_list ap, int i)
{
t_print *new;
int temp;
int ret;
if (!(new = malloc(sizeof(t_print))))
return (-1);
addnew(new);
while (s[i] == '-' || s[i] == '0')
if (s[i++] && new->flag != '-')
new->flag = (unsigned char)s[i - 1];
while (s[i] >= '0' && s[i] <= '9')
new->shir = new->shir * 10 + (s[i++] - '0');
if (s[i] == '*')
{
temp = va_arg(ap, int);
new->shir = temp;
if (temp < 0)
addnew1(new, temp);
i++;
}
i = parser_2(s, new, ap, i);
ret = ft_printcontent(new, ap);
free(new);
return (ret);
}
int ft_printf(const char *str, ...)
{
va_list ap;
int ret;
int i;
int m;
i = 0;
m = 0;
ret = 0;
va_start(ap, str);
while (str[i])
{
if (str[i] == '%')
{
ret += parser(str, ap, ++i);
i += ft_sdvig(str, i);
}
else
{
write(1, &str[i++], 1);
m++;
}
}
va_end(ap);
return (ret + m);
}
|
C
|
#include <stdio.h>
int main()
{
int sum = 0;
for(int i = 0; i < 10; i++){
if(i % 2) continue; /*相当于if(i%2 != 0),跳过所有奇数*/
sum += i; /*迭代,加上所有偶数*/
}
printf("%d\n", sum);
}
/*c中,0表示False,所有非0的数表示True*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define N 27
int numPassengers = 3;
int numCars = 6;
struct Graph {
struct Node* head[N];
};
struct Node {
int dest, weight1,weight2,weight3;
int passenger;
struct Node* next;
};
struct Edge {
int src, dest, weight1,weight2,weight3;
};
struct Graph* createGraph(struct Edge edges[], int n)
{
unsigned i;
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
for (i = 0; i < N; i++)
graph->head[i] = NULL;
for (i = 0; i < n; i++)
{
int src = edges[i].src;
int dest = edges[i].dest;
int weight1 = edges[i].weight1;
int weight2 = edges[i].weight2;
int weight3 = edges[i].weight3;
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->dest = dest;
newNode->weight1 = weight1;
newNode->weight2 = weight2;
newNode->weight3 = weight3;
newNode->next = graph->head[src];
graph->head[src] = newNode;
}
return graph;
}
void printGraph(struct Graph* graph)
{
int i;
for (i = 0; i < N; i++)
{
struct Node* ptr = graph->head[i];
while (ptr != NULL)
{
printf("%d -> %d (%d)(%d)(%d)\t", i, ptr->dest, ptr->weight1,ptr->weight2,ptr->weight3);
ptr = ptr->next;
}
printf("\n");
}
}
int totalDist(struct Graph* graph,int path[],int size)
{
int dist = 0;
int i;
for (int i = 0; i <= size - 2; i++)
{
struct Node* ptr = graph->head[path[i]];
while (ptr != NULL && ptr->dest != path[i + 1])
{
ptr = ptr->next;
}
if(ptr!=NULL)
dist += ptr->weight1;
}
return dist;
}
int totalRc(struct Graph* graph, int path[], int size)
{
int dist = 0;
int i;
for (int i = 0; i <= size - 2; i++)
{
struct Node* ptr = graph->head[path[i]];
while (ptr != NULL && ptr->dest != path[i + 1])
{
ptr = ptr->next;
}
if (ptr != NULL)
dist += ptr->weight2;
}
return dist;
}
int totalTraffic(struct Graph* graph, int path[], int size)
{
int dist = 0;
int i;
for (int i = 0; i <= size - 2; i++)
{
struct Node* ptr = graph->head[path[i]];
while (ptr != NULL && ptr->dest != path[i + 1])
{
ptr = ptr->next;
}
if (ptr != NULL)
dist += ptr->weight3;
}
return dist;
}
int compare(float d1, float r1, float t1, float d2, float r2, float t2, float d2r,float d2t,float r2t) //AHP
{
float pathSelection[3][3] =
{ {1,d2r,d2t}, //shortest path
{1/d2r,1,r2t},
{1/d2t,1/r2t,1} };
float dist[2][2] = { {1,d2/d1},{d1 / d2,1 } }; //shorter dist
float rc[2][2] = { {1,r1 / r2},{r2 / r1,1 } }; //better rd condition
float traffic[2][2] = { {1,(float)t2/t1},{(float)t1/t2,1 } };//lesser traffic
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
//printf("matrix == %f", dist[i][j]);
}
}
float colSum1[2];
float colSum2[2];
float colSum3[2];
float colSumPath[3];
float priorityVec1[2];
float priorityVec2[2];
float priorityVec3[2];
float priorityVecPath[3];
float sum1 = 0;
float sum2 = 0;
float sum3 = 0;
float sumPath = 0;
for (int j = 0; j < 2; j++)
{
colSum1[j] = 0;
colSum2[j] = 0;
colSum3[j] = 0;
priorityVec1[j] = 0;
}
for (int i = 0; i < 3; i++)
{
colSumPath[i] = 0;
priorityVecPath[i] = 0;
}
for (int i = 0; i < 2; i++) // i here is looooooop for column
{
for (int j = 0; j < 2; j++)
{
colSum1[i] += dist[j][i];
}
for (int j = 0; j < 2; j++)
{
dist[j][i] /= colSum1[i];
}
}
for (int i = 0; i < 2; i++) // i here is looooooop for column
{
for (int j = 0; j < 2; j++)
{
colSum2[i] += rc[j][i];
}
for (int j = 0; j < 2; j++)
{
rc[j][i] /= colSum2[i];
}
}
for (int i = 0; i < 2; i++) // i here is looooooop for column
{
for (int j = 0; j < 2; j++)
{
colSum3[i] += traffic[j][i];
}
for (int j = 0; j < 2; j++)
{
traffic[j][i] /= colSum3[i];
}
}
for (int i = 0; i < 3; i++) // i here is looooooop for column
{
for (int j = 0; j < 3; j++)
{
colSumPath[i] += pathSelection[j][i];
}
for (int j = 0; j < 3; j++)
{
pathSelection[j][i] /= colSumPath[i];
}
}
//for dist
for (int j = 0; j < 2; j++)
{
priorityVec1[j] = 0;
}
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
priorityVec1[i] += dist[i][j];
}
}
for (int j = 0; j < 2; j++)
{
priorityVec1[j] /= 2;
sum1 += priorityVec1[j]; //sum is always 1
}
//printf("sum of priority vec for dist matrix %f \n", sum1);
//for rc
for (int j = 0; j < 2; j++)
{
priorityVec2[j] = 0;
}
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
priorityVec2[i] += rc[i][j];
}
}
for (int j = 0; j < 2; j++)
{
priorityVec2[j] /= 2;
sum2 += priorityVec2[j]; //sum is always 1
}
//printf("sum of priority vec for rc matrix %f \n", sum2);
//for traffic
for (int j = 0; j < 2; j++)
{
priorityVec3[j] = 0;
}
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
priorityVec3[i] += traffic[i][j];
}
}
for (int j = 0; j < 2; j++)
{
priorityVec3[j] /= 2;
sum3 += priorityVec3[j]; //sum is always 1
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
priorityVecPath[i] += pathSelection[i][j];
}
}
for (int j = 0; j < 3; j++)
{
priorityVecPath[j] /= 3; //avg
sumPath += priorityVecPath[j]; //sum is always 1
}
float num1 = priorityVec1[0] * priorityVecPath[0] + priorityVec2[0] * priorityVecPath[1] + priorityVec3[0] * priorityVecPath[2];
float num2 = priorityVec1[1] * priorityVecPath[0] + priorityVec2[1] * priorityVecPath[1] + priorityVec3[1] * priorityVecPath[2];
//printf("\n\n num1 :: %f ", num1);
//printf("\n\n num1 :: %f ", num2);
float compo[2] = {num1,num2};
if (num1 >= num2)
{
return 1;
}
else
{
return 2;
}
}
int main(void)
{
struct Edge edges[] =
{
{1,2,1,4,6},{1,3,9,8,5},{1,4,1,1,2},{2,5,5,8,1},{3,6,5,2,1},{3,7,2,3,4},{4,8,1,5,5},{5,9,5,8,9},{5,10,1,2,3},{6,11,3,8,6},{7,11,4,5,9},{8,12,4,5,1},{9,13,2,7,8},{13,16,3,9,7},{10,16,3,1,2},{11,14,7,8,1},{12,15,4,5,6},{14,17,5,5,6},{17,20,3,2,1},{17,21,1,1,2},{17,22,1,1,5},{15,18,1,6,8},{16,19,2,2,1},{20,24,1,2,5},{21,24,6,2,1},{22,24,3,4,1},{18,25,1,5,2},{15,23,2,6,8},{19,26,4,1,3},{24,26,3,7,2},{25,26,2,4,8},{23,26,6,7,8}
};
//changing 15 23 2 6 8 to 15 23 2 6 1
//changing 23 26 6 7 8 to 23 26 6 7 1
//21 24 2 2 1 to 21 34 6 2 1
// calculate number of edges
int n = sizeof(edges) / sizeof(edges[0]);
printf("Number of cars :: 6 \n" );
printf("Numbers of Passengers in waiting:: 3 \n");
float p2D2R = 1/5, p2D2T = 1/9, p2R2T = 1/9;
float p3D2R = 1/9, p3D2T = 1/9, p3R2T = 9;
int newCar1[5];
int newCar2[6];
int newCar3[4];
int newCar4[4];
int newCar5[3];
int newCar6[4];
int capacity[] = { 4,4,4,4,4,4 };//for 6 cars
int car1[] = { 1,2,5,10,16,19,26 };
int size1 = sizeof(car1) / sizeof(car1[0]);
int car2[] = { 1,2,5,9,13,16,19,26 };
int size2 = sizeof(car2) / sizeof(car2[0]);
int car3[] = { 1,3,6,11,14,17,21,24,26 };
int size3 = sizeof(car3) / sizeof(car3[0]);
int car4[] = { 1,3,6,11,14,17,22,24,26 };
int size4 = sizeof(car4) / sizeof(car4[0]);
int car5[] = { 12,15,23,26 };
int size5= sizeof(car5) / sizeof(car5[0]);
int car6[] = { 12,15,18,25,26 };
printf("\nEnter nodes car 7 will cover:: ");
int size6 = sizeof(car6) / sizeof(car6[0]);
int passenger1 = 5;//car1car2
int passenger2 = 17;//car3car4
int passenger3 = 15;//car5car6
int passenger4 = 17;//c3c4
int passenger5 = 12;//c5c6
int passenger6 = 5;//c1c2
int passenger7 = 5;//c1c2
int newCar31[5];
int newCar41[5];
int point1,point2,point3,point4,point5,point6;
struct Graph* graph = createGraph(edges, n);
printf("Position of Passengers :: \n");
printf("P1 :: %d \t",passenger1);
printf("P2 :: %d \t", passenger2);
printf("P3 :: %d \t", passenger3);
printf("P4 :: %d \t", passenger4);
printf("P5 :: %d \t", passenger5);
printf("P6 :: %d \t", passenger6);
printf("P7 :: %d \t", passenger7);
printGraph(graph);
for (int i = 0; i <= 5; i++)
{
printf("\n\n Capacity of car%d = %d", i + 1, capacity[i]);
}
printf("\nPath of Car1:: \n\n");
for (int i = 0; i < size1; i++)
{
printf("%d-> ", car1[i]);
}
printf("\n\nPath of Car2:: \n\n");
for (int i = 0; i < size2; i++)
{
printf("%d-> ", car2[i]);
}
printf("\n\nPath of Car3:: \n\n");
for (int i = 0; i < size3; i++)
{
printf("%d-> ", car3[i]);
}
printf("\n\nPath of Car4:: \n\n");
for (int i = 0; i < size4; i++)
{
printf("%d-> ", car4[i]);
}
printf("\n\nPath of Car5:: \n\n");
for (int i = 0; i < size5; i++)
{
printf("%d-> ", car5[i]);
}
printf("\n\nPath of Car6:: \n\n");
for (int i = 0; i < size6; i++)
{
printf("%d-> ", car6[i]);
}
for (int i = 0; i < size1; i++)
{
if (car1[i] == passenger1)
{
point1 = i;
}
}
int p = 0, q = 0, r = 0,s=0,t=0,u=0;
for (int i = point1; i < size1; i++)
{
newCar1[p++] = car1[i];
}
//car2
for (int i = 0; i < size2; i++)
{
if (car2[i] == passenger1)
{
point2 = i;
}
}
for (int i = point2; i < size2; i++)
{
newCar2[q++] = car2[i];
}
//car3
for (int i = 0; i < size3; i++)
{
if (car3[i] == passenger2)
{
point3 = i;
}
}
for (int i = point3; i < size3; i++)
{
newCar3[r++] = car3[i];
}
//car4
for (int i = 0; i < size4; i++)
{
if (car4[i] == passenger2)
{
point4 = i;
}
}
for (int i = point4; i < size4; i++)
{
newCar4[s++] = car4[i];
}
//car5
for (int i = 0; i < size5; i++)
{
if (car5[i] == passenger3)
{
point5 = i;
}
}
for (int i = point5; i < size5; i++)
{
newCar5[t++] = car5[i];
}
//car6
for (int i = 0; i < size6; i++)
{
if (car6[i] == passenger3)
{
point6 = i;
}
}
for (int i = point6; i < size6; i++)
{
newCar6[u++] = car4[i];
}
size1 = sizeof(newCar1) / sizeof(newCar1[0]);
for (int i =0; i < size1; i++)
{
//printf("\n\n%d", newCar1[i]);
}
size2 = sizeof(newCar2) / sizeof(newCar2[0]);
size5 = sizeof(newCar5) / sizeof(newCar5[0]);
size6 = sizeof(newCar6) / sizeof(newCar6[0]);
int dist1 = totalDist(graph, newCar1, 5);
int rc1 = totalRc(graph, newCar1, 5);
int traffic1 = totalTraffic(graph, newCar1, 5);
//printf("dist =%d", dist1);
int dist2 = totalDist(graph, newCar2, 6);
//printf("dist =%d", dist2);
int rc2 = totalRc(graph, newCar2, 6);
int traffic2 = totalTraffic(graph, newCar2, 6);
printf("\nPassenger1 has priority :: distanceToRoadCondition = 9 distanceToTraffic = 9 roadconditionToTraffic = 5");
int resultPassenger1 = compare(dist1, rc1, traffic1, dist2, rc2, traffic2,9,9,5);
if (resultPassenger1 == 1)
{
printf("\n\n\nPassenger 1 at 5 chooses car 1\n");
capacity[0]--;
}
else
{
printf("\n\n\nPassenger 1 at 5 chooses car 2\n");
capacity[1]--;
}
int dist3 = totalDist(graph, newCar3, 4);
int rc3 = totalRc(graph, newCar3, 4);
int traffic3 = totalTraffic(graph, newCar3, 4);
int dist4 = totalDist(graph, newCar4, 4);
int rc4 = totalRc(graph, newCar4, 4);
int traffic4 = totalTraffic(graph, newCar4, 4);
printf("\nPassenger2 has priority :: distanceToRoadCondition = 1/5 distanceToTraffic = 1/9 roadconditionToTraffic = 1/9");
resultPassenger1 = compare(dist3, rc3, traffic3, dist4, rc4, traffic4, (float)1 / 5, (float) 1 / 9, (float)1 / 9);
if (resultPassenger1 == 1)
{
printf("\n\nPassenger 2 at 17 chooses car 3");
capacity[2]--;
}
else
{
printf("\nPassenger 2 at 17 chooses car 4");
capacity[3];
}
int dist5 = totalDist(graph, newCar5,3 ),x =6;
int rc5 = totalRc(graph, newCar5, 3);
int traffic5 = totalTraffic(graph, newCar5, 3);
int dist6 = totalDist(graph, newCar6, 4);
int rc6 = totalRc(graph, newCar6, 4);
int traffic6 = totalTraffic(graph, newCar6, 4);
printf("\nPassenger3 has priority :: distanceToRoadCondition = 1/5 distanceToTraffic = 1/9 roadconditionToTraffic = 1/9");
resultPassenger1 = compare(dist5, rc5, traffic5, dist6, rc6, traffic6, (float)1 /5, (float)1 / 9, (float)1/9);
if (resultPassenger1 == 1)
{
printf("\n\nPassenger 3 at 15 chooses car 5\n\n");
capacity[4]--;
}
else
{
printf("\n\nPassenger 3 at 15 chooses car 6");
capacity[5];
}
//NEWCAR3CAR4
dist3 = totalDist(graph, newCar3, 4);
rc3 = totalRc(graph, newCar3, 4);
traffic3 = totalTraffic(graph, newCar3, 4);
dist4 = totalDist(graph, newCar4, 4);
rc4 = totalRc(graph, newCar4, 4);
traffic4 = totalTraffic(graph, newCar4, 4);
printf("\n\nPassenger4 has priority :: distanceToRoadCondition = 5 distanceToTraffic = 9 roadconditionToTraffic = 9");
resultPassenger1 = compare(dist3, rc3, traffic3, dist4, rc4, traffic4, (float) 5, (float) 9, (float)9);
if (resultPassenger1 == 1)
{
printf("\n\nPassenger 4 chooses car 3\n\n");
capacity[2]--;
}
else
{
printf("\nPassenger 4 chooses car 4\n\n");
capacity[3]--;
}
dist5 = totalDist(graph, car5, 5), x = 6;
rc5 = totalRc(graph, car5, 5);
traffic5 = totalTraffic(graph, car5, 5);
dist6 = totalDist(graph, car6, 6);
rc6 = totalRc(graph, car6, 6);
traffic6 = totalTraffic(graph, car6, 6);
printf("Passenger5 has priority :: distanceToRoadCondition = 5 distanceToTraffic = 9 roadconditionToTraffic = 9");
resultPassenger1 = compare(dist5, rc5, traffic5, dist6, rc6, traffic6, (float)5, (float)9, (float)9);
if (resultPassenger1 == 1)
{
printf("\n\nPassenger 5 at 17 chooses car 5\n\n");
capacity[4]--;
}
else
{
printf("\n\nPassenger 5 at 17 chooses car 6");
capacity[5]--;
}
printf("Passenger6 has priority :: distanceToRoadCondition = 1/9 distanceToTraffic = 1/9 roadconditionToTraffic = 5");
resultPassenger1 = compare(dist1, rc1, traffic1, dist2, rc2, traffic2, 1/9,1/9,5);
if (resultPassenger1 == 1)
{
printf("\n\n\nPassenger 6 at 12 chooses car 1\n");
capacity[0]--;
}
else
{
printf("\n\n\nPassenger 6 at 12 chooses car 2\n");
capacity[1]--;
}
//p6p7
printf("Passenger7 has priority :: distanceToRoadCondition = 1/9 distanceToTraffic = 9 roadconditionToTraffic = 9");
resultPassenger1 = compare(dist1, rc1, traffic1, dist2, rc2, traffic2, 1/9,9,9);
if (resultPassenger1 == 1)
{
printf("\n\n\nPassenger 7 at 5 chooses car 1\n");
capacity[0]--;
}
else
{
printf("\n\n\nPassenger 7 at 5 chooses car 2\n");
capacity[1]--;
}
for (int i = 0; i <= 5; i++)
{
printf("\n\n Capacity of car%d = %d", i + 1, capacity[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
int Ackermann(int m, int n){
if(m == 0)
return n + 1;
else if(n == 0)
return Ackermann(m - 1, 1);
else
return Ackermann(m - 1, Ackermann(m, n - 1));
}
int main(){
int m, n;
scanf("%d %d", &m, &n);
printf("%d", Ackermann(m, n));
return 0;
}
|
C
|
#include <stdio.h>
void ft_ultimate_ft(int *********nbr);
int main()
{
int n;
void *ps[9];
ps[0] = &n;
for (int i = 1; i < 9; ++i)
ps[i] = &ps[i-1];
ft_ultimate_ft(ps[8]);
printf("%i\n", n);
}
|
C
|
#include<stdio.h>
void main()
{
int a,i,j,k;
scanf("%d",&a);
for(i=a;i>=1;i--)
{
k=1;
for(j=1;j<=a;j++)
{
if (i<=j)
printf("%d",k++);
else
printf(" ");
}
printf("\n");
}
}
|
C
|
/*Implementa un programa que imprima un saludo simple para el usuario, como se muestra abajo.
$ ./hello
hello, world*/
#include "stdio.h"
int main(void){
printf("hello, world\n");
}
|
C
|
#ifndef _HASHTABLE_H
#define _HASHTABLE_H
/*Definitions for abstract hashtable */
struct htable_data;
typedef int boolean_t;
typedef struct htable_data* htable_t;
extern unsigned htable_num_eles(htable_t ht);
/* create and return new hashtable
else return null*/
extern htable_t htable_create();
/*destroy the table and free up all space */
extern void htable_destroy(htable_t ht);
/*add element to hashtable with a key
returns true if succeeded*/
extern boolean_t htable_add(htable_t ht, char* key, void* val);
/*remove key and val from hashtable
returns element */
extern boolean_t htable_remove(htable_t ht, char* key);
/* lookup if key is present in htable
return value if found else null */
extern void* htable_lookup(htable_t ht, char* key);
/* lookup if key is present in htable
return true if found else false */
extern boolean_t htable_ispresent(htable_t ht, char* key);
/* set the hash function of the table */
typedef int (*htable_hashfunc_t) (char* key);
extern void htable_set_hash(htable_t ht, htable_hashfunc_t hf);
/* set the equals function testing whether two keys are the same of the table. */
typedef int (*htable_equalsfunc_t) (void* e1, void* e2);
void htable_set_equals(htable_t ht, htable_equalsfunc_t ef);
#endif //_HASHTABLE_H
|
C
|
#include <stdio.h>
#include <stdint.h>
#include <NDL.h>
// extern int NDL_Init(uint32_t flags);
// extern void NDL_Quit();
// extern uint32_t NDL_GetTicks();
int main() {
NDL_Init(0);
uint32_t start = NDL_GetTicks() / 1000;
uint32_t now = NDL_GetTicks() / 1000;
while(now - start < 1) {
now = NDL_GetTicks() / 1000;
}
int i = now - start;
while (1)
{
now = NDL_GetTicks() / 1000;
if (now > i) {
printf("time is %d\n", now);
i++;
}
}
NDL_Quit();
return 0;
}
|
C
|
#include <GL/gl.h>
#include <GL/glext.h>
#include <H:/glut.h>
#include <math.h>
/*
This program illustrates the use of the Idle Callback,
in this case to carry out some animation.
It draws a rotating square.
*/
float theta = M_PI/4;
GLfloat x1,x2,yy1,yy2;
void display(void)
{
glClearColor(0.0,0.0,1.0,1.0);
glClear(GL_COLOR_BUFFER_BIT);
glPointSize(3.0);
glColor3f(1.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2f(x1,yy1);
glVertex2f(x1,yy2);
glVertex2f(x2,yy2);
glVertex2f(x2,yy1);
glEnd();
glFlush();
return;
}
void MyMouse(GLint button, GLint state, GLint x, GLint y)
{
static int first=1;
if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON)
{
if (first)
{
x1=(x-250.0)/250.0;
yy1=-(y-250)/250.0;;
}
else
{
x2=(x-250.0)/250.0;
yy2=-(y-250)/250.0;
glutPostRedisplay();
}
first = !first;
}
return;
}
void MyIdle()
{
theta += 0.01;
if (theta > 20111*M_PI) theta -= 2000*M_PI;
glutPostRedisplay();
return;
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitWindowSize(500,500);
glutInitWindowPosition(500,200);
glutCreateWindow("mouse");
glutDisplayFunc(display);
glutMouseFunc(MyMouse);
glutIdleFunc(MyIdle);
glutMainLoop();
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_rounding.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ramory-l <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/08 20:08:08 by idunaver #+# #+# */
/* Updated: 2019/06/15 15:33:24 by ramory-l ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
char *ft_replace_num_round(int check, long long accuracy,
char *result)
{
while (accuracy)
{
accuracy--;
check = result[accuracy] - '0';
check++;
if (check > 9)
{
result[accuracy] = 0 + '0';
check = result[accuracy] - '0';
}
else if (check != 9)
{
result[accuracy] = check + '0';
break ;
}
}
return (result);
}
char *ft_if_five_in_fractional(char *result,
int check, long long accuracy)
{
int check_null;
check_null = accuracy + 1;
while (result[check_null])
{
if (result[check_null] != '0')
break ;
check_null++;
}
if (result[check_null])
result = ft_replace_num_round(check, accuracy, result);
return (result);
}
char *ft_rounding_fraction(char *result, long long accuracy)
{
int check;
char *tmp;
long long accuracy_tmp;
check = 0;
tmp = result;
accuracy_tmp = accuracy + 1;
while (*tmp++)
accuracy_tmp--;
if (accuracy_tmp < 0)
{
check = result[accuracy] - '0';
if (check == 5)
result = ft_if_five_in_fractional(result, check, accuracy);
else if (check > 5)
result = ft_replace_num_round(check, accuracy, result);
}
return (result);
}
char *ft_rounding(char *result, long long accuracy)
{
char *tmp;
int before;
int after;
int count;
int check;
check = 0;
count = 0;
tmp = result;
while (*tmp != '.')
{
tmp++;
count++;
}
tmp++;
before = *tmp - '0';
tmp = ft_rounding_fraction(tmp, accuracy);
after = *tmp - '0';
if (before > after || (after >= 5 && accuracy == 0))
{
check = result[count] - '0';
result = ft_replace_num_round(check, count, result);
}
return (result);
}
|
C
|
#include <msp430.h>
#include "rand.h"
#include "dice.h"
#include "dual7_seg.h"
#include "lcd.h"
/* Function prototypes */
void gpio_init(void);
#define ROLL_SEM 0x01
#define PRINT_SEM 0x02
/* Indices in string that indicate how many faces we're rolling */
#define STR_DIG_1 10
#define STR_DIG_2 11
unsigned sem;
int main(void)
{
WDTCTL = WDTPW | WDTHOLD;
gpio_init();
/* Initialize a timer to make the 7-seg display 2 digits */
TACCR0 = SEVENSEG_REFRESH;
TACCR1 = SEVENSEG_REFRESH >> 1; /* Half of refresh interval */
TAIV = 0; /* Clear timer interrupts */
TACCTL0 |= CCIE; TACCTL1 |= CCIE; /* Enable timer interrupts */
TACTL = (MC_1 | TASSEL_2 | TAIFG | TACLR);
init_lcd();
sem = 0; /* No active semaphores */
unsigned const faces[NFACES] = { D20, D6, D8, D10, D12 };
static unsigned face_index = 1;
unsigned nfaces = D20; /* Initialize number of faces on die */
char nsides_str[] = "Rolling: D20";
lcd_print_str(nsides_str);
while(1) {
_BIS_SR(GIE | LPM1_bits); /* Wait for a button to be pressed */
switch (sem) {
case ROLL_SEM: roll(nfaces); break;
case PRINT_SEM:
nfaces = faces[face_index++];
if (nfaces < D10) {
nsides_str[STR_DIG_1] = '0' + nfaces;
nsides_str[STR_DIG_2] = ' ';
} else if (nfaces == D20) {
face_index = 1;
nsides_str[STR_DIG_1] = '2';
nsides_str[STR_DIG_2] = '0';
} else {
nsides_str[STR_DIG_1] = '1';
nsides_str[STR_DIG_2] = nfaces - 10 + '0';
}
lcd_clr_screen();
lcd_print_str(nsides_str);
break;
default: break;
}
}
}
/**
* gpio_init:
* Initializes GPIO on the MSP430G2452 for use as a dice roller
*/
void gpio_init(void)
{
/* Assign P2 to be general purpose outputs */
P2OUT = 0; P2SEL = 0; P2DIR = 0xFF;
P1DIR = LCD_PINS; P1OUT = 0;
/* Make P1.0 and P1.1 inputs w/ pull-up resistors */
P1DIR &= ~(BIT6 | BIT7);
P1REN |= (BIT6 | BIT7); P1OUT |= (BIT6 | BIT7); /* Add pull-up resisitor */
P1IE |= (BIT6 | BIT7); /* Enable interrupts */
P1IES |= (BIT6 | BIT7); /* Interrupt on falling edge */
P1IFG = 0; /* Clear any set interrupts */
return;
}
#define ROLL_BTN 0x40 /* Used to manipulate P1.0 */
/*
* PORT1_ISR
* The first time a button on Port 1 is pressed, the random number generator
* will get seeded.
* The button connected to P1.0 is used to roll the dice, and the button
* connected to P1.1 is used to cycle between the number of faces on the die
* getting rolled.
*/
#pragma vector = PORT1_VECTOR
__interrupt void PORT1_ISR(void)
{
static unsigned rand_seeded = 0;
P1IE &= ~(BIT6 | BIT7); /* Disable buttons until roll is over */
/* The first time a button is pressed, seed the random number generator */
if(!rand_seeded) {
srand(TAR); /* Seed with current value of TA */
rand_seeded = 1; /* We don't need to seed rand again */
}
/* Take action depending on which button was pressed */
if (P1IFG & ROLL_BTN) {
/* Roll button */
P1IFG = 0;
sem = ROLL_SEM;
_BIC_SR(LPM1_EXIT);
} else {
/* Next die button */
P1IFG = 0;
sem = PRINT_SEM;
_BIC_SR(LPM1_EXIT);
}
return;
}
|
C
|
#include<stdio.h>
#include<string.h>
int i,j,n,m;
int p[1000],check[1000];//判断刚刚进来的是等着还是晒着。
char s[500];
int main()
{
while(scanf("%d",&n),n)
{
memset(p,0,sizeof(p));
memset(check,0,sizeof(check));
scanf("%s",s);
m=0;
for (i=0;i<strlen(s);i++)
{
if (p[s[i]])
{
p[s[i]]=0;
if (!check[s[i]])n++;
else m++;
}
else
{
p[s[i]]=1;
if (n) n--;
else check[s[i]]=1;
}
}
if (m) printf("%d customer(s) walked away.\n",m);
else printf("All customers tanned successfully.\n");
}
return 0;
};
|
C
|
/*
* This file is part of the id3v2lib library
*
* Copyright (c) 2013, Lorenzo Ruiz
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "header.h"
#include "utils.h"
static inline int has_id3v2tag(const char *raw_header)
{
return (memcmp(raw_header, "ID3", 3) == 0);
}
ID3v2_header *get_tag_header(const char *file_name)
{
char buffer[ID3_HEADER];
FILE *file = fopen(file_name, "rb");
if (!file) {
perror("Error opening file");
return NULL;
}
fread(buffer, ID3_HEADER, 1, file);
fclose(file);
return get_tag_header_with_buffer(buffer, ID3_HEADER);
}
ID3v2_header *get_tag_header_with_buffer(const char *buffer, int length)
{
int position = 0;
ID3v2_header *tag_header;
if (length < ID3_HEADER) return NULL;
if (!has_id3v2tag(buffer)) return NULL;
tag_header = new_header();
memcpy(tag_header->tag, buffer, ID3_HEADER_TAG);
tag_header->orig_major_version = buffer[position += ID3_HEADER_TAG];
tag_header->major_version = buffer[position];
if (get_tag_orig_version(tag_header) == ID3v22) {
tag_header->major_version = 3;
}
tag_header->minor_version = buffer[position += ID3_HEADER_VERSION];
tag_header->flags = buffer[position += ID3_HEADER_REVISION];
tag_header->tag_size = syncint_decode(btoi(buffer, ID3_HEADER_SIZE, position += ID3_HEADER_FLAGS));
if (tag_header->flags & ID3_HEADER_FLAGS_HAS_UNSYNCHRONISATION) {
tag_header->unsynchronised = 1;
}
if (tag_header->flags & ID3_HEADER_FLAGS_HAS_EXTENDED_HEADER) {
// an extended header exists, so we retrieve the actual size of it and save it into the struct
tag_header->extended_header_size = syncint_decode(btoi(buffer, ID3_EXTENDED_HEADER_SIZE, position += ID3_HEADER_SIZE));
} else {
// no extended header existing
tag_header->extended_header_size = 0;
}
return tag_header;
}
int get_tag_version(ID3v2_header *tag_header)
{
switch (tag_header->major_version) {
case 3:
return ID3v23;
case 4:
return ID3v24;
default:
return NO_COMPATIBLE_TAG;
}
}
int get_tag_orig_version(ID3v2_header *tag_header)
{
switch (tag_header->orig_major_version) {
case 2:
return ID3v22;
case 3:
return ID3v23;
case 4:
return ID3v24;
default:
return NO_COMPATIBLE_TAG;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int Sequential_Search(int *a, int n, int key){
int i;
for(i = 0; i < n; i++){
if(a[i] == key){
return i;
}
}
return 0;
}
int Sequential_Search2(int *a, int n, int key){
int i;
a[0] = key;
i = n;
while(a[i] != key){
i--;
}
return i;
}
int main(){
printf("Hello World!");
return 0;
}
|
C
|
/* Startup and setup */
#include "main.h"
/* Size of buffer for reading lines from input file */
#define MAXLINELENGTH 128
/* Read points from input file to array in memory */
void input(char *path) {
FILE *f;
char inputLine[MAXLINELENGTH];
float x, y, e, maxe = 0.0;
int i, pointsSoFar = 0;
f = fopen(path, "r");
if(f == NULL) {
printf("Failed to open %s.\n", path);
exit(1);
}
while(fgets(inputLine, MAXLINELENGTH, f)) {
if(sscanf(inputLine, "slices %d", &state.sliceCount) == 1) {
/* Noop */
} else if(sscanf(inputLine, "points %d", &state.pointsPerSlice) == 1) {
state.data = (point_t *)malloc(state.sliceCount * state.pointsPerSlice * sizeof(point_t));
} else if(sscanf(inputLine, "%f %f %f", &x, &y, &e) == 3) {
/* Slice data is read in onto the XY plane, rotated into 3D later */
state.data[pointsSoFar].position.y = -y;
state.data[pointsSoFar].position.x = x;
state.data[pointsSoFar].position.z = 0.0;
state.data[pointsSoFar].e = e;
/* Track max e */
if(e > maxe) {
maxe = e;
}
/* Set the "sample size", which will be used to size splats */
state.data[pointsSoFar].r = 3.0 * (tan(M_PI / state.sliceCount) / 2.0) * fabs(x) * 2.0;
pointsSoFar++;
}
}
if(pointsSoFar == 0) {
printf("Failed to read any points. Are you sure this is a real .sli3 file?\n");
exit(1);
}
fclose(f);
/* Normalize error values to [0,1], avoiding division by zero */
if(maxe != 0.0) {
for(i = 0; i < state.sliceCount * state.pointsPerSlice; i++) {
state.data[i].e /= maxe;
}
}
}
/* Rotate each slice into its proper 3D position */
void rotateSlices(void) {
float radians, x;
int i;
for(i = 0; i < state.sliceCount * state.pointsPerSlice; i++) {
radians = (i / state.pointsPerSlice) * (M_PI / state.sliceCount) - M_PI / 2;
x = state.data[i].position.x;
state.data[i].position.x = x * cos(radians);
state.data[i].position.z = x * sin(radians);
x = state.data[i].normal.x;
state.data[i].normal.x = x * cos(radians);
state.data[i].normal.z = x * sin(radians);
normalise(&state.data[i].normal);
}
}
/* Window resize callback */
void size(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (float)width / (float)height, 0.1, 1000.0);
}
/* Render method-specific initialisation */
void renderInit(void) {
switch(state.renderMethod) {
case POINTS:
initPoints();
break;
case POINTNORMALS:
initPointnormals();
break;
case SPLATS:
initSplats();
break;
case SIZEDSPLATS:
initSizedSplats();
break;
}
glutPostRedisplay();
}
/* Render method-specific teardown */
void renderUninit(void) {
switch(state.renderMethod) {
case POINTS:
uninitPoints();
break;
case POINTNORMALS:
uninitPointnormals();
break;
case SPLATS:
uninitSplats();
break;
case SIZEDSPLATS:
uninitSizedSplats();
break;
}
}
/* Window damage/redraw callback */
void draw(void) {
vector3_t up, right;
/* Clear the window */
glClearColor(1.0, 1.0, 1.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* Set up matrices from current state */
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(-state.cameraScope, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
/* Derive camera up and right vectors */
up.x = 0.0;
up.y = 0.0;
up.z = 1.0;
right.x = -cos(state.cameraAzimuth + (M_PI / 2));
right.y = sin(state.cameraAzimuth + (M_PI / 2));
right.z = 0.0;
/* Rotate and translate dataset to current viewing angle and position */
glRotatef(state.cameraAzimuth / (M_PI / 180.0), up.x, up.y, up.z);
glRotatef(-state.cameraElevation / (M_PI / 180.0), right.x, right.y, right.z);
glTranslatef(-state.cameraX * right.x, -state.cameraX * right.y, -state.cameraX * right.z);
glTranslatef(-state.cameraY * up.x, -state.cameraY * up.y, -state.cameraY * up.z);
/* Render dataset */
switch(state.renderMethod) {
case POINTS:
renderPoints();
break;
case POINTNORMALS:
renderPointnormals();
break;
case SPLATS:
renderSplats();
break;
case SIZEDSPLATS:
renderSizedSplats();
break;
}
glutSwapBuffers();
}
int main(int argc, char *argv[]) {
if(argc != 2 || strcmp("-h", argv[1]) == 0) {
printf("Usage: visualise input.sli3\nKeys: 1 - Render as point cloud\n 2 - Draw every 8th vertex normal\n 3 - Render as constant-size, screen-aligned, aliased splats\n 4 - Attempt to render as sized, perspective correct, surface-oriented Gaussian splats\n -/+ to zoom\n Drag to rotate, right-drag to translate\n Press q to quit.\n");
exit(1);
}
/* Read data file */
input(argv[1]);
/* Derive vertex normals and store with data */
precalcNormals();
/* Rotate each slice to its true 3D position */
rotateSlices();
/* Simple GLUT startup */
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(800, 800);
glutCreateWindow("Visualise");
/* GLUT callback registration */
glutReshapeFunc(size);
glutDisplayFunc(draw);
glutKeyboardFunc(press);
glutMouseFunc(click);
glutMotionFunc(drag);
glutPassiveMotionFunc(move);
/* Global init */
state.cameraScope = 300.0;
state.cameraAzimuth = -M_PI / 4.0;
state.cameraElevation = M_PI / 8.0;
state.cameraX = 0.0;
state.cameraY = 0.0;
state.dragging = NONE;
renderInit();
glutMainLoop();
return(0);
}
|
C
|
#include "timer.h"
#include "../drivers/screen.h"
#include "../libc/function.h"
#include "isr.h"
#include "ports.h"
int tick = 0;
//timer_callback is of type *isr_t
//
static void timer_handler(registers_t* r){
++tick;
(void)r;
}
void init_timer(int freq){
//PIT0 couples to IRQ0
register_interrupt_handler(IRQ0, timer_handler);
int divisor = 1193180 / freq;
char low = (char)(divisor & 0xff);
char high = (char)((divisor >> 8) & 0xff);
outb(0x43, 0x36); //write 0x36 (square wave on PIT0, set low and high bit) to PIT command port
//port 0x40 is PIT0, set low and high bit of frequency divisor
outb(0x40, low);
outb(0x40, high);
}
|
C
|
#include <stdio.h>
float avg(float a, float b, float c, float d, float e);
int main(void)
{
printf("%f", avg(1.0, 2.0, 3.0, 4.0, 6.0));
return 0;
}
float avg(float a, float b, float c, float d, float e)
{
return ((a+b+c+d+e) / 5.0);
}
|
C
|
#include <stdlib.h>
//#include<time.h>
#include <string.h>
//#include <stdint.h>
#include <stdio.h>
int tlb_queue[10];
int tlb_queue_size=0;
int head=-1;
int tail=-1;
int size=0;
int page_size = 4096;
void swap(int total_number_of_bytes,char *buffer,char **page_table){
int total_number_of_pages = total_number_of_bytes / page_size;
char temp[page_size];
int temp_index;
int first_index = rand() % total_number_of_pages;
int second_index = rand() % total_number_of_pages;
//TODO check same
if(first_index == second_index){
second_index = rand() % total_number_of_pages;
}
//printf("%d\n",page_table[first_index]);
//printf("%d\n",page_table[second_index]);
//printf("\n%d\n",page_table[first_index]);
//printf("%d\n",page_table[second_index]);
char *temp_add;
temp_add = page_table[first_index];
for(int i=0; i < page_size; i++){
//temp[i] = buffer[first_index*pa+ge_size+i];
temp[i] = *(page_table[first_index]+i);
//printf("%c",temp[i]);
}
//printf("\n\n");
for(int i=0; i < page_size; i++){
//buffer[first_index*page_size+i] = buffer[second_index*page_size+i];
*(page_table[first_index]+i) = *(page_table[second_index]+i);
//printf("%c",*((char*)page_table[first_index]+i));
}
page_table[first_index] = page_table[second_index];
//printf("\n\n");
for(int i=0; i < page_size; i++){
//buffer[second_index*page_size+i] = temp[i];
*((char*)page_table[second_index]+i)= temp[i];
//printf("%c",*((char*)page_table[second_index]+i));
}
//printf("\n\n");
page_table[second_index] = temp_add;
}
void create_read_list(){
return;
}
void print_page_table(char **page_table,int total_number_of_pages){
for(int i=0; i < total_number_of_pages; i++){
printf("%d.page_address : %d\n",i,page_table[i]);
}
}
void print_mem(char *arr,int numbytes){
for(int i=0; i < numbytes; i++){
printf("%c",arr[i]);
}
}
//
int get_address(char **page_table,int index){
int i = index % page_size;
int page_no = index / page_size;
char *address;
address = (char*)page_table[page_no]+i;
printf("%d,%c\n",address,*address);
return (int)address;
}
int get_tlb_index(char **tlb ,char* address){
for(int i=0;i<10;i++){
if(tlb[i] == address){
//hit
return i;
}
}
//miss
return -1;
}
void enqueu(int index){
head = (head +1) %10;
tlb_queue[head] = index;
size++;
}
int dequeue(){
head = (head-1) %10;
int index = tlb_queue[head];
size--;
}
int update_tlb(int tlb_index,char **tlb ,char* page_address){
int index;
if(tlb_index == -1){
if(tlb_queue_size<10){
//printf("tlb_queue_size :%d\n",tlb_queue_size);
tlb[tlb_queue_size] = page_address;
tlb_queue[tlb_queue_size] = tlb_queue_size;
tlb_queue_size++;
for(int i = 0;i<tlb_queue_size;i++){
//printf("tlb_queue[%d] : %d\n",i,tlb_queue[i]);
}
}
else{
int temp_queue[10];
for(int i = 0;i<tlb_queue_size;i++){
temp_queue[i] = tlb_queue[i];
}
tlb_queue[0] = tlb_queue[tlb_queue_size-1];
for(int i = 0;i<tlb_queue_size;i++){
tlb_queue[i+1] = temp_queue[i];
}
tlb[tlb_queue[0]] = page_address;
for(int i = 0;i<tlb_queue_size;i++){
//printf("tlb_queue[%d] : %d\n",i,tlb_queue[i]);
}
//printf("tlb_queue[0] : %d\n",tlb_queue[0]);
//printf("tlb[tlb_queue[0]] : %d\n",tlb[tlb_queue[0]]);
}
return 0;
}
//UPDATE TLB QUEUE
int temp_queue[10];
for(int i = 0;i<tlb_queue_size;i++){
temp_queue[i] = tlb_queue[i];
}
tlb_queue[0] = tlb_index;
int j = 0;
for(int i = 1;i<tlb_queue_size;i++){
if(temp_queue[j]==tlb_index){
j++;
continue;
}
tlb_queue[i] = temp_queue[j];
j++;
}
return 0;
}
main() {
FILE *infile;
char *buffer;
long numbytes;
infile = fopen("password.txt", "r");
if(infile == NULL)
return 1;
fseek(infile, 0L, SEEK_END);
numbytes = ftell(infile);
if( numbytes % page_size != 0 ){
numbytes = ((numbytes / page_size) + 1) * page_size;
}
fseek(infile, 0L, SEEK_SET);
buffer = calloc(numbytes, sizeof(char));
if(buffer == NULL)
return 1;
fread(buffer, sizeof(char), numbytes, infile);
srand(time(0));
int access[1000];
int counter = 0;
FILE *fp;
char buff[255];
fp = fopen("access.txt", "r");
for(int i=1;i<1000;i++){
fgets(buff, 255, (FILE*)fp);
int a = atoi(buff);
access[i] = a;
}
fclose(fp);
char **page_table;
int total_number_of_bytes = numbytes;
int total_number_of_pages = total_number_of_bytes / page_size;
printf("total_number_of_bytes %d\n",total_number_of_bytes);
printf("total_number_of_pages %d\n",total_number_of_pages);
page_table = malloc(total_number_of_pages * sizeof(char*));
for(int i=0; i < total_number_of_pages; i++){
page_table[i] = &buffer[i*page_size];
}
printf("\n");
print_page_table(page_table,total_number_of_pages);
printf("\n");
for(int i=0; i < 100; i++){
swap(numbytes,buffer,page_table);
}
print_page_table(page_table,total_number_of_pages);
char *tlb[10];
int hit =0;
int miss = 0;
int tlb_index;
for(int i=0;i<1000;i++){
printf("accessed virtual address: %d\n",access[i]);
int page_no = access[i] / page_size;
char *page_address = (char*)page_table[page_no];
tlb_index = get_tlb_index(tlb,page_address);
if(tlb_index > -1){
hit++;
printf("TLB Hit, page no : %d\n",page_no);
}
else{
miss++;
printf("TLB Miss, page no : %d\n",page_no);
}
update_tlb( tlb_index,tlb ,page_address);
}
printf("hit :%d\n",hit);
printf("miss :%d\n",miss);
exit(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "hashtable.h"
int
main(int argc, char **argv)
{
hashtable *ht = init(1);
const char *x = "abhinav";
int age = 22;
const char *y = "abcd";
put(&ht, "name", (void *) x);
printf("size: %d, maxsize: %d\n", ht->size, ht->max_size);
put(&ht, "age", (void *) &age);
printf("size: %d, maxsize: %d\n", ht->size, ht->max_size);
put(&ht, "random", (void *) y);
printf("size: %d, maxsize: %d\n", ht->size, ht->max_size);
printf("%s\n", (char *) get(ht, "name"));
printf("%d\n", *(int *)get(ht, "age"));
printf("%s\n", (char *) get(ht, "random"));
clear(ht);
return 0;
}
|
C
|
/**************************************************************
* Name : ex1-4.c
* Author : Bronze Lee
* Version : 0.1
* Date : 2017年2月13日
**************************************************************/
#include <stdio.h>
/*print Celsius-Fahrenheit table for celsius = -20, -10, ...,100 */
/*--------------- MAIN Code Module -----------------*/
main ()
{
float fahr, celsius;
float lower, upper, step;
lower = -20;
/* lower limit of temperature scale */
upper = 100.0;
/* upper limit */
step = 10.0;
/* step size */
celsius = lower;
printf("Celsius-Fahrenheit Table\n");
printf("\tfrom -20 to 100\n");
while (celsius <= upper)
{
fahr = 9.0 / 5.0 * celsius + 32.0;
printf("%3.0f%9.2f\n", celsius, fahr);
celsius = celsius + step;
}
}
|
C
|
#include "myLib.H"
namespace Foam
{
myLib::myLib()
:
name_("none"),
ID_(0)
{
}
myLib::myLib(word name, label ID)
:
name_(name),
ID_(ID)
{}
myLib::myLib(dictionary dict)
:
name_(dict.lookup("name")),
ID_(readScalar(dict.lookup("ID")))
{}
myLib::~myLib()
{
Info << "I'm killed " << endl;
}
const word& myLib::name() const
{
return name_;
}
const label& myLib::ID() const
{
return ID_;
}
void myLib::setName(word name)
{
name_=name;
}
void myLib::setScore(label ID)
{
ID_=ID;
}
Ostream& operator<<(Ostream& os, const myLib& ml)
{
os << "name: " << ml.name_ << tab << "ID: " << ml.ID_ ;
return os;
}
} // namespace Foam
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int num[3];
int i, j, a;
printf("Enter three intergers, and I will tell you\n");
printf("the biggest and the smallest integer");
scanf_s("%d %d %d", &num[0], &num[1], &num[2]);
for (i = 0; i <= 3; i++)
{
for (j = 0; j <= 1; j++)
{
if (num[i] < num[i + 1])
{
a = num[i];
num[i] = num[i + 1];
num[i + 1] = a;
}
}
}
printf("the biggest integer is:%d\n", num[0]);
printf("the smallest integer is:%d", num[2]);
system("pause");
return 0;
}
|
C
|
#include <bfd.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "section.h"
#include "general.h"
void print_ascii(char character) {
printf("%c", character >= ' ' && character <= '~' ? character : '.');
}
void print_padding(int64_t size) {
if (size % 16 != 0) {
for (int i = 0; i < (16 - (size % 16)); i++) {
printf(" ");
if ((i % 2) == 1)
putchar(' ');
}
if ((size % 2) == 1)
putchar(' ');
}
}
long parsed_sections(bfd *handle, struct Section **reference) {
asection* list;
int flags;
long count = 0;
enum SectionType type;
bool read;
//allocate first Section structure
struct Section *sections = malloc(sizeof(struct Section));
if (sections == NULL)
error("No memory can be allocated\n");
for (list = handle->sections; list; list = list->next) {
flags = bfd_get_section_flags(handle, list);
//allow code and data sections only
if (flags & SEC_CODE)
type = Code;
else if (flags & SEC_DATA)
type = Data;
else
continue;
//allocate next Section structure
if (count > 0) {
sections = realloc(
sections,
(count + 1) * sizeof(struct Section)
);
if (sections == NULL)
error("No memory can be allocated\n");
}
//parse section type, name, virtual address and size
sections[count].type = type;
sections[count].name = bfd_section_name(handle, list);
sections[count].virtual_address = bfd_section_vma(handle, list);
sections[count].size = bfd_section_size(handle, list);
//parse section content
sections[count].contents = (uint8_t*) malloc(
sections[count].size
);
if (sections[count].contents == NULL)
error("No memory can be allocated\n");
read = bfd_get_section_contents(
handle,
list,
sections[count].contents,
0,
sections[count].size
);
if (read == false)
error("Unable to read section\n");
count++;
}
*reference = sections;
return count;
}
void print_sections(struct Section *sections, long count) {
if (count > 0) {
printf("Sections:\n");
for (long i = 0; i < count; i++)
printf(
" %-40s %-8jx %s %-8ju\n",
sections[i].name,
sections[i].virtual_address,
sections[i].type == Data ? "Data" : "Code",
sections[i].size
);
}
}
struct Section parsed_section(
struct Section *sections,
long count,
char *name
) {
struct Section section;
bool found = false;
//find a section by name and return its content
for (long i = 0; i < count; i++)
if (strcmp(sections[i].name, name) == 0) {
section = (struct Section) sections[i];
found = true;
}
if (!found)
error("Section not found\n");
return section;
}
void print_section(struct Section section) {
uint64_t address = section.virtual_address;
int j;
printf(
"%s 0x%08jx %s %ju\n",
section.name,
section.virtual_address,
section.type == Data ? "Data" : "Code",
section.size
);
for (int i = 0; i < section.size; i++) {
//print ASCII values
if ((i % 16) == 0 && i != 0)
for (j = (i - 16); j < i; j++)
print_ascii(section.contents[j]);
//print line address
if ((i % 16) == 0) {
printf("\n%-8jx", address);
address += 16;
}
//print hexadecimal characters
printf("%02x", section.contents[i]);
if ((i % 2) == 1)
printf(" ");
//print ASCII values with padding of last line
if (i == section.size - 1) {
print_padding(section.size);
for (j = i - i % 16; j <= i; j++)
print_ascii(section.contents[j]);
}
}
putchar('\n');
}
|
C
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.c
* Author: apacot
*
* Created on 29 septembre 2020, 10:44
*/
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
int main(int argc, char** argv)
{
//p1
int pid1,pid2;
int cpt=0;
pid1 = fork();
if ( pid1 == 0 ) //p2
{
cpt++;
pid2 = fork();
if ( pid2 == 0 ) //p3
{
cpt++;
printf("dans petit fils cpt=%d a l'adresse %4X\n",cpt,&cpt);
}
else //p2
{
cpt++;
printf("dans fils cpt=%d a l'adresse %4X\n",cpt,&cpt);
}
}
else //p1
{
cpt++;
printf("dans pere cpt=%d a l'adresse %4X\n",cpt,&cpt);
}
return (EXIT_SUCCESS);
}
|
C
|
#include<stdio.h>
#include <conio.h>
char board[3][3] =
{{'1','2','3'},
{'4','5','6'},
{'7','8','9'}};
int player=0,choice=0;
int CheckForWin();
void drawboard();
void markboard( char mark);
int main(void)
{
int gamestatus=0;
char mark;
player=1;
do
{
//e
drawboard();
//pGPlayerH2lƬO1(]NOu)AplayerNO1AlNO2
player = (player % 2) ? 1 : 2;
printf("Player %d, enter a number: ", player);
scanf("%d", &choice);
//pGPlayergO1ܡAmarkOX lNO O
mark = (player == 1) ? 'X' : 'O';
//}le
markboard(mark);
//MwCA
gamestatus = checkwin();
//PLAYERƦr۰ʥ[1
player++;
}while (gamestatus == - 1);
if (gamestatus == 1)
printf("==>\aPlayer %d win ", --player);
else
printf("==>\aGame draw");
return 0;
}
//ܤrCe
void drawboard()
{
system("cls");
printf("\n\n Tic Tac Toe\n");
printf("\nPlayer 1(X) - Player 2(O) \n");
printf("\n\n");
printf(" %c | %c | %c\n",board[0][0], board[0][1], board[0][2]);
printf("---+---+---\n");
printf(" %c | %c | %c\n",board[1][0], board[1][1], board[1][2]);
printf("---+---+---\n");
printf(" %c | %c | %c\n",board[2][0], board[2][1], board[2][2]);
}
int checkwin()
{
//rC1,2,3sb@_ɭԡAgame over MwӪ
if (board[0][0] == board[0][1] && board[0][1] == board[0][2])
return 1;
//rC4,5,6sb@_ɭԡAgame over èMwӪ
else if (board[1][0] == board[1][1] && board[1][1] == board[1][2])
return 1;
//rC7,8,9sb@_ɭԡAgame over èMwӪ
else if (board[2][0] == board[2][1] && board[2][1] == board[2][2])
return 1;
//rC1,4,7sb@_ɭԡAgame over èMwӪ
else if (board[0][0] == board[1][0] && board[1][0] == board[2][0])
return 1;
//rC2,5,8sb@_ɭԡAgame over èMwӪ
else if (board[0][1] == board[1][1] && board[1][1] == board[2][1])
return 1;
//rC3,6,9sb@_ɭԡAgame over èMwӪ
else if (board[0][2] == board[1][2] && board[1][2] == board[2][2])
return 1;
//rC1,5,9sb@_ɭԡAgame over èMwӪ
else if (board[0][0] == board[1][1] && board[1][1] == board[2][2])
return 1;
//rC3,5,7sb@_ɭԡAgame over èMwӪ
else if (board[0][2] == board[1][1] && board[1][1] == board[2][0])
return 1;
//YLpN^-1A]SĹ
else
return - 1;
}
//TweOX0
void markboard( char mark)
{
if (choice == 1 && board[0][0] == '1')
{
board[0][0] = mark;
}
else if (choice == 2 && board[0][1] == '2')
{
board[0][1] = mark;
}
else if (choice == 3 && board[0][2] == '3')
{
board[0][2] = mark;
}
else if (choice == 4 && board[1][0] == '4')
{
board[1][0] = mark;
}
else if (choice == 5 && board[1][1] == '5')
{
board[1][1] = mark;
}
else if (choice == 6 && board[1][2] == '6')
{
board[1][2] = mark;
}
else if (choice == 7 && board[2][0] == '7')
{
board[2][0] = mark;
}
else if (choice == 8 && board[2][1] == '8')
{
board[2][1] = mark;
}
else if (choice == 9 && board[2][2] == '9')
{
board[2][2] = mark;
}
else
{
printf("Invalid move ");
player--;
getch();
}
}
|
C
|
//
// Created by Horvath on 2021. 05. 25..
//
#include "array.h"
Array createArray(int size){
Array res;
res.size=size;
res.count=0;
res.names=(Name*)malloc((res.size+1)*sizeof(Name));
return res;
}
void addName(Array *res,Name name){
res->names[res->count]=name;
res->count++;
}
bool findName(Array *res,Name name){
for(int i=0;i<res->count;i++){
if(compareName(res->names[i],name)==0){
return true;
}
}
return false;
}
void deleteName(Array *res,Name name){
for(int i=0;i<res->count;i++){
if(compareName(name,res->names[i])==0){
for(int j=i;j<res->count-1;j++){
res->names[j]=res->names[j+1];
}
res->count--;
return;
}
}
}
void listName(Array *res){
for(int i=0;i<res->count;i++){
printf("Name:%s %s\n",res->names[i].firstName,res->names[i].lastName);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_julia_event.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sandruse <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/02/28 15:08:14 by sandruse #+# #+# */
/* Updated: 2017/03/01 16:54:32 by sandruse ### ########.fr */
/* */
/* ************************************************************************** */
#include "fractol.h"
void ft_zoom(t_julia ***j, double b)
{
t_julia **jul;
int i;
jul = *j;
i = 0;
while (i < 8)
{
jul[i]->z = jul[i]->z * b;
if (jul[i]->z < 1)
jul[i]->z = 1;
jul[i]->y = -1;
i++;
}
}
void ft_move_julia(int keycode, t_julia ***j)
{
t_julia **jul;
int i;
i = -1;
jul = *j;
if (keycode == 123)
while (++i < 8)
jul[i]->mx = jul[i]->mx + 0.05;
else if (keycode == 124)
while (++i < 8)
jul[i]->mx = jul[i]->mx - 0.05;
else if (keycode == 125)
while (++i < 8)
jul[i]->my = jul[i]->my - 0.05;
else
while (++i < 8)
jul[i]->my = jul[i]->my + 0.05;
i = -1;
while (++i < 8)
jul[i]->y = -1;
}
void ft_color(int keycode, t_julia ***j)
{
t_julia **jul;
int i;
i = -1;
jul = *j;
if (keycode == 1)
while (++i < 8)
jul[i]->k = 16;
else if (keycode == 2)
while (++i < 8)
jul[i]->k = 32;
else
while (++i < 8)
jul[i]->k = 8;
i = -1;
while (++i < 8)
jul[i]->y = -1;
}
int ft_key_julia(int keycode, t_julia ***jul)
{
if ((keycode >= 0 && keycode < 3) || (keycode >= 123 && keycode <= 126)
|| keycode == 24 || keycode == 27 || keycode == 53)
{
if (keycode == 24)
ft_zoom(jul, 1.1);
else if (keycode == 27)
ft_zoom(jul, 0.9);
if (keycode == 53)
exit(0);
else if (keycode >= 123 && keycode <= 126)
ft_move_julia(keycode, jul);
else if (keycode == 1 || keycode == 2 || keycode == 0)
ft_color(keycode, jul);
ft_popo(*jul);
}
return (0);
}
|
C
|
/*
Codegenerator for CRC32 as used in RFC1951 (GZip 4.3)
This is the same CRC32 as specified in ISO 3309 and ITU-T V.42
*/
/*
Copyright (c) 2018, Thomas Spielauer
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed by Thomas Spielauer
4. Neither the name of the Thomas Spielauer may be used to endorse or
promote products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY Thomas Spielauer ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Thomas Spielauer BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
static unsigned long int crc32Table[256];
int main(int argc, char* argv[]) {
/* CRC32 Table Generator ... */
unsigned long int c;
unsigned int n, k;
unsigned long int i,j;
/* Calculate CRC32 table */
for(n = 0; n < 256; n=n+1) {
c = n;
for(k = 0; k < 8; k=k+1) {
if((c & 1) != 0) {
c = 0xedb88320L ^ (c >> 1);
} else {
c = c >> 1;
}
}
crc32Table[n] = c;
}
/* Generate sourcecode ... */
printf("unsigned long int rfc1951_crc32Table[256] = {\n");
for(i = 0; i < 32; i=i+1) {
printf("\t");
for(j = 0; j < 8; j=j+1) {
printf("0x%lx", crc32Table[j + i*8]);
if(!((j == 7) && (i == 31))) { printf(","); }
}
printf("\n");
}
printf("};\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#define NUM_THREADS 3
#define LIMIT 12
#define TCOUNT 10
#define ADD_COUNT 125
pthread_t thrd[NUM_THREADS];
pthread_mutex_t mutex;
pthread_cond_t cond;
int count;
/* a thread function for accumulating count */
void *inc_count(void *args);
/* a thread function for changing the count while the condition is true */
void *watch_count(void *args);
/* timestamp the thread wait */
void thread_wait(const int sec);
int main(int argc, char *argv[])
{
int i, ret, thrd_id_a, thrd_id_b, thrd_id_c;
pthread_attr_t attr;
void *status;
/* initialise mutex and condition variables for synchronization */
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
/* initialise threads attributes and set threads joinable */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
thrd_id_a = 1;
thrd_id_b = 2;
thrd_id_c = 3;
count = 0; /* initialise the begin value */
pthread_create(thrd + 0, &attr, watch_count, (void*)thrd_id_a);
pthread_create(thrd + 1, &attr, inc_count, (void*)thrd_id_b);
pthread_create(thrd + 2, &attr, inc_count, (void*)thrd_id_c);
status = NULL;
for (i = 0; i < NUM_THREADS; ++i)
{
ret = pthread_join(thrd[i], &status);
if (ret)
{
printf("ERROR; return code from pthread_create(): %d\r\n", ret);
exit(-1);
}
}
printf("Main(): Waited on %d threads. Final value of count = %d.Done!\r\n",
NUM_THREADS, count);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
pthread_exit(NULL);
}
/* a thread function for accumulating count */
void *inc_count(void *args)
{
int id, i;
id = (int)args;
for (i = 0; i < TCOUNT; ++i)
{
pthread_mutex_lock(&mutex);
++count;
if (count == LIMIT)
{
printf("inc_count(): thread %d, count = %d Threadhold reached.",
id, count);
pthread_cond_signal(&cond);
printf("Just send signal!\n");
}
printf("inc_count(): thread %d, count = %d, unlocking mutex\r\n",
id, count);
pthread_mutex_unlock(&mutex);
thread_wait(2);
}
pthread_exit(NULL);
}
/* a thread function for changing the count while the condition is true */
void *watch_count(void *args)
{
int id;
id = (int)args;
printf("Starting watch_count(): thread %d\r\n", id);
pthread_mutex_lock(&mutex);
if (count < LIMIT)
{
printf("watch_count(): thread %d is going into wait...\r\n", id);
/* block there waiting for condition(count >= LIMIT), and then unlock */
pthread_cond_wait(&cond, &mutex);
/* got the lock */
printf("watch_count(): thread %d condition signal received!\r\n", id);
count += ADD_COUNT;
printf("watch count(): thread %d count now = %d\r\n",
id, count);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
/* timestamp the thread wait */
void thread_wait(const int sec)
{
pthread_mutex_t mutex;
pthread_cond_t cond;
struct timespec timeout;
/* there is no need to wait */
if (sec < 0)
{
return;
}
/* mutex for protect the code */
pthread_mutex_init(&mutex, NULL);
/* condition for making current thread to wait some time */
pthread_cond_init(&cond, NULL);
pthread_mutex_lock(&mutex);
/* timeout point: current_time + sec */
timeout.tv_sec = time(NULL) + sec;
timeout.tv_nsec = 0;
pthread_cond_timedwait(&cond, &mutex, &timeout);
pthread_mutex_unlock(&mutex);
}
|
C
|
#include<stdio.h>
int main()
{
int ara[15];
int i;
for(i=0; i<15; i++) ara[i] = i;
ara[9] = ara[9] + 500;
for(i=0; i<15; i++) printf("%d ",ara[i]);
}
|
C
|
#include <stdio.h>
void ssort(double *v, int tam){
int i, j;
double aux;
for ( i = 0; i < tam; ++i)
{
for ( j = i; j < tam; ++j)
{
if (v[j] > v[i])
{
aux = v[j];
v[j] = v[i];
v[i] = aux;
}
}
}
}
|
C
|
#include "buttons.h"
// PMW instance
APP_PWM_INSTANCE(PWM2, 2); // Setup a PWM instance with TIMER 2
static volatile int ready_flag = true;
void button_handler(uint8_t pin_no, uint8_t button_action)
{
NRF_LOG_INFO("Button press detected \r\n");
if(pin_no == BUTTON_1 && button_action == APP_BUTTON_PUSH)
{
NRF_LOG_INFO("Button 1 pressed \r\n");
nrf_drv_gpiote_out_task_trigger(LED_1);
APP_ERROR_CHECK(app_pwm_channel_duty_set(&PWM2, 0, 10));
ready_flag = false;
nrf_delay_ms(1000);
while(!ready_flag){APP_ERROR_CHECK(app_pwm_channel_duty_set(&PWM2, 0, 0));}
}
if(pin_no == BUTTON_2 && button_action == APP_BUTTON_PUSH)
{
NRF_LOG_INFO("Button 2 pressed \r\n");
nrf_drv_gpiote_out_task_trigger(LED_2);
APP_ERROR_CHECK(app_pwm_channel_duty_set(&PWM2, 0, 5));
ready_flag = false;
nrf_delay_ms(1000);
while(!ready_flag){APP_ERROR_CHECK(app_pwm_channel_duty_set(&PWM2, 0, 0));}
}
}
void buttons_init()
{
ret_code_t err_code;
/*
static app_button_cfg_t button_cfg = {
.pin_no = BUTTON_1,
.active_state = APP_BUTTON_ACTIVE_LOW,
.pull_cfg = NRF_GPIO_PIN_PULLUP,
.button_handler = button_handler
};
*/
static app_button_cfg_t button_cfg[2] = {
{BUTTON_1,APP_BUTTON_ACTIVE_LOW,NRF_GPIO_PIN_PULLUP,button_handler},
{BUTTON_2,APP_BUTTON_ACTIVE_LOW,NRF_GPIO_PIN_PULLUP,button_handler}
};
err_code = app_button_init(button_cfg,2,5);
APP_ERROR_CHECK(err_code);
err_code = app_button_enable();
APP_ERROR_CHECK(err_code);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "dynamicArray.h"
#define PI 3.14159
#define E 2.71828
/* param: s the string
param: num a pointer to double
returns: true (1) if s is a number else 0 or false.
postcondition: if it is a number, num will hold
the value of the number
*/
int isNumber(char *s, double *num)
{
char *end;
double returnNum;
if(strcmp(s, "0") == 0)
{
*num = 0;
return 1;
}
else
{
returnNum = strtod(s, &end);
/* If there's anythin in end, it's bad */
if((returnNum != 0.0) && (strcmp(end, "") == 0))
{
*num = returnNum;
return 1;
}
}
return 0; //if got here, it was not a number
}
/* param: stack the stack being manipulated
pre: the stack contains at least two elements
post: the top two elements are popped and
their sum is pushed back onto the stack.
*/
void add (struct DynArr *stack)
{
double ans;
int a, b;
if(!(sizeDynArr(stack) >= 2)) { //checks that there are two numbers to add
printf("Error: Too few inputs\n");
exit(EXIT_FAILURE);
}
a = sizeDynArr(stack) - 2; //element right below top of stack
b = sizeDynArr(stack) - 1; //element at top of stack
ans = (getDynArr(stack, a) + getDynArr(stack, b)); //adds the two numbers
putDynArr(stack, a, ans); //replaces element right below stack with new num
popDynArr(stack); //removes top element and decrements size by one
}
/* param: stack the stack being manipulated
pre: the stack contains at least two elements
post: the top two elements are popped and
their difference is pushed back onto the stack.
*/
void subtract(struct DynArr *stack)
{
double ans;
int a, b;
if(!(sizeDynArr(stack) >= 2)) {
printf("Error: Too few inputs\n");
exit(EXIT_FAILURE);
}
a = sizeDynArr(stack) - 2;
b = sizeDynArr(stack) - 1;
ans = (getDynArr(stack, a) - getDynArr(stack, b));
putDynArr(stack, a, ans);
popDynArr(stack);
}
/* param: stack the stack being manipulated
pre: the stack contains at least two elements
post: the top two elements are popped and
their quotient is pushed back onto the stack.
*/
void divide(struct DynArr *stack)
{
double ans;
int a, b;
if(!(sizeDynArr(stack) >= 2)) {
printf("Error: Too few inputs\n");
exit(EXIT_FAILURE);
}
a = sizeDynArr(stack) - 2;
b = sizeDynArr(stack) - 1;
ans = (getDynArr(stack, a) / getDynArr(stack, b));
putDynArr(stack, a, ans);
popDynArr(stack);
}
void multiply(struct DynArr *stack)
{
double ans;
int a, b;
if(!(sizeDynArr(stack) >= 2)) {
printf("Error: Too few inputs\n");
exit(EXIT_FAILURE);
}
a = sizeDynArr(stack) - 2;
b = sizeDynArr(stack) - 1;
ans = (getDynArr(stack, a) * getDynArr(stack, b));
putDynArr(stack, a, ans);
popDynArr(stack);
}
void power(struct DynArr *stack)
{
double ans;
int a, b;
if(!(sizeDynArr(stack) >= 2)) {
printf("Error: Too few inputs\n");
exit(EXIT_FAILURE);
}
a = sizeDynArr(stack) - 2;
b = sizeDynArr(stack) - 1;
ans = pow(getDynArr(stack, a), getDynArr(stack, b));
putDynArr(stack, a, ans);
popDynArr(stack);
}
void square(struct DynArr *stack)
{
double ans;
int a;
if(!(sizeDynArr(stack) >= 1)) {
printf("Error: Too few inputs\n");
exit(EXIT_FAILURE);
}
a = sizeDynArr(stack) - 1;
ans = pow(getDynArr(stack, a), 2);
putDynArr(stack, a, ans);
}
void cube(struct DynArr *stack)
{
double ans;
int a;
if(!(sizeDynArr(stack) >= 1)) {
printf("Error: Too few inputs\n");
exit(EXIT_FAILURE);
}
a = sizeDynArr(stack) - 1;
ans = pow(getDynArr(stack, a), 3);
putDynArr(stack, a, ans);
}
void absoluteValue(struct DynArr *stack)
{
double ans;
int a;
if(!(sizeDynArr(stack) >= 1)) {
printf("Error: Too few inputs\n");
exit(EXIT_FAILURE);
}
a = sizeDynArr(stack) - 1;
ans = getDynArr(stack, a);
if (ans < 0)
ans = (getDynArr(stack, a) * -1);
putDynArr(stack, a, ans);
}
void squareRoot(struct DynArr *stack)
{
double ans;
int a;
if(!(sizeDynArr(stack) >= 1)) {
printf("Error: Too few inputs\n");
exit(EXIT_FAILURE);
}
a = sizeDynArr(stack) - 1;
ans = pow(getDynArr(stack, a), 0.5);
putDynArr(stack, a, ans);
}
void exponential(struct DynArr *stack)
{
double ans;
int a;
if(!(sizeDynArr(stack) >= 1)) {
printf("Error: Too few inputs\n");
exit(EXIT_FAILURE);
}
a = sizeDynArr(stack) - 1;
ans = pow(E, getDynArr(stack, a));
putDynArr(stack, a, ans);
}
void naturalLog(struct DynArr *stack)
{
double ans;
int a;
if(!(sizeDynArr(stack) >= 1)) {
printf("Error: Too few inputs\n");
exit(EXIT_FAILURE);
}
a = sizeDynArr(stack) - 1;
ans = log(getDynArr(stack, a));
putDynArr(stack, a, ans);
}
void loga(struct DynArr *stack)
{
double ans;
int a;
if(!(sizeDynArr(stack) >= 1)) {
printf("Error: Too few inputs\n");
exit(EXIT_FAILURE);
}
a = sizeDynArr(stack) - 1;
ans = log10(getDynArr(stack, a));
putDynArr(stack, a, ans);
}
double calculate(int numInputTokens, char **inputString)
{
int i;
double result = 0.0;
double num;
char *s;
struct DynArr *stack;
//set up the stack
stack = createDynArr(20);
// start at 1 to skip the name of the calculator calc
for(i = 1; i < numInputTokens; i++)
{
s = inputString[i];
// Hint: General algorithm:
// (1) Check if the string s is in the list of operators.
// (1a) If it is, perform corresponding operations.
// (1b) Otherwise, check if s is a number.
// (1b - I) If s is not a number, produce an error.
// (1b - II) If s is a number, push it onto the stack
if(strcmp(s, "+") == 0)
add(stack);
else if(strcmp(s,"-") == 0)
subtract(stack);
else if(strcmp(s, "/") == 0)
divide(stack);
else if(strcmp(s, "x") == 0)
multiply(stack);
else if(strcmp(s, "^") == 0)
power(stack);
else if(strcmp(s, "^2") == 0)
square(stack);
else if(strcmp(s, "^3") == 0)
cube(stack);
else if(strcmp(s, "abs") == 0)
absoluteValue(stack);
else if(strcmp(s, "sqrt") == 0)
squareRoot(stack);
else if(strcmp(s, "exp") == 0)
exponential(stack);
else if(strcmp(s, "ln") == 0)
naturalLog(stack);
else if(strcmp(s, "log") == 0)
loga(stack);
else
{
if (isNumber(s, &num) || !strcmp(s, "pi") || !strcmp(s, "e")) {
if (!strcmp(s, "pi"))
num = PI;
else if (!strcmp(s, "e"))
num = E;
pushDynArr(stack, num);
}
else {
printf("Error: Unrecognized Input\n");
exit(EXIT_FAILURE);
}
}
} //end for
if (sizeDynArr(stack) == 1) {
result = topDynArr(stack);
popDynArr(stack);
return result;
}
else {
printf("Error: Invalid Input\n");
exit(EXIT_FAILURE);
}
}
int main(int argc , char** argv)
{
// assume each argument is contained in the argv array
// argc-1 determines the number of operands + operators
double ans;
if (argc == 1)
return 0;
ans = calculate(argc,argv);
printf("%f\n", ans);
return 0;
}
|
C
|
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_RESET "\x1b[0m"
#define printf_color(color, ...) \
do { \
printf(color); \
printf(__VA_ARGS__); \
printf(ANSI_COLOR_RESET); \
} while (0)
#define printf_red(...) printf_color(ANSI_COLOR_RED, __VA_ARGS__)
#define printf_green(...) printf_color(ANSI_COLOR_GREEN, __VA_ARGS__)
#define printf_yellow(...) printf_color(ANSI_COLOR_YELLOW, __VA_ARGS__)
#define printf_blue(...) printf_color(ANSI_COLOR_BLUE, __VA_ARGS__)
#define printf_magenta(...) printf_color(ANSI_COLOR_MAGENTA, __VA_ARGS__)
#define printf_cyan(...) printf_color(ANSI_COLOR_CYAN, __VA_ARGS__)
|
C
|
#ifndef GRAPH_H
#define GRAPH_H
// Definizione della struttura "grafo".
// E' rappresentato con 2 liste, una per i nodi ed una per gli archi.
// In ogni nodo c'è una lista dei suoi archi(ovvero gli archi di cui è from/to).
// Le liste in questione sono doppiamente concatenate.
typedef struct node_list node_list;
typedef struct node node;
typedef struct edge_list edge_list;
typedef struct edge edge;
typedef struct graph graph;
graph *new_graph();
void add_edge_to_graph(graph *g, node *from, node *to, int id, _Bool is_directed);
void add_node_to_graph(graph *g, int id);
node *graph_get_node_by_id(graph *g, int id);
node *node_opposite(edge *e, node *n);
void BFS(graph *g);
struct node_list {
struct node_list *prev;
struct node_list *next;
node *info;
};
struct node {
int id;
node_list *ref_list;
edge_list *edges;
int color;
};
struct edge_list {
struct edge_list *prev;
struct edge_list *next;
edge *info;
};
struct edge {
int id;
node *from;
node *to;
edge_list *ref_list;
edge_list *ref_list_from;
edge_list *ref_list_to;
};
struct graph {
node_list *nodes;
edge_list *edges;
int num_nodes;
int num_edges;
};
#endif
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "../include/babak_lib.h"
void swapByteOrder(char *in, int4 N)
{
char *dum;
if(N<=0)
{
printf("\n\nWarning swapByteOrder(): Non-positive array dimension argument.\n\n");
return;
}
if(in==NULL)
{
printf("\n\nWarning swapByteOrder(): NULL array argument.\n\n");
return;
}
dum = (char *)malloc(N);
if(dum==NULL)
{
printf("\n\nWarning swapByteOrder(): Memory allocation failure.\n\n");
return;
}
for( int4 i=0; i<N; i++)
{
dum[i]=in[N-1-i];
}
for( int4 i=0; i<N; i++)
{
in[i]=dum[i];
}
free(dum);
}
////////////////////////////////////////////////////////////////////////////////
// Returns 1 if the computer is bigEndian (e.g., SUN) and 0 if it is Little Endian (e.g., IBM PC)
int4 bigEndian()
{
int2 s;
char *cp;
// We will set s=1. If the computer is Big Endian, the first byte in s will be
// 0 and the second byte will be 1. So this function returns the second byte.
s=1;
cp=(char *)(&s);
return( (int4)cp[1] );
}
void swapN(char *in, int4 N)
{
char dum[2];
for(int4 i=0; i<N/2; i++)
{
dum[0]=in[i*2+1];
dum[1]=in[i*2];
in[i*2]=dum[0];
in[i*2+1]=dum[1];
}
}
void swap_double_array( float8 *x, int4 n)
{
for(int4 i=0; i<n; i++)
{
swapByteOrder( (char *)(x+i), sizeof(float8) );
}
}
void swap_float_array( float4 *x, int4 n)
{
for(int4 i=0; i<n; i++)
{
swapByteOrder( (char *)(x+i), sizeof(float4) );
}
}
void swap_int_array( int4 *x, int4 n)
{
for(int4 i=0; i<n; i++)
{
swapByteOrder( (char *)(x+i), sizeof(int4) );
}
}
void swap_model_file_hdr(model_file_hdr *hdr)
{
swapByteOrder( (char *)(&hdr->nxHR), sizeof(int4));
swapByteOrder( (char *)(&hdr->nzHR), sizeof(int4));
swapByteOrder( (char *)(&hdr->dxHR), sizeof(float4));
swapByteOrder( (char *)(&hdr->nxLR), sizeof(int4));
swapByteOrder( (char *)(&hdr->nvol), sizeof(int4));
swapByteOrder( (char *)(&hdr->RPtemplateradius), sizeof(int4));
swapByteOrder( (char *)(&hdr->RPtemplateheight), sizeof(int4));
swapByteOrder( (char *)(&hdr->RPtemplatesize), sizeof(int4));
swapByteOrder( (char *)(&hdr->ACtemplateradius), sizeof(int4));
swapByteOrder( (char *)(&hdr->ACtemplateheight), sizeof(int4));
swapByteOrder( (char *)(&hdr->ACtemplatesize), sizeof(int4));
swapByteOrder( (char *)(&hdr->PCtemplateradius), sizeof(int4));
swapByteOrder( (char *)(&hdr->PCtemplateheight), sizeof(int4));
swapByteOrder( (char *)(&hdr->PCtemplatesize), sizeof(int4));
swapByteOrder( (char *)(&hdr->nangles), sizeof(int4));
}
void swap_model_file_tail(model_file_tail *tail)
{
swapByteOrder( (char *)(&tail->RPPCmean[0]), sizeof(float4));
swapByteOrder( (char *)(&tail->RPPCmean[1]), sizeof(float4));
swapByteOrder( (char *)(&tail->parcomMean), sizeof(float4));
swapByteOrder( (char *)(&tail->percomMean), sizeof(float4));
swapByteOrder( (char *)(&tail->RPmean[0]), sizeof(float4));
swapByteOrder( (char *)(&tail->RPmean[1]), sizeof(float4));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
int isSafe(char s[])
{
int i = 0;
int length = strlen(s);
int u = 0;
int l = 0;
int d = 0;
for(i =0; i < length; i++) {
if(isupper(s[i]))
u++;
if(islower(s[i]))
l++;
if(isdigit(s[i]))
d++;
}
if(u>=2 && l>=2 & d>=2) {
printf("Password is safe\n");
} else {
printf("Please think of a more secure password\n");
}
return 0;
}
int main (int argc, char *argv[]) {
int result;
if(argc <2) {
fprintf(stderr, "Usage: %s argument\n", argv[0]);
result = EXIT_FAILURE;
} else {
isSafe(argv[1]);
result = EXIT_SUCCESS;
}
return result;
}
|
C
|
#include <stdio.h>
#include <string.h>
struct std
{
char name[20], idno[25], station[25];
float cgpa;
};
void
main ()
{
int n, i;
char ele[100];
scanf ("%d", &n);
struct std s[n];
for (i = 0; i < n; i++)
{
scanf ("%f", &s[i].cgpa);
gets (s[i].name);
gets (s[i].idno);
gets (s[i].station);
}
gets (ele);
for (i = 0; i < n; i++)
{
if (!(strcmp (s[i].name, ele)))
{
puts (s[i].name);
puts (s[i].idno);
puts (s[i].station);
printf ("%d", s[i].cgpa);
}
}
}
|
C
|
/*
Database "company_1" contains tables:
department
department_locations
dependent
employee
project
works_on
*/
#ifndef COMPANY_1
#define COMPANY_1
struct T_department {
char department_name[15];
double department_number;
double manager_ssn;
char manager_start_date[11];
};
struct T_department_locations {
double department_number;
char department_location[10];
};
struct T_dependent {
double employee_ssn;
char dependent_name[10];
char sex[2];
char birth_date[11];
char relationship[9];
};
struct T_employee {
char first_name[10];
char minit[2];
char last_name[8];
double ssn;
char birth_date[11];
char address[25];
char sex[2];
double salary;
double super_ssn;
double department_no;
};
struct T_project {
char dependent_name[16];
double dependent_number;
char dependent_location[10];
double department_number;
};
struct T_works_on {
double employee_ssn;
double project_number;
double hours;
};
struct T_department
department[] = {
{ "Headquarters", 1, 888665555, "1981-06-19" },
{ "Administration", 4, 987654321, "1995-01-01" },
{ "Research", 5, 333445555, "1988-05-22" }
};
struct T_department_locations
department_locations[] = {
{ 1, "Houston" },
{ 4, "Stafford" },
{ 5, "Bellaire" },
{ 5, "Sugarland" },
{ 5, "Houston" }
};
struct T_dependent
dependent[] = {
{ 333445555, "Alice", "F", "1986-04-05", "Daughter" },
{ 333445555, "Theodore", "M", "1983-10-25", "Son" },
{ 333445555, "Joy", "F", "1958-05-03", "Spouse" },
{ 987654321, "Abner", "M", "1942-02-28", "Spouse" },
{ 123456789, "Michael", "M", "1988-01-04", "Son" },
{ 123456789, "Alice", "F", "1988-12-30", "Daughter" },
{ 123456789, "Elizabeth", "F", "1967-05-05", "Spouse" }
};
struct T_employee
employee[] = {
{ "Jonh", "B", "Smith", 123456789, "1965-01-09", "731 Fondren, Houston, TX", "M", 30000, 333445555, 5 },
{ "Franklin", "T", "Wong", 333445555, "1955-12-08", "638 Voss, Houston, TX", "M", 40000, 888665555, 5 },
{ "Joyce", "A", "English", 453453453, "1972-07-31", "5631 Rice, Houston, TX", "F", 25000, 333445555, 5 },
{ "Ramesh", "K", "Narayan", 666884444, "1962-09-15", "975 Fire Oak, Humble, TX", "M", 38000, 333445555, 5 },
{ "James", "E", "Borg", 888665555, "1937-11-10", "450 Stone, Houston, TX", "M", 55000, None, 1 },
{ "Jennifier", "S", "Wallace", 987654321, "1941-06-20", "291 Berry, Bellaire, TX", "F", 43000, 888665555, 4 },
{ "Ahmad", "V", "Jabbar", 987987987, "1969-03-29", "980 Dallas, Houston, TX", "M", 25000, 987654321, 4 },
{ "Alicia", "J", "Zelaya", 999887777, "1968-01-19", "3321 Castle, Spring, TX", "F", 25000, 987654321, 4 }
};
struct T_project
project[] = {
{ "ProductX", 1, "Bellaire", 5 },
{ "ProductY", 2, "Sugarland", 5 },
{ "ProductZ", 3, "Houston", 5 },
{ "Computerization", 10, "Stafford", 4 },
{ "Reorganization", 20, "Houston", 1 },
{ "Newbenefits", 30, "Stafford", 4 }
};
struct T_works_on
works_on[] = {
{ 123456789, 1, 32.5 },
{ 123456789, 2, 7.5 },
{ 666884444, 3, 40.0 },
{ 453453453, 1, 20.0 },
{ 453453453, 2, 20.0 },
{ 333445555, 2, 10.0 },
{ 333445555, 3, 10.0 },
{ 333445555, 10, 10.0 },
{ 333445555, 20, 10.0 },
{ 999887777, 30, 30.0 },
{ 999887777, 10, 10.0 },
{ 987987987, 10, 35.0 },
{ 987987987, 30, 5.0 },
{ 987654321, 30, 20.0 },
{ 987654321, 20, 15.0 },
{ 888665555, 20, None }
};
#endif
|
C
|
#include <stdio.h>
int main () {
char characters[7];
char *ptr=characters;
printf("Enter 7 characters: ");
for(int i=0;i<7;i++){
scanf("%s", ptr+i);
}
printf("The characters you entered is %s\n", characters);
return 0;
}
|
C
|
//Memory-Management-Simulator---Best-Fit-Algorithm
//Simulator for the memory management portion of an operating system with fixed partition scheme using best-fit algorithm
/*
Memory: 32 KB
Scheme: Fixed
Algorithm: Best-Fit
No. of Partitions:
Partition 1: 4 KB
Partition 1: 4 KB
Partition 1: 8 KB
Partition 1: 16 KB
/*
#include <stdio.h>
int main(void){
int SIZE = 100;
int total_time_m3p2b = 0;
int m3p2b_exe = 0;
int m3p2b_not_exe = 0;
int jobs[SIZE][2];
int i, j;
for(i = 0; i < SIZE; i++){
jobs[i][0] = rand()%15+2;
jobs[i][1] = rand()%20+1;
}
int m3p2b[2][2];
m3p2b[0][0] = 0;
m3p2b[0][1] = 4;
m3p2b[1][0] = 0;
m3p2b[1][1] = 4;
m3p2b[2][0] = 0;
m3p2b[2][1] = 8;
m3p2b[3][0] = 0;
m3p2b[3][1] = 16;
int k;
int stm3p2b[3];
stm3p2b[0] = 0;
stm3p2b[1] = 0;
stm3p2b[2] = 0;
for(i = 0; i < SIZE; i++){
if(jobs[i][1] > 16){
m3p2b_not_exe++;
}
else{
k = ind_small(jobs[i][1], m3p2b[0][1], m3p2b[1][1], m3p2b[2][1], m3p2b[3][1]);
m3p2b_exe++;
total_time_m3p2b += stm3p2b[k];
stm3p2b[k] = jobs[i][0];
}
}
printf("Number of jobs executed: %d\n", m3p2b_exe);
printf("Number of jobs not executed: %d\n", m3p2b_not_exe);
printf("Total time of execution: %d\n", total_time_m3p2b);
return 0;
}
int ind_small(int a, int b, int c, int d, int e){
int arr[4];
arr[0] = a-b;
if(arr[0] < 0)
arr[0] = -100;
arr[1] = a-c;
if(arr[1] < 0)
arr[1] = -100;
arr[2] = a-d;
if(arr[2] < 0)
arr[2] = -100;
arr[3] = a-e;
if(arr[3] < 0)
arr[3] = -100;
int i, j, temp = 0;
for(i = 0; i < 4; i++){
for(j = 0; j < 3; j++){
if(arr[j] > arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
int t = 0;
for(i = 0; i < 4; i++){
if(arr[i] >= 0){
if(arr[i] + b == a){
t = 0;
break;
}
else if(arr[i] + c == a){
t = 1;
break;
}
else if(arr[i] + d == a){
t = 2;
break;
}
else if(arr[i] + e == a){
t = 3;
break;
}
}
}
return t;
}
|
C
|
#include <stdio.h>
void pre_order_traverse(node_t *tree)
{
if (tree == NULL)
return;
/* you can change printf to any operations you want */
printf("%d\n", tree->data);
pre_order_traverse(tree->lchild);
pre_order_traverse(tree->rchild);
}
|
C
|
//Write the program to print "Hello World !"
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
char name[MAX_SIZE];
printf("Enter your name: ");
scanf("%s",name);
printf("Your name: %s\n",name);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
struct Object {
int *nums_lhs;
int len_lhs;
int *nums_rhs;
int len_rhs;
};
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode *make_tree(int *nums, int pos, int size)
{
if (nums[pos] == INT_MIN) {
return NULL;
}
struct TreeNode *node = malloc(sizeof(struct TreeNode));
node->val = nums[pos];
int left = 2 * pos + 1;
int right = 2 * pos + 2;
if (left >= size) {
node->left = NULL;
} else {
node->left = make_tree(nums, left, size);
}
if (right >= size) {
node->right = NULL;
} else {
node->right = make_tree(nums, right, size);
}
return node;
}
void free_tree(struct TreeNode *node)
{
if (node == NULL) {
return;
}
if (node->left != NULL) {
free_tree(node->left);
}
if (node->right != NULL) {
free_tree(node->right);
}
free(node);
}
void print_tree(struct TreeNode *node)
{
printf("%d ", node->val);
if (node->left != NULL) {
print_tree(node->left);
} else {
printf("# ");
}
if (node->right != NULL) {
print_tree(node->right);
} else {
printf("# ");
}
}
bool is_same_tree(struct TreeNode *p, struct TreeNode *q)
{
if (p != NULL && q != NULL) {
if (p->val != q->val) {
return false;
}
if (!is_same_tree(p->left, q->left)) {
return false;
}
if (!is_same_tree(p->right, q->right)) {
return false;
}
} else {
return p == q;
}
return true;
}
int main(int argc, char **argv)
{
int nums1[] = { 1, 2, 3 }, len1 = sizeof(nums1) / sizeof(int);
int nums2[] = { 1, 2, INT_MIN }, len2 = sizeof(nums2) / sizeof(int);
int nums3[] = { 1, INT_MIN, 2 }, len3 = sizeof(nums3) / sizeof(int);
int nums4[] = { 1, 2, 1 }, len4 = sizeof(nums4) / sizeof(int);
int nums5[] = { 1, 1, 2 }, len5 = sizeof(nums5) / sizeof(int);
struct Object inputs[] = {
{ .nums_lhs = nums1, .len_lhs = len1, .nums_rhs = nums1, .len_rhs = len1 },
{ .nums_lhs = nums2, .len_lhs = len2, .nums_rhs = nums3, .len_rhs = len3 },
{ .nums_lhs = nums4, .len_lhs = len4, .nums_rhs = nums5, .len_rhs = len5 },
};
int i, len = sizeof(inputs) / sizeof(struct Object);
for (i = 0; i < len; i++) {
int *nums_lhs = inputs[i].nums_lhs;
int len_lhs = inputs[i].len_lhs;
int *nums_rhs = inputs[i].nums_rhs;
int len_rhs = inputs[i].len_rhs;
struct TreeNode *lhs = make_tree(nums_lhs, 0, len_lhs);
struct TreeNode *rhs = make_tree(nums_rhs, 0, len_rhs);
printf("\n Input: ");
print_tree(lhs);
printf("\n ");
print_tree(rhs);
bool same = is_same_tree(lhs, rhs);
printf("\n Output: %s\n", same ? "true" : "false");
free_tree(lhs);
free_tree(rhs);
}
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <conio.h>
int main()
{
int i=0;
while(i<=5)
{
printf("\n INDIA" "\n I LOVE INDIA");
i++;
}
printf("\n Thanks");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int
count_words(char* text)
{
if (text[0] == '\0') {
return 0;
}
int yy = 1;
for (int ii = 0; text[ii] != '\0'; ++ii) {
if (text[ii] == ' ') {
yy += 1;
}
}
return yy;
}
char**
alloc_stra(int nn)
{
char** yy = malloc(nn * sizeof(char*));
for (int ii = 0; ii < nn; ++ii) {
yy[ii] = 0;
}
return yy;
}
void
delete_stra(char** aa, int nn)
{
for (int ii = 0; ii < nn; ++ii) {
if (aa[ii]) {
free(aa[ii]);
aa[ii] = 0;
}
}
free(aa);
}
int
word_len(char* text)
{
int ii = 0;
while (text[ii] != ' ' && text[ii] != '\0') {
ii++;
}
return ii;
}
char**
split_words(char* text)
{
int nn = count_words(text);
char** xs = alloc_stra(nn);
int jj = 0;
for (int ii = 0; ii < nn; ++ii) {
}
}
char*
reverse_words(char* text)
{
char** words0 = split_words(text);
char** words1 = reverse_stra(words0);
char* revw = join_words(words1);
delete_stra(words0);
delete_stra(words1);
return revw;
}
int
main(int _ac, char* _av[])
{
while (true) {
char* text = 0;
size_t size = 0;
ssize_t rv = getline(&text, &size, stdin);
if (rv == -1) {
break;
}
printf("text: %s\n", text);
char* revw = reverse_words(text);
printf("revw: %s\n", revw);
free(text);
free(revw);
}
}
|
C
|
//*****************************************************************************
// main.c
// Author: jkrachey@wisc.edu
//*****************************************************************************
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "TM4C123.h"
#include "driver_defines.h"
#include "validate.h"
/******************************************************************************
* Includes
*****************************************************************************/
#include "ws2812b.h"
/******************************************************************************
* MACROS
*****************************************************************************/
#define NUM_LEDS 8
/******************************************************************************
* Global Variables
*****************************************************************************/
WS2812B_t LEDs[NUM_LEDS];
//*****************************************************************************
// External Functions
//*****************************************************************************
extern void WS2812B_write(uint32_t port_base_addr, uint8_t *led_array_base_addr, uint16_t num_leds);
//*****************************************************************************
//*****************************************************************************
void DisableInterrupts(void)
{
__asm {
CPSID I
}
}
//*****************************************************************************
//*****************************************************************************
void EnableInterrupts(void)
{
__asm {
CPSIE I
}
}
//*****************************************************************************
//*****************************************************************************
int
main(void)
{
int i;
if( validate_ice(ICE_INTRO_TO_C) == false)
{
// Error in configuing the board, so enter infinite loop.
DisableInterrupts();
while(1){};
}
put_string("\n\r\n\r");
put_string("**************************************\n\r");
put_string("* ECE353: ICE-08-Intro-To-C\n\r");
put_string("**************************************\n\r");
// initialize array
LEDs[0].green = 0x00;
LEDs[0].red = 0x00;
LEDs[0].blue = 0x80;
LEDs[1].green = 0x00;
LEDs[1].red = 0x80;
LEDs[1].blue = 0x00;
LEDs[2].green = 0x00;
LEDs[2].red = 0x80;
LEDs[2].blue = 0x80;
LEDs[3].green = 0x80;
LEDs[3].red = 0x00;
LEDs[3].blue = 0x00;
LEDs[4].green = 0x80;
LEDs[4].red = 0x00;
LEDs[4].blue = 0x80;
LEDs[5].green = 0x80;
LEDs[5].red = 0x80;
LEDs[5].blue = 0x00;
LEDs[6].green = 0x80;
LEDs[6].red = 0x80;
LEDs[6].blue = 0x80;
LEDs[7].green = 0x40;
LEDs[7].red = 0x20;
LEDs[7].blue = 0x80;
// Initialize all LEDs to 0x00
for (i = 0; i < NUM_LEDS; i++)
{
LEDs[i].green = 0x80;
LEDs[i].red = 0x80;
LEDs[i].blue = 0x80;
}
// Write to WS28128B LEDs
// typecast the LEDs pointer as an unsigned 8 bit integer
WS2812B_write(WS2812B_GPIO_ADDR, (uint8_t *) LEDs, NUM_LEDS);
// Infinite Loop
while(1)
{
// rotate the WS2812B_t array
ws2812b_pulse( LEDs, NUM_LEDS);
WS2812B_write(WS2812B_GPIO_ADDR, (uint8_t *) LEDs, NUM_LEDS);
// loop to delay the rotation of the WS28128B LEDs
// should exit when counts from 0 to 500000
// after rotated LEDs, write new colors using WS28128_write
for (i = 0; i < 500000; i++)
{
continue;
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
if(argc != 2) return -1;
int s=atoi(argv[1]);
if(!s){
puts("Division by zero detected -- aborting");
s=1/s;
}
printf("The entered number was %d\n", s);
return 0;
}
|
C
|
/*************************************************************************
> File Name: httpd.c
> Author: fx
> Mail: 1007160080qq.com
> Created Time: Fri 18 Aug 2017 07:50:06 AM PDT
************************************************************************/
#include"httpd.h"
void print_log(const char* str,int error)
{
char* err[2] = {"WARNING","FATAL"};
openlog("print_log",LOG_CONS|LOG_PID,LOG_USER);
syslog(LOG_INFO,"%s%s\n",str,err[error]);
closelog();
}
int startup(const char* ip,const char* port)
{
assert(ip);
assert(port);
int sock = socket(AF_INET,SOCK_STREAM,0);
if(sock < 0)
{
print_log("socket error -- ",FATAL);
exit(1);
}
int opt = 1;
if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)) < 0)
{
printf("setsockopt error -- ",WARNING);
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(atoi(port));
addr.sin_addr.s_addr = inet_addr(ip);
int len = sizeof(addr);
if(bind(sock,(struct sockaddr*)&addr,len) < 0)
{
print_log("bind error -- ",FATAL);
close(sock);
exit(2);
}
if(listen(sock,5) < 0)
{
print_log("listen error -- ",FATAL);
close(sock);
exit(3);
}
return sock;
}
int get_line(int sock,char* buf,int size)
{
int i = 0;
char c = '\0';
int n;
//将终止条件统一为 \n 换行符,标准化buf数组
while((i < size-1) && (c != '\n'))
{
//一次接受一个字节
n = recv(sock,&c,1,0);
if( n > 0)
{
//收到 \r 则继续接收下一个字符,因为换行符可能是 \r\n
if(c == '\r')
{
//使用MSG_PEEK标志使下一次读取依然可以得到这次读取的内容
n = recv(sock,&c,1,MSG_PEEK);
if((n > 0) && (c == '\n'))
recv(sock,&c,1,0);
else
c = '\n';
}
//存到缓冲区
buf[i] = c;
i++;
}
else
c = '\n';
}
buf[i] = '\0';
return i;
}
void clear_header(int sock)
{
char buf[1024];
int ret = 0;
do
{
ret = get_line(sock,buf,sizeof(buf));
}while(ret != 1 && strcmp("\n",buf));
}
int echo_www(int sock,const char* path,int size)
{
printf("This os echo_www!\n");
int outfd = open(path,O_RDONLY);
if(outfd < 0)
{
print_log("open file(get outfd) error -- ",FATAL);
return -1;
}
char buf[200] = "HTTP/1.0 200 OK\r\n\r\n<html><html>";
int headret = send(sock,buf,sizeof(buf),0);
if(headret <= 0)
{
print_log("ECHO head is error -- ",FATAL);
return -1;
}
int ret = 0;
if((ret = sendfile(sock,outfd,0,size)) < 0)
{
print_log("ECHO (CGI=0) is error -- ",FATAL);
return -1;
}
return ret;
}
void Dealwithsock(int sock)
{
char buf[SIZE];
char method[100];
char url[1024];
char path[512];
char Deal[100];
char* query_string = NULL;
int cgi = 0;
int s = get_line(sock,buf,sizeof(buf));
int i = 0;
int j = 0;
printf("%s\n",buf);
while(!isspace(buf[i]) && i < (sizeof(method)-1))
{
method[i] = buf[i];
i++;
}
method[i]='\0';
while(isspace(buf[i]) && i<sizeof(buf))
i++;
while(!isspace(buf[i]) && j < (sizeof(url)-1))
{
url[j] = buf[i];
i++;
j++;
}
if(strcasecmp("GET",method) && strcasecmp("POST",method))
{
print_log("Method is error -- ",FATAL);
close(sock);
exit(3);
}
if(!strcasecmp("POST",method))
{
cgi = 1;
}
if(!strcasecmp("GET",method))
{
j = 0;
while(url[j] != '?' && j < sizeof(path)-1)
{
path[j] = url[j];
j++;
}
path[j] = '\0';
if(url[j] == '?')
{
cgi = 1;
query_string = url + j + 1;
}
}
while(isspace(buf[i]) && i < sizeof(buf))
{
i++;
}
int k = 0;
while(!isspace(buf[i]) && k < sizeof(Deal)-1)
{
Deal[k] = buf[i];
k++;
i++;
}
printf("CGI: %d\n",cgi);
printf("Method: %s\n",method);
printf("path: %s\n",path);
printf("url: %s\n",url);
printf("Deal: %s\n",Deal);
char All_path[512] = {0};
sprintf(All_path,"wwwroot%s",path);
printf("All_path: %s\n",All_path);
if(All_path[strlen(All_path)-1] == '/')
{
printf(" '\\' exist...\n");
strcat(All_path,"index.html");
printf("Allpath is :%s\n",All_path);
}
struct stat st;
if(stat(All_path,&st) < 0)
{
clear_header(sock);
print_log("FILE is unknow -- ",FATAL);
exit(4);
}
else
{
printf(" '\\' no exist..\n");
if(st.st_mode & S_IFDIR)
{
printf("file is dir..\n");
All_path[strlen(All_path)] = '/';
strcat(All_path,"index.html");
printf("AllPath:%s\n",All_path);
}
}
printf("CGI: %d\n",cgi);
if((st.st_mode & S_IXUSR) ||\
(st.st_mode & S_IXGRP) || \
(st.st_mode & S_IXOTH))
{
cgi = 1;
}
printf("CGI: %d\n",cgi);
if(cgi == 1)
{
echo_cgi(sock,method,All_path,query_string);
}
else
{
printf("cgi = 0\n");
clear_header(sock);
printf("cgi = 0\n");
int ret = echo_www(sock,All_path,st.st_size);
if(ret < 0)
{
print_log("echo_www is error -- ",FATAL);
exit(5);
}
close(sock);
}
}
int echo_cgi(int sock,const char* method,const char* path,const char* query)
{
char buf[1024] = {0};
int len = 0;
printf("This is echo_cgi()!!!\n");
if(strcmp("GET",method) != 0)
{
//POST
printf("POST\n");
int ret = 0;
do
{
ret = get_line(sock,buf,sizeof(buf));
printf("%s\n",buf);
if(strncmp("Connect-Length:",buf,15) == 0)
{
len = atoi(&(buf[16]));
}
}
while(ret > 0 && *buf != '\n');
printf("len is %d\n",len);
if(len <= 0)
{
print_log("Content-Length is error --",FATAL);
exit(-1);
}
}
else
{
//GET
printf("This is echo_cgi()-->GET!\n");
clear_header(sock);
}
int input[2];
int output[2];
if(pipe(input) < 0 || pipe(output) < 0)
{
print_log("pipe create error -- ",FATAL);
close(sock);
exit(-1);
}
printf("pipe is successful\n");
pid_t id = 0;
id = fork();
printf("!!!!! id = %d\n",id);
if(id < 0)
{
print_log("fork child error -- ",FATAL);
close(sock);
exit(-1);
}
else if(id > 0)//parent
{
printf("This is parent!\n");
close(input[0]);
close(output[1]);
if(strcasecmp("POST",method) == 0)
{
char ch = '\0';
int i = 0;
for(i = 0; i<len; i++)
{
recv(sock,&ch,1,0);
write(input[1],&ch,1);
}
}
char ch = '\0';
while(read(output[0],&ch,1) > 0)
{
send(sock,&ch,1,0);
}
close(sock);
close(input[1]);
close(output[0]);
waitpid(id,NULL,0);
}
else//child
{
printf("This is child,\n");
close(input[1]);
close(output[0]);
dup2(input[0],0);
dup2(output[1],1);
char Method[255] = {0};
char content_len[255] = {0};
char query_string[255] = {0};
sprintf(Method,"METHOD=%s",method);
putenv(Method);
if(!strcasecmp(method,"POST"))
{
sprintf(content_len,"CONTENT_LEN=%s",len);
putenv(content_len);
}
if(!strcasecmp(method,"GET"))
{
sprintf(query_string,"QUERY_STRING=%s",query);
putenv(query_string);
}
execl(path,path,NULL);
printf("execl is error\n");
exit(0);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef RED_BLACK_CODE_H_
#define RED_BLACK_CODE_H_
typedef struct Red_black red_black;
typedef struct root_rb root;
//Creates an empty tree and sets it as root
root_rb *create_root_tree ();
//Creates a new node of the tree
red_black *add_red_black (int data);
//Checks the value of the node's brother. If they're equals, returns the parameter node. Else, it returns the node's brother.
red_black *brother_node (red_black *rb);
//Returns the father of a node's brother
red_black *uncle_node (red_black *rb);
//Returns the grandfather node of the tree
red_black *grand_father_node (red_black *rb);
//Checks the color of a node
int node_color (red_black *rb);
//Changes the color of a node, but doesn't affect the values or content of the tree
void change_color (red_black *rb);
/*B node changes place with A node.
A node becomes the left son of B node.
B node recieves the color of A node and A node turns to red, may a color correction for A node be necessary*/
void left_rotate (red_black *node_a);
/*The A node changes position with B node and becomes B node's right son.
B node recieves the color of A node and A node becomes red*/
void right_rotate (red_black *node_a);
//Replaces a node with a new node, according to the value
void replace_node (root *root_tree, red_black *rb, red_black *new_rb);
/* Verifies if the root is NULL and creates a new root if needs, or it inserts the new node and colors the tree*/
void insert_red_black (red_black *rb, void *data);
//Recolors the tree to maintain the right properties of a red-black tree
void case1 (root *root_tree, red_black *rb);
void case2 (root *root_tree, red_black *rb);
void case3 (root *root_tree, red_black *rb);
void case4 (root *root_tree, red_black *rb);
void case5 (root *root_tree, red_black *rb);
//Deletes a node of the tree and checks the properties to rebalance and maintain the properties
void delete_red_black (Root *root_tree, int value);
void delete_case1 (root *root_tree, red_black *rb);
void delete_case2 (root *root_tree, red_black *rb);
void delete_case3 (root *root_tree, red_black *rb);
void delete_case4 (root *root_tree, red_black *rb);
void delete_case5 (root *root_tree, red_black *rb);
void delete_case6 (root *root_tree, red_black *rb);
//Prints the tree in pre order
void print_pre_order (root *root_tree);
//Prints the tree in order
void print_in_order (red_black *rb);
//Returns the node with maximum value
red_black *node_max (red_black *rb);
//Searches a value on the tree
red_black *search(root *root_rb, int value);
|
C
|
/**
* Hash chain functions for packet authentication and
* packet signatures
*
* Description:
*
* Authors:
* - Tobias Heer <heer@tobobox.de> 2006
* - Rene Hummen <rene.hummen@rwth-aachen.de> 2008
*
* Licence: GNU/GPL
*
*/
#ifndef HASH_CHAIN_H
#define HASH_CHAIN_H
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/md5.h>
#include "hashtree.h"
/* longest digest in openssl lib */
#ifdef SHA512_DIGEST_LENGTH
# define MAX_HASH_LENGTH SHA512_DIGEST_LENGTH
#else
# define MAX_HASH_LENGTH 64
#endif
/* hash function used for the creation and verification of the hash chain */
typedef unsigned char * (*hash_function_t)(const unsigned char *, size_t,
unsigned char *);
typedef struct hash_chain
{
/* pointer to the hash-function used to create and verify the hchain
*
* @note params: (in_buffer, in_length, out_buffer)
* @note out_buffer should be size MAX_HASH_LENGTH */
hash_function_t hash_function;
int hash_length; /* length of the hashes, of which the hchain consist */
int hchain_length; /* number of initial elements in the hash-chain */
int hchain_hierarchy; /* hierarchy this hchain belongs to */
int current_index; /* index to currently revealed element for hchain traversal*/
unsigned char * elements; /* array containing the elements of the hash chain*/
hash_tree_t *link_tree; /* pointer to a hash tree for linking hchains */
} hash_chain_t;
/** prints the hash chain
*
* @param hash_chain the hash chain to be printed
*/
void hchain_print(const hash_chain_t * hash_chain);
/** checks if a hash is part of a hash chain
*
* @param current_hash the hash value to be verified
* @param lasl_hash the last known hash value
* @param hash function the hash function to be used
* @param hash_length length of the hash values
* @param tolerance the maximum number of hash calculations
* @param secret the potentially incorporated secret
* @param secret_length length og the secret
* @return hash distance if the hash authentication was successful, 0 otherwise
*/
int hchain_verify(const unsigned char * current_hash, const unsigned char * last_hash,
hash_function_t hash_function, int hash_length, int tolerance,
unsigned char *secret, int secret_length);
/** creates a new hash chain
*
* @param hash_function hash function to be used to generate the hash values
* @param hash_length length of the hash values
* @param hchain_length number of hash elements
* @param hchain_hierarchy the hierarchy level this hash chain will belong to
* @param link_tree the link tree, if HHL is used
* @return pointer to the newly created hash chain
*/
hash_chain_t * hchain_create(hash_function_t hash_function, int hash_length,
int hchain_length, int hchain_hierarchy, hash_tree_t *link_tree);
unsigned char * hchain_get_anchor(const hash_chain_t *hash_chain);
unsigned char * hchain_get_seed(const hash_chain_t *hash_chain);
unsigned char * hchain_element_by_index(const hash_chain_t *hash_chain, int index);
int hchain_set_current_index(hash_chain_t *hash_chain, int index);
/** removes and returns the next element from the hash chain
*
* @param hash_chain the hash chain which has to be popped
* @return pointer to the current hashchain element or NULL if the hash chain is depleted
*/
unsigned char * hchain_pop(hash_chain_t * hash_chain);
/** returns the next element of the hash chain but does not advance the current element
* pointer. This function should only be used if the next element is kept secret and has to
* be used for special purposes like message signatures.
*
* @param hash_chain the hash chain
* @return next element of the hash chain or NULL if the hash chain is depleted
*/
unsigned char * hchain_next(const hash_chain_t *hash_chain);
unsigned char * hchain_previous(hash_chain_t * hash_chain);
/** returns the current element of the hash chain
*
* @param hash_chain the hash chain
* @return current element of the hash chain or NULL if the hash chain is depleted
*/
unsigned char * hchain_current(const hash_chain_t *hash_chain);
/** delete hash chain and free memory
*
* @param hash_chain the hash chain which has to be removed
* @return 0 in case of success
*/
int hchain_free(hash_chain_t *hash_chain);
unsigned char * hchain_push(hash_chain_t * hash_chain);
int hchain_reset(hash_chain_t *hash_chain);
/** accessor function which returns the number of remaining hash chain elements
*
* @param hash_chain the hash chain
* @return number of remaining elements
*/
int hchain_get_num_remaining(const hash_chain_t * hash_chain);
#if 0
/*************** Helper functions ********************/
int concat_n_hash_SHA(unsigned char *hash, unsigned char** parts, int* part_length,
int num_parts);
#endif
#endif /*HASH_CHAIN_H*/
|
C
|
#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
/*
// 27.1: Compile and run the simple stand-alone interpreter (Figure 27.1, “A bare-bones stand-alone Lua interpreter”).
int main(void) {
char buff[256];
int error;
lua_State *L = luaL_newstate();
luaL_openlibs(L);
while(fgets(buff, sizeof(buff), stdin) != NULL){
error = luaL_loadstring(L, buff) || lua_pcall(L, 0, 0, 0);
if (error) {
fprintf(stderr, "%s\n", lua_tostring(L, -1));
lua_pop(L, 1);
}
}
lua_close(L);
return 0;
}
//*/
/*
// 27.2: Assume the stack is empty. What will be its contents after the following sequence of calls?
// lua_pushnumber(L, 3.5);
// lua_pushstring(L, "hello");
// lua_pushnil(L);
// lua_rotate(L, 1, -1);
// lua_pushvalue(L, -2);
// lua_remove(L, 1);
// lua_insert(L, -2);
// 27.3:
static void stackDump (lua_State *L) {
int i;
int top = lua_gettop(L); // depth of the stack
for (i = 1; i <= top; i++) { // repeat for each level
int t = lua_type(L, i);
switch (t) {
case LUA_TSTRING: { //s trings
printf("'%s'", lua_tostring(L, i));
break;
}
case LUA_TBOOLEAN: { // Booleans
printf(lua_toboolean(L, i) ? "true" : "false");
break;
}
case LUA_TNUMBER: { // numbers
printf("%g", lua_tonumber(L, i));
break;
}
default: { // other values
printf("%s", lua_typename(L, t));
break;
}
}
printf(" "); // put a separator
}
printf("\n"); // end the listing
}
int main(void) {
lua_State *L = luaL_newstate();
lua_pushnumber(L, 3.5);
lua_pushstring(L, "hello");
lua_pushnil(L);
stackDump(L);
lua_rotate(L, 1, -1);
stackDump(L);
lua_pushvalue(L, -2);
stackDump(L);
lua_remove(L, 1);
stackDump(L);
lua_insert(L, -2);
stackDump(L);
lua_close(L);
return 0;
}
//*/
//*
// Exercise 27.4: Write a library that allows a script to limit the total amount of memory used by its Lua state.
// It may offer a single function, setlimit, to set that limit.
// The library should set its own allocation function. This function, before calling the original allocator,
// checks the total memory in use and returns NULL if the requested memory exceeds the limit.
// (Hint: the library can use the user data of the allocation function to keep its state: the byte count, the current
// memory limit, etc.; remember to use the original user data when calling the original allocation function.)
typedef struct UMemLimit {
lua_Alloc frealloc; /* function to reallocate memory */
void *ud; /* auxiliary data to 'frealloc' */
size_t bytecount;
size_t memlimit;
} UMemLimit;
static void *l_alloc_withmemlimit (void *ud, void *ptr, size_t osize, size_t nsize) {
UMemLimit *umem = (UMemLimit *)ud;
printf("Try use new alloc: %016p, %d, %d, %d\n", ptr, osize, nsize, umem->bytecount);
size_t newcount;
if (ptr == NULL){
newcount = umem->bytecount + nsize;
}
else{
if (umem->bytecount + nsize >= osize)
newcount = umem->bytecount + nsize - osize;
else
newcount = 0;
}
if (newcount > umem->memlimit){
printf("Alloc exceed limit\n");
printf("newsize: %d + current: %d > limit: %d, \n", newcount, umem->bytecount, umem->memlimit);
return NULL;
}
else{
umem->bytecount = newcount;
return umem->frealloc(umem->ud, ptr, osize, nsize);
}
}
static void setlimit(lua_State *L, size_t memlimit){
UMemLimit *umem = (UMemLimit *)lua_newuserdata(L, sizeof(UMemLimit));
umem->frealloc = lua_getallocf(L, &(umem->ud));
umem->bytecount = 0;
umem->memlimit = memlimit;
lua_setallocf(L, l_alloc_withmemlimit, umem);
}
int main(void) {
lua_State *L = luaL_newstate();
setlimit(L, 1<<16);
char buff[256];
int error;
luaL_openlibs(L);
lua_close(L);
return 0;
}
//*/
|
C
|
/**
Составьте программу, которая принимает с клавиатуры целое число, соответствующее порядковому номеру месяца.
В случае, если полученное значение равно порядковому номеру одного из месяцев,
следует вывести сезон (лето, осень, зима, весна), к которому относится месяц.
В случае, если введенное значение не является порядковым номером месяца,
следует вывести на экран сообщение об ошибке.
ПРОВЕРКА:
ввод: 10 ⇒ вывод: это осень; ввод: 15 ⇒ вывод: ошибка)
*/
#include<stdio.h>
main()
{
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
//ֲ̬
void Test()//һTest
{
static int i = 0;
i++;
printf("%d\n",i);
}
int main(){
int i = 0;
for (; i < 10; i++)
{
Test();//Testĵ
}
return 0;
}
|
C
|
#include <string.h>
#include <stdlib.h>
#include "../stack/stack.h"
#include "tree.h"
/* From leetcode 208 */
/** Initialize your data structure here. */
Trie* trieCreate()
{
Trie *t = (Trie*) malloc(sizeof(Trie));
memset(t, 0, sizeof(Trie));
t->end = 0;
return t;
}
/** Inserts a word into the trie. */
void trieInsert(Trie *obj, char *word)
{
while (*word) {
if (!obj->child[*word-'a'])
obj->child[*word-'a'] = trieCreate();
obj = obj->child[*word-'a'];
++word;
}
obj->end = 1;
}
/** Returns if the word is in the trie. */
bool trieSearch(Trie *obj, char *word)
{
while (*word) {
if (!obj->child[*word-'a'])
return false;
obj = obj->child[*word-'a'];
word++;
}
return (obj->end);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool trieStartsWith(Trie *obj, char *prefix) {
while (*prefix) {
if (!obj->child[*prefix-'a'])
return false;
obj = obj->child[*prefix-'a'];
prefix++;
}
return true;
}
void trieFree(Trie *obj)
{
int i;
if (!obj)
return;
for (i=0; i<26; i++) {
if (obj->child[i])
trieFree(obj->child[i]);
}
free(obj);
}
void trieFree_notrec(Trie *obj)
{
int i;
stack_t *stack;
Trie *t;
if (!obj)
return;
stack = init_stack();
stack->push(stack, obj);
while (!stack->empty(stack)) {
t = (Trie*) stack->pop(stack);
for (i=0; i<26; i++)
if (t->child[i])
stack->push(stack, t->child[i]);
free(t);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
#include <sysexits.h>
#include <ctype.h>
#include <wordexp.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
/*
* Autores:
*
* Barata Gonzalez, Jorge
* Galan Galiano, Cristian
*
* */
/**
* Funciones
* */
void recibir(int serverConnected, char* copia, unsigned int longitud);
char* obtenerIpServer(char* server);
/**
* Atributos Globales:
* */
int debug = 0;
int serverConnected;
int servicio;
void usage(char *program_name) {
printf("Usage: %s [-d] -s <server> -p <port>\n", program_name);
}
void f_ping(){
if (debug)
printf("PING\n");
// Write code here
servicio = 1;
struct timespec ini, end;
//Tiempo
clock_gettime(CLOCK_REALTIME, &ini);
if(write(serverConnected, &servicio, sizeof(int)) < 0){
perror("No se puede enviar el servicio de ping.");
exit(-1);
}
char ack;
if(read(serverConnected, &ack, sizeof(char)) < 0){
perror("No se puede recibir el servicio de ping.");
exit(-1);
}
//Tiempo
clock_gettime( CLOCK_REALTIME, &end);
fprintf(stderr, "%f s\n", (float)(1.0*(1.0*end.tv_nsec - ini.tv_nsec*1.0)*1e-9 + 1.0*end.tv_sec - 1.0*ini.tv_sec));
}
void f_swap(char *src, char *dst){
if (debug)
printf("SWAP <SRC=%s> <DST=%s>\n", src, dst);
// Write code here
servicio = 2;
//Le envia el tipo de servicio que es
if(write(serverConnected, &servicio, sizeof(int)) <0 ){
perror("No se puede enviar el servicio de swap");
exit(-1);
}
//Obtiene los datos del fichero
FILE *archivo = fopen(src,"r");
if(archivo == NULL)
exit(1);
char caracteres[10];
int total = 0;
char* copia = calloc(total, sizeof(char));
char* resultado;
//Se obtiene el fichero
while (fgets(caracteres,10,archivo) != NULL)
{
total = total + 10;
resultado = calloc(total, sizeof(char));
strcpy(resultado, copia);
strcat(resultado, caracteres);
copia = calloc(total, sizeof(char));
strcpy(copia, resultado);
}
free(resultado);
fclose(archivo);
//Le envia la longitud del texto
unsigned int longitud = strlen(copia);
if(write(serverConnected, &longitud, sizeof(unsigned int)) != sizeof(unsigned int)){
perror("No se puede enviar el servicio de swap: Longitud.");
fprintf(stderr, "Error: %u", longitud);
exit(-1);
}
//Le envia un cadena
if(write(serverConnected, copia, longitud) != longitud){
perror("No se puede enviar el servicio de swap: Cadena");
fprintf(stderr, "Error: %s", copia);
exit(-1);
}
//Recibe la cantidad de letras cambiadas
unsigned int letrasCambiadas = 0;
if(read(serverConnected, &letrasCambiadas, sizeof(unsigned int)) != sizeof(unsigned int)){
perror("No se puede recibir el servicio de swap: LetrasCambiadas");
fprintf(stderr, "Error: %u", letrasCambiadas);
exit(-1);
}
//Recibe la nueva cadena
free(copia);
copia = calloc(longitud, sizeof(char));
recibir(serverConnected,copia, longitud);
//Se imprime por pantalla
fprintf(stderr, "%i\n", letrasCambiadas);
//Graba los datos en un fichero
FILE *archivo2 = fopen(dst,"w");
if(archivo2 == NULL)
exit(1);
fputs(copia, archivo2);
fclose(archivo2);
free(copia);
}
void f_hash(char *src){
if (debug)
printf("HASH <SRC=%s>\n", src);
// Write code here
servicio = 3;
if(write(serverConnected, &servicio, sizeof(int)) <0 ){
perror("No se puede enviar el servicio de hash");
exit(-1);
}
//Obtiene los datos del fichero
FILE *archivo;
char caracteres[10];
archivo = fopen(src,"r");
if(archivo == NULL)
exit(1);
int total = 0;
char* copia = calloc(total, sizeof(char));
char* resultado;
while (fgets(caracteres,10,archivo) != NULL)
{
total = total + 10;
resultado = calloc(total, sizeof(char));
strcpy(resultado, copia);
strcat(resultado, caracteres);
copia = calloc(total, sizeof(char));
strcpy(copia, resultado);
}
free(resultado);
fclose(archivo);
//Le envia la longitud del fichero
unsigned int longitud = strlen(copia);
if(write(serverConnected, &longitud, sizeof(unsigned int)) != sizeof(unsigned int)){
perror("No se puede enviar el servicio de hash: Longitud");
exit(-1);
}
//Le envia una cadena
if(write(serverConnected, copia, longitud) != longitud){
perror("No se puede enviar el servicio de hash: Cadena.");
exit(-1);
}
//Recibe el valor de hash
unsigned int hash = 0;
if(read(serverConnected, &hash, sizeof(unsigned int)) != sizeof(unsigned int)){
perror("No se puede recibir el servicio de hash: Hash.");
exit(-1);
}
//Se imprime por pantalla
fprintf(stderr, "%u\n", hash);
free(copia);
}
void f_check(char *src, int hash){
if (debug)
printf("CHECK <SRC=%s> <HASH=%d>\n", src, hash);
// Write code here
servicio = 4;
if(write(serverConnected, &servicio, sizeof(int)) <0 ){
perror("No se puede enviar el servicio de check");
exit(-1);
}
//Obtiene los datos del fichero
FILE *archivo;
char caracteres[10];
archivo = fopen(src,"r");
if(archivo == NULL)
exit(1);
int total = 0;
char* copia = calloc(total, sizeof(char));
char* resultado;
while (fgets(caracteres,10,archivo) != NULL)
{
total = total + 10;
resultado = calloc(total, sizeof(char));
strcpy(resultado, copia);
strcat(resultado, caracteres);
copia = calloc(total, sizeof(char));
strcpy(copia, resultado);
}
free(resultado);
fclose(archivo);
//Le envia la longitud del texto
int longitud = strlen(copia);
if(write(serverConnected, &longitud, sizeof(unsigned int)) != sizeof(unsigned int)){
perror("No se puede enviar el servicio de check: Longitud.");
exit(-1);
}
//Le envia una cadena
if(write(serverConnected, copia, longitud) != longitud){
perror("No se puede enviar el servicio de check: Cadena.");
exit(-1);
}
//Le envia el valor hash
unsigned int uhash = hash;
if(write(serverConnected, &uhash, sizeof(unsigned int)) != sizeof(unsigned int)){
perror("No se puede enviar el servicio de check: Hash.");
exit(-1);
}
//Recibe si es correcto o falso la funcion resumen
char correcto;
if(read(serverConnected, &correcto, sizeof(char)) != sizeof(char)){
perror("No se puede recibir el servicio de check: Correcto.");
exit(-1);
}
//Se imprime por pantalla
if(correcto == 0)
fprintf(stderr, "FAIL\n");
else
fprintf(stderr, "OK\n");
free(copia);
}
void f_stat(){
if (debug)
printf("STAT\n");
// Write code here
servicio = 5;
if(write(serverConnected, &servicio, sizeof(int)) <0 ){
perror("No se puede enviar el servicio de stat");
exit(-1);
}
//Recibe el valor de ping
unsigned int ping;
if(read(serverConnected, &ping, sizeof(unsigned int)) != sizeof(unsigned int)){
perror("No se puede recibir el servicio de stat: Ping.");
exit(-1);
}
//Se imprime por pantalla
fprintf(stderr, "ping %u \n", ping);
//Recibe el valor de swap
unsigned int swap;
if(read(serverConnected, &swap, sizeof(unsigned int)) != sizeof(unsigned int)){
perror("No se puede recibir el servicio de stat: Swap.");
exit(-1);
}
//Se imprime por pantalla
fprintf(stderr, "swap %u \n", swap);
//Recibe el valor de hash
unsigned int hash;
if(read(serverConnected, &hash, sizeof(unsigned int)) != sizeof(unsigned int)){
perror("No se puede recibir el servicio de stat: Hash.");
exit(-1);
}
//Se imprime por pantalla
fprintf(stderr, "hash %u \n", hash);
//Recibe el valor de check
unsigned int check;
if(read(serverConnected, &check, sizeof(unsigned int)) != sizeof(unsigned int)){
perror("No se puede recibir el servicio de stat: Check.");
exit(-1);
}
//Se imprime por pantalla
fprintf(stderr, "check %u \n", check);
//Recibe el valor de stat
unsigned int stat;
if(read(serverConnected, &stat, sizeof(unsigned int)) != sizeof(unsigned int)){
perror("No se puede recibir el servicio de stat: Stat.");
}
//Se imprime por pantalla
fprintf(stderr, "stat %u \n", stat);
}
void quit(){
if (debug)
printf("QUIT\n");
// Write code here
servicio = 6;
if(write(serverConnected, &servicio, sizeof(int)) <0 ){
perror("No se puede enviar el servicio de quit");
}
}
void recibir(int serverConnected, char* copia, unsigned int longitud){
//Envia la nueva copia de la cadena
int datosRestantes = longitud;
int enviado = 0;
while (datosRestantes != 0){
char* cadena = calloc(datosRestantes, sizeof(char));
enviado = read(serverConnected, cadena, datosRestantes);
datosRestantes = datosRestantes - enviado;
strcat(copia, cadena);
free(cadena);
}
}
//Obtiene la ip a traves de su hostname
char* obtenerIpServer(char* server) {
struct sockaddr_in host;
host.sin_addr = * (struct in_addr*) gethostbyname(server)->h_addr;
return inet_ntoa(host.sin_addr);
}
void shell() {
char line[1024];
char *pch;
int exit = 0;
wordexp_t p;
char **w;
int ret;
memset(&p, 0, sizeof(wordexp));
do {
fprintf(stdout, "c> ");
memset(line, 0, 1024);
pch = fgets(line, 1024, stdin);
if ( (strlen(line)>1) && ((line[strlen(line)-1]=='\n') || (line[strlen(line)-1]=='\r')) )
line[strlen(line)-1]='\0';
ret=wordexp((const char *)line, &p, 0);
if (ret == 0) {
w = p.we_wordv;
if ( (w != NULL) && (p.we_wordc > 0) ) {
if (strcmp(w[0],"ping")==0) {
if (p.we_wordc == 1)
f_ping();
else
printf("Syntax error. Use: ping\n");
} else if (strcmp(w[0],"swap")==0) {
if (p.we_wordc == 3)
f_swap(w[1],w[2]);
else
printf("Syntax error. Use: swap <source_file> <destination_file>\n");
} else if (strcmp(w[0],"hash")==0) {
if (p.we_wordc == 2)
f_hash(w[1]);
else
printf("Syntax error. Use: hash <source_file>\n");
} else if (strcmp(w[0],"check")==0) {
if (p.we_wordc == 3)
f_check(w[1], atoi(w[2]));
else
printf("Syntax error. Use: check <source_file> <hash>\n");
} else if (strcmp(w[0],"stat")==0) {
if (p.we_wordc == 1)
f_stat();
else
printf("Syntax error. Use: stat\n");
} else if (strcmp(w[0],"quit")==0) {
quit();
exit = 1;
} else {
fprintf(stderr, "Error: command '%s' not valid.\n", w[0]);
}
}
wordfree(&p);
}
} while ((pch != NULL) && (!exit));
}
int main(int argc, char *argv[]){
char *program_name = argv[0];
int opt, port=0;
char *server, *port_s;
// Parse command-line arguments
while ((opt = getopt(argc, argv, "ds:p:")) != -1) {
switch (opt) {
case 'd':
debug = 1;
break;
case 's':
server = optarg;
break;
case 'p':
port_s = optarg;
port = strtol(optarg, NULL, 10);
break;
case '?':
if ((optopt == 's') || (optopt == 'p'))
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);
default:
usage(program_name);
exit(EX_USAGE);
}
}
if ((port < 1024) || (port > 65535)) {
fprintf (stderr, "Error: Port must be in the range 1024 <= port <= 65535\n");
usage(program_name);
exit(EX_USAGE);
}
if (debug)
printf("SERVER: %s PORT: %d\n",server, port);
/*
* EMPIEZA EL CODIGO PROPIO
* NO SE SI HAY QUE USAR STDERR O STDOUT. Realmente no piden salida, se puede usar printf.
**/
struct sockaddr_in serverIn;
//Se crea el socket
serverConnected = socket(AF_INET, SOCK_STREAM, 0);
if(serverConnected < 0){
perror("Error creando socket");
}
//Obtiene la direccion del servidor
serverIn.sin_family = AF_INET;
serverIn.sin_port = htons(port);
serverIn.sin_addr.s_addr = inet_addr(server);
//serverIn.sin_addr.s_addr = INADDR_ANY;
//Comprueba si se puede conectar
if(connect(serverConnected, (struct sockaddr *) &serverIn, sizeof(serverIn)) <0){
char* ip = obtenerIpServer(server);
serverIn.sin_addr.s_addr = inet_addr(ip);
if(connect(serverConnected, (struct sockaddr *) &serverIn, sizeof(serverIn)) <0){
fprintf(stderr, "Error en la conexion con el servidor %s:%i", server, port);
exit(-1);
}else
shell();
}else
shell();
close(serverConnected);
exit(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/defs.h>
#include <sys/syscall.h>
DIR *opendir(const char *name)
{
int fd = -1;
if (-1 == (fd = open(name, O_DIRECTORY))) {
printf("open : %s failed.", name);
return NULL;
}
DIR *dir = (DIR *) malloc(sizeof(DIR));
dir->dfd = fd;
dir->ptr_dir = (struct dirent *) malloc(sizeof(struct dirent));
return dir;
}
|
C
|
#include <stdlib.h>
int main(void) {
/* Valgrind can detect that this allocates memory that is never freed: */
int *arr = (int *)malloc(sizeof(int) * 4);
return *arr;
}
|
C
|
#include "os.h"
#include "draw3.h"
#include "imgtools.h"
void
drawellipse(Image *dst, Rect dstr, intcoord *a, intcoord *b, intcoord rad, int pscl, uchar *color)
{
u32int *dstp, *dst_end, *dst_ustart, *dst_uend;
u32int color32;
int dst_stride;
int u, v;
intcoord ab[2];
intcoord tmp;
/* todo: do the bounding box right. this one's way too large */
tmp = (mini(a[0], b[0])-rad) >> pscl;
if(dstr.u0 < tmp)
dstr.u0 = tmp;
tmp = (mini(a[1], b[1])-rad) >> pscl;
if(dstr.v0 < tmp)
dstr.v0 = tmp;
tmp = ((maxi(a[0], b[0])+rad) >> pscl) + 1;
if(dstr.uend > tmp)
dstr.uend = tmp;
tmp = ((maxi(a[1], b[1])+rad) >> pscl) + 1;
if(dstr.vend > tmp)
dstr.vend = tmp;
ab[0] = b[0]-a[0];
ab[1] = b[1]-a[1];
rad += sqrtf(ab[0]*ab[0] + ab[1]*ab[1]);
dstr = cliprect(dstr, dst->r);
dst_stride = dst->stride/4;
dst_ustart = img_uvstart(dst, dstr.u0, dstr.v0, 1);
dst_end = dst_ustart + dst_stride*recth(&dstr);
dst_uend = dst_ustart + rectw(&dstr);
color32 = *(u32int *)color;
v = dstr.v0 << pscl;
float blend_limit, blend_factor;
blend_limit = (float)(1<<pscl);
blend_factor = 255.0f / blend_limit;
while(dst_ustart < dst_end){
dstp = dst_ustart;
u = dstr.u0 << pscl;
while(dstp < dst_uend){
float adst, bdst, dst;
int adst2, bdst2;
adst2 = (u-a[0])*(u-a[0]) + (v-a[1])*(v-a[1]);
bdst2 = (u-b[0])*(u-b[0]) + (v-b[1])*(v-b[1]);
adst = sqrtf(adst2);
bdst = sqrtf(bdst2);
dst = rad-(adst+bdst);
if(dst > 0.0f){
if(dst < blend_limit){ // todo: work out the math here. this fudge doesn't really work
dst *= blend_factor;
*dstp = blend32(*dstp, color32, (int)dst);
} else {
*dstp = color32;
}
}
dstp++;
u += 1<<pscl;
}
dst_ustart += dst_stride;
dst_uend += dst_stride;
v += 1<<pscl;
}
}
|
C
|
void p(char *buf, char *s)
{
char big_buffer[4104];
char *ptr;
puts(s);
read(0, big_buffer, 4096);
ptr = strchr(big_buffer, '\n');
*ptr = 0;
strncpy(buf, big_buffer, 20);
}
void pp(char *buff)
{
char s1[20];
char s2[20];
p(s1, " - ");
p(s2, " - ");
strcpy(buff, s1);
buff[strlen(s1)] = ' ';
strcat(buff, s2);
}
int main()
{
char buff[54];
pp(buff);
puts(buff);
return (0);
}
|
C
|
//
// main.c
// ReadWAVHeader
//
// Created by Mathias Lyngklip Kjeldgaard on 03/03/2017.
// Copyright © 2017 Mathias Lyngklip Kjeldgaard. All rights reserved.
//
#include <stdio.h>
// #define DEBUG_Mine 1
// #define WAVE_FILEN "kick.wav"
// const char WAVE_FILEN[] = "kick.txt";
#ifdef DEBUG_Mine
const char WAVE_FILEN[] = "kick.wav";
#endif
int main(int argc, const char * argv[]) {
printf("\n\n\n\n");
#ifdef DEBUG_Mine
// insert code here...
printf("argc: %d\n", argc);
// printf("argv[%d]: %s\n", argv[argc]);
for(int i = 0; i <= sizeof(&argv);i++){
printf("%s\n", argv[i]);
}
#endif
FILE * wave_file = NULL;
#ifndef DEBUG_Mine
if(argc > 1){
// printf("Got a filename from parameter\n");
wave_file = fopen(argv[1], "r");
if(wave_file == NULL){
// It failed opening the file
return -1;
}
} else
{
printf("Okay, you did not specifi a filename.\nEnter one now\n");
do{
char tempName[101];
scanf("%s", tempName);
wave_file = fopen(tempName, "r");
if(wave_file == NULL){
printf("Oops, wrong name, try again.\n");
}
} while(wave_file == NULL);
}// else
#endif
#if DEBUG_Mine == 1
wave_file = fopen(WAVE_FILEN, "r");
if(wave_file == NULL){
printf("Something went wrong\n");
} else { printf("Alt er godt!\n"); }
#endif
// Okay, filen er åben!
// fpos_t position;
// fsetpos(wave_file, &position); // Nu står vi i starten af filen
// char buffer[100];
/* Read and display data */
// fread(buffer, 2, 1, wave_file);
// 20 = AudioFormat
fseek(wave_file, 20, SEEK_SET); // Nu er vi i staren af det vi vil have!
char *tempChar = NULL;
// printf("tempChar: %X\n", tempChar);
fread(&tempChar, 2, 1, wave_file); // AudioFormat
int AudioFormat = 0;
AudioFormat = (unsigned)(int)tempChar;
printf("AudioFormat: %d\n", AudioFormat);
// Number of channels
fread(&tempChar, 2, 1, wave_file); // NumChannels
int NumChannels = 0;
NumChannels = (unsigned)(int)tempChar;
printf("NumChannels: %d\n", NumChannels);
tempChar = NULL;
// Samplerate
fread(&tempChar, 4, 1, wave_file); // SampleRate
int SampleRate = 0;
SampleRate = (unsigned)(int)tempChar;
printf("SampleRate: %d\n", SampleRate);
tempChar = NULL;
// ByteRate
fread(&tempChar, 4, 1, wave_file); // ByteRate
int ByteRate = 0;
ByteRate = (unsigned)(int)tempChar;
printf("ByteRate: %d\n", ByteRate);
tempChar = NULL;
// BlockAlign
fread(&tempChar, 2, 1, wave_file); // BlockAlign
int BlockAlign = 0;
BlockAlign = (unsigned)(int)tempChar;
printf("BlockAlign: %x\n", BlockAlign);
tempChar = NULL;
// BitsPerSample
// fseek(wave_file, 33, SEEK_SET);
fread(&tempChar, 2, 1, wave_file); // BitsPerSample
int BitsPerSample = 0;
BitsPerSample = (unsigned)(int)tempChar;
printf("BitsPerSample: %x\n", BitsPerSample);
tempChar = NULL;
return 0;
}
|
C
|
/* Huffman Code */
#include <cstdio>
#include <cstdlib>
#include <string>
#include <iostream>
#include <bitset>
#include <fstream>
#include <ctime>
#define CharCount 256
using namespace std;
/*Huffman Tree's Node*/
struct TreeNode{
int value;
int alpha;
string code;
TreeNode * lChild;
TreeNode * rChild;
TreeNode(){ value = 0; alpha = 0; lChild = rChild = NULL; code="";} //构造函数
};
/*链表结点,辅助构造Huffman树*/
struct ListNode{
TreeNode huffNode;
ListNode * child;
ListNode(){ child = NULL;} //构造函数
};
//保存输入文件的统计信息,hash表
struct hashTable{
int value;
int alpha;
hashTable(){alpha=0; value=0;}
}Ascii[CharCount];
//qsort的排序函数
int Comp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
TreeNode * CreateHuffmanTree(hashTable ascii[])
{
/*初始化建立二叉树森林,每个树只有一个结点,并把这些森林串到一个链表中*/
ListNode * root = new ListNode;
ListNode * next = root; //root指向第一个节点,此节点有信息
for(int i=0; /*i<127*/; i++)
{
if(ascii[i].value == 0)
continue;
next->huffNode.value = ascii[i].value;
next->huffNode.alpha = ascii[i].alpha;
if(i == CharCount-1) //防止多建一个无用的节点
break;
next->child = new ListNode;
next = next->child;
}
//如果森林中的树>1,就继续处理,直到森林(链表)中只有一颗树,这时Huffman树也已建成
while(root->child != NULL)
{
ListNode * p = new ListNode;
/*把新结点的权值设为最小两个结点的权值之和*/
p->huffNode.value = root->huffNode.value + root->child->huffNode.value;
/*把新结点中的Huffman节点中的左右子树设置为两个较小节点中的Huffman节点*/
p->huffNode.lChild = &(root->huffNode);
p->huffNode.rChild = &(root->child->huffNode);
/*从链表中删除最小的两个结点,但是内存不能释放,因为还要用这些节点构造Huffman树*/
root = root->child->child;
/*对链表重新排序,即把新建的这个结点插入到合适的位置,使链表的升序不被破坏*/
next = root;
ListNode * parent = NULL;
while( next != NULL && p->huffNode.value >= next->huffNode.value )
{
parent = next;
next = next->child;
}// find location
//insert
if(parent == NULL) // Insert into start.
{
p->child = next;
root = p;
}
else // Insert into middle or end.
{
p->child = next;
parent->child = p;
}
}
return &(root->huffNode);
}
/*字符-Huffman码表*/
string charHuffmanTable[CharCount];
/*字符串栈,用来在遍历Huffman树时得到Huffman编码*/
string stack;
/*树的前序遍历*/
void preorder(TreeNode * root)
{
// if(root == NULL)
// {
// stack.erase(stack.length()-2);
// return;
// }
// else
// {
//printf("%c %d\n", root->alpha, root->value);
if(root->lChild == NULL && root->rChild == NULL)
{
charHuffmanTable[root->alpha] = stack;
stack.erase(stack.length()-1);
return;
}
stack.append("0");
preorder(root->lChild);
stack.append("1");
preorder(root->rChild);
//cout << stack.length() << endl;
if(!stack.empty())
stack.erase(stack.length()-1);
// }
}
//传进来一个"10101001"的字符串,返回一个对应的ASCII字符
unsigned char StrToBin(string str)
{
int a = atoi(str.c_str());
int b = 1;
int ans = 0;
while(a != 0)
{
ans += a%10 * b;
b *= 2;
a /= 10;
}
return (unsigned char)ans;
}
//把unsigned char类型转换为2进制字符串
string BinToStr(unsigned char c)
{
string ans;
while(c != 0)
{
ans.insert(ans.begin(), (unsigned char)(c%2 + '0'));
c /= 2;
}
if(ans.length() < 8)
{
ans.insert(ans.begin(), 8-ans.length(), '0');
}
return ans;
}
/************************************************************************/
/*译码模块,返回译出的字符,删除string中已经用过的串 */
/************************************************************************/
char decode(TreeNode * root, string & code)
{
int i=0;
for( i=0; i<code.length(); i++)
{
if(root->alpha == 0)
root = (code[i]-'0') ? root->rChild : root->lChild;
else
{
code.erase(0,i);
return root->alpha;
}
}
if(root->alpha != 0)
{
code.erase(0,i);
return root->alpha;
}
code.erase();
return '\0';
}
int main(void)
{
/*读取文件并统计字符*/
FILE * fin = fopen("huffman.in", "r");
int c; //这里c不能定义为unsigned char 否则下面这个循环永远都结束不了,取不了EOF(-1)
while( (c=fgetc(fin)) != EOF )
{
//putchar(c);
Ascii[c].alpha = c;
Ascii[c].value++;
}
puts("");
qsort(Ascii, sizeof(Ascii)/sizeof(Ascii[0]), sizeof(Ascii[0]), Comp);
/*构造Huffman树*/
TreeNode * HuffmanRoot = CreateHuffmanTree(Ascii);//ok
/*建立字符-Huffman码表,结果存到charHuffmanTable[]*/
preorder(HuffmanRoot);
//---------Debug--------打印出统计信息----
cout << "Char\tTimes\tCode\n";
for(int i=0; i<CharCount; i++)
{
if(Ascii[i].value != 0)
{
cout << (char)Ascii[i].alpha << "\t" << Ascii[i].value << "\t" << charHuffmanTable[Ascii[i].alpha] << endl;
}
}//----------------Debug-------------------
/*编码并输出到压缩文件中*/
FILE * fout = fopen("huffman.bin","w");
rewind(fin); //重置文件指针
string buf;
while( (c=fgetc(fin)) != EOF )
{
buf += charHuffmanTable[c];
if(buf.length() >= 8)
{
fputc(StrToBin(buf.substr(0, 8)), fout);
buf.erase(0, 8);
}
//fwrite(charHuffmanTable[c].c_str(), 1, charHuffmanTable[c].length(), fout);
}
int appendZero = 0; //附加0的数量
if(!buf.empty())
{
appendZero = 8 - buf.length();
buf.append(appendZero, '0');
fputc(StrToBin(buf.substr(0, 8)), fout);
buf.erase(0, 8);
}
fclose(fin);
fclose(fout);
/*译码并输出到还原文件中*/
fin = fopen("huffman.bin", "rb");
fout = fopen("huffman.out", "w");
/*-----------Debug----------*/
/*-----------Debug----------*/
//unsigned char 因为这里有取值最高为11111111b,最小为-1,所以用int,short也可以
int uc;
/*----------------Debug-------------Rewrite---------*/
while( (uc=fgetc(fin)) != EOF ) //!feof(fin) ) //在把文件打开模式改为"rb"后,完美解决
{
buf += BinToStr(uc);
//cout << buf.substr(buf.length()-8) << " ";
//------Debug----Print------//
//cout << buf << endl;
}
/*-----------Debug----------*/
while(buf.length()-appendZero != 0 && !buf.empty())
{
//搜索Huffman树并译码
fputc(decode(HuffmanRoot, buf),fout);
//fputc(decode(HuffmanRoot, buf), fout);
}
fclose(fin);
fclose(fout);
printf("Time used: %d ms", clock());
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <mqueue.h>
#include <sys/mman.h>
#include <semaphore.h>
#define BSIZE 4 // Rozmiar bufora
#define LSIZE 80 // Dlugosc linii
typedef struct {
char buf[BSIZE][LSIZE];
int head;
int tail;
int cnt;
sem_t mutex;
sem_t empty;
sem_t full;
} bufor_t;
int main(int argc, char * argv[])
{
int i,stat,k, pid, size, fd, res, n;
bufor_t *wbuf ;
fd=shm_open("bufor", O_RDWR|O_CREAT , 0774);
// Odwzorowanie segmentu fd w obszar pamieci procesow
wbuf = ( bufor_t *)mmap(0,sizeof(bufor_t), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if(wbuf == NULL) {perror("map"); exit(-1); }
printf("Bufor ok\n");
printf("Producent\n");
for(i=0;i<10;i++) {
sem_wait(&(wbuf->empty));
sem_wait(&(wbuf->mutex));
sprintf(wbuf->buf[wbuf->head],"Komunikat %d",i);
printf("Komunikat %i -> Producent = cnt:%d head: %d tail: %d\n", i, wbuf-> cnt,wbuf->head,wbuf->tail);
wbuf-> cnt ++;
wbuf->head = (wbuf->head +1) % BSIZE;
sem_post(&(wbuf->mutex));
sem_post(&(wbuf->full));
sleep(1);
}
/*shm_unlink("bufor");
sem_close(&(wbuf->mutex));
sem_close(&(wbuf->empty));
sem_close(&(wbuf->full));*/
return(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person {
char name[30];
int age;
};
void bubbleSortint(struct person *p, int n)
{
int temp_age;
char temp_name[30];
for (int i = 0; i < n-1; i++){
for (int j = 0; j < n-i-1; j++){
if ((p+i)->age > (p+i+1)->age){
temp_age = (p+i+1)->age;
//temp_name = (p+i+1)->name;
strcmp(temp_name, (p+i+1)->name);
(p+i)->age = (p+i+1)->age;
// (p+i)->name = (p+i+1)->name;
strcmp((p+i)->name, (p+i+1)->name);
(p+i+1)->age = temp_age;
// (p+i+1)->name = temp_name;
strcmp((p+i+1)->name, temp_name);
}
}
}
}
void sortStrings(char arr[][100], int n)
{
char temp[100];
for (int j=0; j<n-1; j++)
{
for (int i=j+1; i<n; i++)
{
if (strcmp(arr[j], arr[i]) > 0)
{
strcpy(temp, arr[j]);
strcpy(arr[j], arr[i]);
strcpy(arr[i], temp);
}
}
}
}
void printstruct(struct person *p, int n){
for (int i=0; i<n; i++){
printf("{%s %d} ", (p+i)->name, (p+i)->age);
}
printf("\n");
}
int main()
{
struct person *p;
int n;
scanf("%d", &n);
p = (struct person*)malloc(sizeof(struct person)*n);
for (int i=0; i<n; i++){
scanf("%s\n%d", (p+i)->name, &(p+i)->age);
}
bubbleSortint(p, n);
printstruct(p, n);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <stdlib.h>
#define MAX_LINE_LENGTH 255
enum
{
DONE, OK, EMPTY_LINE
};
struct lable{
int location;
char* lable;
};
int main(int argc, char* argv[]) {
int isOpcode(char * lPtr){
if (strcmp(lPtr,"ADD")==0) return 0;
if (strcmp(lPtr,"AND")==0) return 0;
if (strcmp(lPtr,"HALT")==0) return 0;
if (strcmp(lPtr,"JMP")==0) return 0;
if (strcmp(lPtr,"JSR")==0) return 0;
if (strcmp(lPtr,"JSRR")==0) return 0;
if (strcmp(lPtr,"LDB")==0) return 0;
if (strcmp(lPtr,"LDW")==0) return 0;
if (strcmp(lPtr,"LEA")==0) return 0;
if (strcmp(lPtr,"NOP")==0) return 0;
if (strcmp(lPtr,"NOT")==0) return 0;
if (strcmp(lPtr,"RET")==0) return 0;
if (strcmp(lPtr,"LSHF")==0) return 0;
if (strcmp(lPtr,"RSHFL")==0) return 0;
if (strcmp(lPtr,"RTI")==0) return 0;
if (strcmp(lPtr,"STB")==0) return 0;
if (strcmp(lPtr,"STW")==0) return 0;
if (strcmp(lPtr,"TRAP")==0) return 0;
if (strcmp(lPtr,"XOR")==0) return 0;
if (strcmp(lPtr,"BR")==0) return 0;
if (strcmp(lPtr,"BRn")==0) return 0;
if (strcmp(lPtr,"BRz")==0) return 0;
if (strcmp(lPtr,"BRp")==0) return 0;
if (strcmp(lPtr,"BRnz")==0) return 0;
if (strcmp(lPtr,"BRnp")==0) return 0;
if (strcmp(lPtr,"BRzp")==0) return 0;
if (strcmp(lPtr,"BRnzp")==0) return 0;
return -1;
}
int
readAndParse( FILE * pInfile, char * pLine, char ** pLabel, char
** pOpcode, char ** pArg1, char ** pArg2, char ** pArg3, char ** pArg4
)
{
char * lRet, * lPtr;
int i;
if( !fgets( pLine, MAX_LINE_LENGTH, pInfile ) )
return( DONE );
for( i = 0; i < strlen( pLine ); i++ )
pLine[i] = tolower( pLine[i] );
/* convert entire line to lowercase */
*pLabel = *pOpcode = *pArg1 = *pArg2 = *pArg3 = *pArg4 = pLine + strlen(pLine);
/* ignore the comments */
lPtr = pLine;
while( *lPtr != ';' && *lPtr != '\0' &&
*lPtr != '\n' )
lPtr++;
*lPtr = '\0';
if( !(lPtr = strtok( pLine, "\t\n ," ) ) )
return( EMPTY_LINE );
if( isOpcode( lPtr ) == -1 && lPtr[0] != '.' ) /* found a label */
{
*pLabel = lPtr;
if( !( lPtr = strtok( NULL, "\t\n ," ) ) ) return( OK );
}
*pOpcode = lPtr;
if( !( lPtr = strtok( NULL, "\t\n ," ) ) ) return( OK );
*pArg1 = lPtr;
if( !( lPtr = strtok( NULL, "\t\n ," ) ) ) return( OK );
*pArg2 = lPtr;
if( !( lPtr = strtok( NULL, "\t\n ," ) ) ) return( OK );
*pArg3 = lPtr;
if( !( lPtr = strtok( NULL, "\t\n ," ) ) ) return( OK );
*pArg4 = lPtr;
return( OK );
}
int toNum( char * pStr )
{
char * t_ptr;
char * orig_pStr;
int t_length,k;
int lNum, lNeg = 0;
long int lNumLong;
orig_pStr = pStr;
if( *pStr == '#' ) /* decimal */
{
pStr++;
if( *pStr == '-' ) /* dec is negative */
{
lNeg = 1;
pStr++;
}
t_ptr = pStr;
t_length = strlen(t_ptr);
for(k=0;k < t_length;k++)
{
if (!isdigit(*t_ptr))
{
printf("Error: invalid decimal operand, %s\n",orig_pStr);
exit(4);
}
t_ptr++;
}
lNum = atoi(pStr);
if (lNeg)
lNum = -lNum;
return lNum;
}
else if( *pStr == 'x' ) /* hex */
{
pStr++;
if( *pStr == '-' ) /* hex is negative */
{
lNeg = 1;
pStr++;
}
t_ptr = pStr;
t_length = strlen(t_ptr);
for(k=0;k < t_length;k++)
{
if (!isxdigit(*t_ptr))
{
printf("Error: invalid hex operand, %s\n",orig_pStr);
exit(4);
}
t_ptr++;
}
lNumLong = strtol(pStr, NULL, 16); /* convert hex string into integer */
lNum = (lNumLong > INT_MAX)? INT_MAX : lNumLong;
if( lNeg )
lNum = -lNum;
return lNum;
}
else
{
printf( "Error: invalid operand, %s\n", orig_pStr);
exit(4); /* This has been changed from error code 3 to error code 4, see clarification 12 */
}
}
int line =0;
struct lable lables[10];
char *prgName = NULL;
char *iFileName = NULL;
char *oFileName = NULL;
prgName = argv[0];
iFileName = argv[1];
oFileName = argv[2];
printf("here");
printf("program name = '%s'\n", prgName);
printf("input file name = '%s'\n", iFileName);
printf("output file name = '%s'\n", oFileName);
printf("here");
char lLine[MAX_LINE_LENGTH + 1], *lLabel, *lOpcode, *lArg1,
*lArg2, *lArg3, *lArg4;
int lRet;
FILE * lInfile;
lInfile = fopen(iFileName, "r" ); /* open the input file */
do
{
lRet = readAndParse( lInfile, lLine, &lLabel,
&lOpcode, &lArg1, &lArg2, &lArg3, &lArg4 );
if( lRet != DONE && lRet != EMPTY_LINE )
{
line++;
if(strcmp(lOpcode,".ORIG"==0)){
line=toNum(lArg1);
}
if(lLabel != NULL){
int i;
for(i = 0; i<10; i++){
if(lables[i].lable==NULL){
lables[i].location=line;
lables[i].lable=lLabel;
}
}
}
printf("lable: %s\n",lLabel);
printf("opcode: %s\n",lOpcode);
printf("arg 1: %s\n",lArg1);
printf("arg 2: %s\n",lArg2);
printf("arg 3: %s\n",lArg3);
}
} while( lRet != DONE );
}
|
C
|
#include <stdio.h>
int main () {
int b[20][20];
int maxmul = 0;
// read in buffer
FILE *fp;
fp = fopen("b.txt", "r");
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
fscanf(fp, "%d", &b[i][j]);
}
}
fclose(fp);
for (int i = 0; i <= 20 - 4; i++) {
for (int j = 0; j <= 20 - 4; j++) {
int mul11 = b[i][j] * b[i + 1][j] * b[i + 2][j] * b[i + 3][j];
int mul22 = b[i][j] * b[i][j + 1] * b[i][j + 2] * b[i][j + 3];
int mul12 = b[i + 3][j] * b[i + 2][j + 1] * b[i + 1][j + 2] * b[i][j + 3];
int mul21 = b[i][j] * b[i + 1][j + 1] * b[i + 2][j + 2] * b[i + 3][j + 3];
if (mul11 > maxmul) {
maxmul = mul11;
}
if (mul22 > maxmul) {
maxmul = mul22;
}
if (mul12 > maxmul) {
maxmul = mul12;
}
if (mul21 > maxmul) {
maxmul = mul21;
}
}
}
// whoops, it seems we did not check the horizontal/vertical product of
// the last three rows/columns ...
printf("%d\n", maxmul);
return 0;
}
|
C
|
#include <stdio.h>
int main () {
system("color 74");
int v1,v2,aux;
printf("Por favor, Ingresa el valor de la variable Uno: \n");
scanf("%i", &v1);
printf("Por favor, Ingresa el valor de la variable Dos: \n");
scanf(" %i", &v2);
//en la siguiente linea estamos imprimiendo integerA
printf("Tu valor de V1 -> %i \n", v1);
printf("Tu valor de V2 -> %i \n", v2);
printf("Ahora tus valores son: \n");
sleep(3);
aux = v1;
v1 = v2;
//en la siguiente linea estamos imprimiendo integerA
printf("El valor de la variable 1 es: %i \n", v1);
printf("El valor de la variable 2 es: %i \n", aux);
return 0;
}
|
C
|
/*
Lee cadenas de caracteres hasta n-1 caracteres
O hasta que lea un salto de linea "\n"
o el final del archivo EOF
char *fgets(char *buffer, int tamanio, FILE *archivo);
*/
#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE *archivo;
char sCaracteres[100];
archivo = fopen("gente.txt","r");
if(archivo == NULL){
exit(1);
}else{
printf("\nEl contenido del archivo de prueba es: \n\n");
while(feof(archivo) == 0){
fgets(sCaracteres,100,archivo);
printf("%s",sCaracteres);
}//fin while
getchar();
}//fin if-else
fclose(archivo);
return 0;
}//fin int main
|
C
|
#include <stdio.h>
int main(void) {
char str[100];
char comment[100];
int flag = 0;
int i = 0;
int j = 0;
printf("Enter your line of code: \n");
scanf("%s", str);
// main loop reads characters until we find '/'
for (i = 0; i < sizeof(str); i++) {
if (str[i] == '*' && str[i+1] == '/' && flag == 1)
break;
if (flag == 1) {
comment[j] = str[i];
j++;
}
if (str[i] == '/' && str[i+1] == '*' && flag != 1) {
flag = 1;
i++;
}
}
printf("%s \n", comment);
return 0;
}
|
C
|
//Program to calculate the factorial of a number
#include<stdio.h>
int i,n;
unsigned long long f=1;
int itr_fact(int);
int rec_fact(int);
int main()
{
// int i,n;
// unsigned long long f=1;
printf("Enter an integer =\t");
scanf("%d",&n);
printf("\n Factorial using iterative function\n");
itr_fact(n);
printf("\n Factorial using recursive function\n");
int x=rec_fact(n);
printf("%d\n",x);
}
int itr_fact(int n)
{
if(n<0)
printf("Factorial does not exist\n");
else
{
for(i=1;i<=n;i++)
{
f*=i;
}
printf("Factorial of %d = %llu\n",n,f);
}
}
int rec_fact(int n)
{
if (n<0)
printf("Factorial does not exist\n");
else if (n>=1)
{
return n*rec_fact(n-1);
}
else
{
return 1;
}
}
|
C
|
/*
1- Variaveis
2- Substituio de variaveis
3- Leitura de dados digitados
*/
#include <stdio.h>
int main(void) {
int numero = 46,altura;
float valor = 8.37,comprimento;
char letra = 'X',nome[50],sobrenome[50];
printf("Variavel numero: %d \n",numero);
numero+=10;
printf("Variavel numero + 10: %d \n",numero);
printf("Variavel valor: %f \n",valor);
/*%10.2f = numero de 10 digitos com 2 casas decimais. OBS: como o nmero menor que 10, o programa preenche com espaos vazios*/
printf("Variavel valor: %10.2f \n",valor);
printf("Variavel valor: %.2f \n",valor);
printf("Variavel letra: %c \n",letra);
/*Na leitura: para variveis no vetores deve ser utilizado o '&' antes do nome da varivel*/
/*Para variveis vetores(como string) no necessrio o '&'*/
printf("Digite um nome: ");
gets(nome);
printf("Nome digitado: %s \n", nome);
printf("Digite um comprimento: ");
scanf("%f",&comprimento);
printf("Comprimento digitado: %f \n",comprimento);
printf("Digite uma altura: ");
scanf("%d",&altura);
printf("Altura digitada: %d \n",altura);
/*fflush limpa o buffer.*/
/*Quando pegamos o nome, o fflush no foi necessrio porque no havia um scanf antes, ou seja, no havia um 'ENTER' no buffer.*/
/*Quando fossemos pegar o sobrenome, haveria um 'ENTER'(porque colocamos a altura e apertamos o 'ENTER') no buffer, e ento, o programa leria o 'ENTER' automaticamente sem pedir para digitarmos nada.*/
/*Para resolver esse problema colocamos o fflush antes do gets (apenas quando h um scanf antes do gets)*/
/*Outra forma de resolver o problema colocar todos os gets antes dos scanf*/
fflush(stdin);
printf("Digite um sobrenome: ");
gets(sobrenome);
printf("Sobrenome digitado: %s \n", sobrenome);
return 0;
}
|
C
|
//
// MultiplicityRatio -
//
// M. H. Wood, Canisius College
//--------------------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <iostream.h>
gROOT->Reset();
Int_t lcol[10] = {1,2,4,6,7,8,9,12,14,15};
Int_t mkr[10] = {20,21,22,24,23,25,26,27,28,29};
char *fSame[10] = {"","same","same","same","same","same","same","same","same","same"};
Float_t Lmar = 0.125; // set the left margin
Float_t Rmar = 0.125; // set the right margin
Float_t yoff = 1.5; // set the offset between the y-axis label and the axis values
void Plot_MultiplictyRatio(string yldFile){
Int_t i, j, k;
Double_t val1, val2;
const Double_t num = 3;
Double_t Tgt[3];
Double_t errTgt[3];
Double_t Yield[3][2];
Double_t errYield[3][2];
Double_t Ratio[3];
Double_t errRatio[3];
Double_t err1, err2;
string run, target;
// open text file for the yields
ifstream fin(yldFile.c_str());
while(!fin.eof()){
fin>>run>>target>>val1>>val2;
if(target.compare("LD2")==0) j = 0;
if(target.compare("Nuc")==0) j = 1;
if(run.compare("C12")==0){
Tgt[0] = pow(12,1./3.);
errTgt[0] = 0;
Yield[0][j] = val1;
errYield[0][j] = val2;
}elseif(run.compare("Fe56")==0){
Tgt[1] = pow(56,1./3.);
errTgt[1] = 0;
Yield[1][j] = val1;
errYield[1][j] = val2;
}elseif(run.compare("Pb208")==0){
Tgt[2] = pow(208,1./3.);
errTgt[2] = 0;
Yield[2][j] = val1;
errYield[2][j] = val2;
}else{
cout<<"Unknown target "<<target<<endl;
}
}
for(k=0; k<3; k++){
if(Yield[k][0]>0 && Yield[k][1]>0){
Ratio[k] = Yield[k][1]/Yield[k][0];
err1 = errYield[k][0]/Yield[k][0];
err2 = errYield[k][1]/Yield[k][1];
errRatio[k] = Ratio[k]*sqrt(err1*err1 + err2*err2);
}
}
gStyle->SetOptStat(0);
TCanvas *can1 = new TCanvas("can1","Multiplicity Ratio",0,0,600,600); // create the canvas
can1->SetBorderMode(0); //Bordermode (-1=down, 0 = no border, 1=up)
can1->SetBorderSize(5);
can1->SetFillStyle(4000);
// set up the Pad parameters
gPad->SetLeftMargin(Lmar);
gPad->SetRightMargin(Rmar);
gPad->SetFillColor(0);
TGraphErrors *grRatio = new TGraphErrors(num,Tgt,Ratio,errTgt,errRatio);
grRatio->Draw("AP");
grRatio->SetTitle(0);
grRatio->SetMarkerStyle(21);
grRatio->SetMarkerColor(4);
grRatio->GetXaxis()->SetTitle("A^{1/3}");
grRatio->GetXaxis()->CenterTitle();
grRatio->GetYaxis()->SetTitle("uncorrected Yield(A)/Yield(D_{2})");
grRatio->GetYaxis()->CenterTitle();
grRatio->GetYaxis()->SetTitleOffset(yoff);
// create the image files
char OutCan[100];
sprintf(OutCan,"Plot_MultiplicityRatio.gif");
can1->Print(OutCan);
sprintf(OutCan,"Plot_MultiplicityRatio.eps");
can1->Print(OutCan);
fin.close();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int funkzia_proverki_vvoda()
{
int k;
while(system("pause"),fflush(stdin),system("cls"),printf(" : "),scanf("%i",&k)!=1||k>20||k<=0)
printf("! \n");
return k;
}
void funkzia_vvoda_mass(int a[],int n)
{
int i;
for (i=0;i<n;i++)
while(printf("a[%i]= ",i),scanf("%i",&a[i])!=1)
printf(" \n");
printf("\n");
}
int funkzia_sort_mass(int a[],int n)
{
int i,k=0;
if (a[0]==a[1])
for (i=0;i<n;i++)
if (a[i]!=a[0])
{
k=i;
for (k;k<n;k++)
a[k]=a[k+1];
n--;
i--;
}
if (a[0]<a[1])
for (i=0;i<n-1;i++)
if(a[i]>a[i+1])
{
k=i+1;
for (k;k<n;k++)
a[k]=a[k+1];
n--;
i--;
}
if (a[0]>a[1])
for (i=0;i<n-1;i++)
if(a[i]<a[i+1])
{
k=i+1;
for (k;k<n;k++)
a[k]=a[k+1];
n--;
i--;
}
return n;
}
void out_mass(int a[],int n)
{
int i;
for (i=0;i<n;i++)
printf("a[%i]= %i\n",i,a[i]);
}
int main()
{
system("chcp 1251>nul");
int n, a[20]={0};
n=funkzia_proverki_vvoda();
funkzia_vvoda_mass(a,n);
n=funkzia_sort_mass(a,n);
printf(" : %i\n",n);
out_mass(a,n);
system("pause");
return 0;
}
|
C
|
//C Program to find the simple interest
#include<stdio.h>
int main()
{
int p,t,r; //p-principal t-time r-rate
float interest;
printf("enter the value of p,t,r");
scanf("%d %d %d",&p,&t,&r);
interest=(p*t*r)/100;
printf("interest: %f",interest);
return 0;
}
|
C
|
// run with below command on terminal
// gcc -o call.out blocking-call.c
#include "stdio.h"
#include <unistd.h>
void fp() {
printf("3\n");
}
void fp_call(void (*fp)(void)) {
fp();
}
int main() {
printf("1\n");
printf("2\n");
usleep(1000 * 2000);
fp_call(&fp);
return 0;
}
|
C
|
#include <stdio.h>
int main(int argc, char** argv)
{
FILE* file;
file = fopen(argv[1],"w");
if(file == NULL){
printf("Something went wrong. Too few arguments?");
}
fprintf(file,"Some text %s\n", "THIS IS A TESTFILE, PLEASE IGNORE");
fclose(file);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h> /* Use of pow function */
#include <complex.h> /* Makes the use of complex numbers much easier */
#include <fftw3.h> /* Used for FFTs */
#include "multislice.h" /* Contains definitions and some function declarations */
int main()
{
/* Gets the required input parameters from the user (in angstroms) */
getuserinput();
/* Converting lattice parameters to S.I units */
a = a * angstrom;
b = b * angstrom;
c = c * angstrom;
/* Swapping a with c and width with depth, consistent with a side view */
if(view == 1){
temp = a;
a = c;
c = temp;
temp1 = width;
width = depth;
depth = temp1;
}
/* Swapping a with c and width with depth, consistent with a side view */
if(view == 2){
temp = b;
b = c;
c = temp;
temp1 = height;
height = depth ;
depth = temp1;
}
/* Size of an individual voxel */
dx = (a / width);
dy = (b / height);
dz = (c / depth); /* Slicethickness */
size = height*width*depth; /* The number of potential readings in file */
wavefunctionsize = height*width; /* Number of points wavefunction is evaluated at */
/* Outputs the wavefunction parameters to the file "size.text" to be used by the python script */
outputparameters();
/* Calculate the Relativistic De Broglie wavelength and Electron Interaction parameter */
wavelength = calcwavelength(v);
sigma = calcsigma(wavelength,v);
/* Dynamically Allocates Memory for the arrays used */
allocatememory();
/* Reads in the correctly ordered potential file "ordered.txt" */
if(view == 0){
readinputfile();
}
if(view == 1){
readinputfilesideview();
}
if(view == 2){
readinputfiletopview();
}
/* Converts potentials from Hartrees to Volts (energy to volltage),and positions into metres */
for (i=0; i<size; i++){
V[i] = V[i] * hartree/charge;
x[i] = x[i] * dx;
y[i] = y[i] * dy;
}
/* Working out where the atoms are located (maximising efficiency) */
whereareatoms();
/* Calculating the Spatial Frequency squared (reciprical lattice) */
calck_x2(width,dx,x);
calck_y2(height,dy,y);
/* If the unit cell is Hexagonal, follow this step of the loop */
if(unitcellcode == 1){
calck_x2H(width,dx,x);
calck_y2H(height,dy,y);
hexagonalsampling();
interpolation();
}
/* If the unit cell is rectangular then no remapping/interpolation is needed */
if(unitcellcode == 0){
for(i=0;i<size;i++){
P2[i] = V[i];
}
}
/* Propogation Function */
for (i=0; i<wavefunctionsize; i++){
P[i] = cexp(-I*pi*dz*wavelength*(k_x2[i]+k_y2[i]));
}
/* Propogation Function including specimin tilt */
if(tilt == 1){
for (i=0; i<wavefunctionsize; i++){
P[i] = cexp((-I*pi*dz*wavelength*(k_x2[i]+k_y2[i]))+(2*pi*I*dz*((pow(k_x2[i],0.5)*tan(tiltx))+pow(k_y2[i],0.5)*tan(tilty))));
}
}
/* Calculating the Transfer Function of the objective Lens */
df = pow(1.5*abberation*wavelength,0.5); /* Optimum defocus */
aperture = pow(((4*wavelength)/abberation),0.25); /* Optimum Aperture size */
for (i=0; i<wavefunctionsize; i++){
k = pow((k_x2[i]+k_y2[i]),0.5);
if(k <= aperture){
abbfunction = (pi*wavelength*(k_x2[i]+k_y2[i]))*((0.5*abberation*pow(wavelength,2)*(k_x2[i]+k_y2[i]))-df);
PSF[i] = cexp(-I*abbfunction);
}
else{
abbfunction = 0;
PSF[i] = cexp(-I*abbfunction);
}
}
/* Initialising FFTW arrays */
n[0] = width;
n[1] = height;
in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * wavefunctionsize);
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * wavefunctionsize);
plan = fftw_plan_dft_2d(height, width, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
planinverse = fftw_plan_dft_2d(height, width, in, out, FFTW_BACKWARD, FFTW_ESTIMATE);
/* Initialising the wavefunction */
for (i=0; i<wavefunctionsize; i++){
wavefunction[i] = 1.;
}
/* Multislice loop */
for(j=loop1; j<depth; j++){
for (i=0; i<wavefunctionsize; i++){
T[i] = cexp(-I*sigma*P2[i+j*wavefunctionsize]*dz);
}
for (i=0; i<wavefunctionsize; i++){
in[i] = T[i]*wavefunction[i];
}
fftw_execute(plan);
for (i=0; i<wavefunctionsize; i++){
in[i] = out[i]*P[i];
}
fftw_execute(planinverse);
for (i=0;i<wavefunctionsize;i++){
wavefunction[i] = out[i] / wavefunctionsize ;
}
}
/* Convolution with Objective lens */
for (i=0; i<wavefunctionsize; i++){
in[i] = wavefunction[i];
}
fftw_execute(plan);
for (i=0; i<wavefunctionsize; i++){
in[i] = out[i]*PSF[i];
}
fftw_execute(planinverse);
for (i=0; i<wavefunctionsize; i++){
wavefunction[i] = out[i] / wavefunctionsize;
}
/* Convergence Test */
for(i=0;i<wavefunctionsize;i++){
tester = pow(cabs(wavefunction[i]),2) + tester;
}
if(tester/wavefunctionsize < 0.9){
printf("The total integrated intensity is %lf which is less than 0.9. There is likely to be a problem with this simulation \n", tester/wavefunctionsize);
}
if(tester/wavefunctionsize > 1.00001){
printf("The total integrated intensity is %lf which is greater than 1. There is likely to be a problem with this simulation \n", tester/wavefunctionsize);
}
else{
printf("The total integrated intensity is: %lf - Test Passed \n", tester/wavefunctionsize);
}
/* Output the image intensity to "output.txt" */
FILE* output;
output = fopen("output.txt", "w");
for (i=0; i<wavefunctionsize; i++){
fprintf(output, "%.20lf \n", pow(cabs(wavefunction[i]),2));
}
fclose(output);
/* Free the dynamic arrays */
destroymem();
}
|
C
|
/*
* motores.c
*
* Created on: Mar 14, 2020
* Author: augusto
*/
#include <motores.h>
#include <HPL_GPIO.h>
#define MOTORES_USE_PWM
#define MOTORES_AMOUNT 2
#define MOTORES_PIN_AMOUNT 2
#define MOTORES_OPEN_IDX 0
#define MOTORES_CLOSE_IDX 1
#define MOTORES_PWM_MAX 20
#define MOTORES_PWM_OPEN 3
#define MOTORES_PWM_CLOSE 2
static const uint8_t motores_ports[MOTORES_AMOUNT][MOTORES_PIN_AMOUNT] = //!< Puertos de los pines de los motores
{
{ 0, 0 },
{ 0, 0 }
};
static const uint8_t motores_pins[MOTORES_AMOUNT][MOTORES_PIN_AMOUNT] = //!< Pines de los pines de los motores
{
{ 29, 28 },
{ 27, 26 }
};
static motor_accion_en motores_actions[MOTORES_AMOUNT] = //!< Acciones actuales de los motores
{
MOTOR_LIBERAR,
MOTOR_LIBERAR
};
#ifdef MOTORES_USE_PWM
static uint32_t motores_pwm_value[MOTORES_AMOUNT] = //!< Valores actuales de PWM de los motores
{
0, 0
};
#endif
static void motor_open(motor_selection_en motor);
static void motor_close(motor_selection_en motor);
static void motor_break(motor_selection_en motor);
static void motor_release(motor_selection_en motor);
/*!
* @brief Inicializacion de los pines de los motores
*/
void motores_init_pins(void)
{
uint8_t i, j;
GPIO_init(0);
for(i = 0; i < MOTORES_AMOUNT; i++)
{
for(j = 0; j < MOTORES_PIN_AMOUNT; j++)
{
GPIO_set_dir(motores_ports[i][j], motores_pins[i][j], GPIO_DIR_OUTPUT, 0);
}
}
}
/*!
* @brief Accionar algun motor
* @param motor Cual de los motores accionar
* @param accion Accion del motor a realizar
*/
void motores_action(motor_selection_en motor, motor_accion_en accion)
{
switch(accion)
{
case MOTOR_ABRIR:
{
motor_open(motor);
motores_actions[motor] = MOTOR_ABRIR;
break;
}
case MOTOR_CERRAR:
{
motor_close(motor);
motores_actions[motor] = MOTOR_CERRAR;
break;
}
case MOTOR_FRENAR:
{
motor_break(motor);
motores_actions[motor] = MOTOR_FRENAR;
break;
}
case MOTOR_LIBERAR:
{
motor_release(motor);
motores_actions[motor] = MOTOR_LIBERAR;
break;
}
}
}
/*!
* @brief Obtener el estado de algun motor
* @param motor Cual de los motores consultar
* @return Accion del motor actual
*/
motor_accion_en motores_get_state(motor_selection_en motor)
{
return motores_actions[motor];
}
/*!
* @brief Manejo de PWM en caso de estar habilitado de los motores. Llamar cada 1mseg
*/
void motores_check(void)
{
#ifdef MOTORES_USE_PWM
static uint32_t motores_step_counter;
uint8_t counter;
motores_step_counter = (motores_step_counter + 1) % MOTORES_PWM_MAX;
for(counter = 0; counter < MOTORES_AMOUNT; counter++)
{
switch(motores_actions[counter])
{
case MOTOR_ABRIR:
{
if(motores_step_counter == 0)
{
if(motores_pwm_value[counter] > 0)
{
GPIO_set_pin(motores_ports[counter][MOTORES_OPEN_IDX], motores_pins[counter][MOTORES_OPEN_IDX]);
}
}
else
{
if(motores_pwm_value[counter] == motores_step_counter)
{
GPIO_clear_pin(motores_ports[counter][MOTORES_OPEN_IDX], motores_pins[counter][MOTORES_OPEN_IDX]);
}
}
break;
}
case MOTOR_CERRAR:
{
if(motores_step_counter == 0)
{
if(motores_pwm_value[counter] > 0)
{
GPIO_set_pin(motores_ports[counter][MOTORES_CLOSE_IDX], motores_pins[counter][MOTORES_CLOSE_IDX]);
}
}
else
{
if(motores_pwm_value[counter] == motores_step_counter)
{
GPIO_clear_pin(motores_ports[counter][MOTORES_CLOSE_IDX], motores_pins[counter][MOTORES_CLOSE_IDX]);
}
}
break;
}
case MOTOR_LIBERAR: break;
case MOTOR_FRENAR: break;
}
}
#endif
}
/*!
* @brief Abrir un motor
* @param motor Motor a abrir
*/
static void motor_open(motor_selection_en motor)
{
#ifndef MOTORES_USE_PWM
GPIO_clear_pin(motores_ports[motor][MOTORES_CLOSE_IDX], motores_pins[motor][MOTORES_CLOSE_IDX]);
GPIO_set_pin(motores_ports[motor][MOTORES_OPEN_IDX], motores_pins[motor][MOTORES_OPEN_IDX]);
#else
motores_pwm_value[motor] = MOTORES_PWM_OPEN;
GPIO_clear_pin(motores_ports[motor][MOTORES_OPEN_IDX], motores_pins[motor][MOTORES_OPEN_IDX]);
GPIO_clear_pin(motores_ports[motor][MOTORES_CLOSE_IDX], motores_pins[motor][MOTORES_CLOSE_IDX]);
// En el proximo ciclo de PWM se normalizan los estados
#endif
}
/*!
* @brief Cerrar un motor
* @param motor Motor a cerrar
*/
static void motor_close(motor_selection_en motor)
{
#ifndef MOTORES_USE_PWM
GPIO_clear_pin(motores_ports[motor][MOTORES_OPEN_IDX], motores_pins[motor][MOTORES_OPEN_IDX]);
GPIO_set_pin(motores_ports[motor][MOTORES_CLOSE_IDX], motores_pins[motor][MOTORES_CLOSE_IDX]);
#else
motores_pwm_value[motor] = MOTORES_PWM_CLOSE;
GPIO_clear_pin(motores_ports[motor][MOTORES_OPEN_IDX], motores_pins[motor][MOTORES_OPEN_IDX]);
GPIO_clear_pin(motores_ports[motor][MOTORES_CLOSE_IDX], motores_pins[motor][MOTORES_CLOSE_IDX]);
// En el proximo ciclo de PWM se normalizan los estados
#endif
}
/*!
* @brief Frenar un motor
* @param motor Motor a frenar
*/
static void motor_break(motor_selection_en motor)
{
#ifndef MOTORES_USE_PWM
GPIO_set_pin(motores_ports[motor][MOTORES_OPEN_IDX], motores_pins[motor][MOTORES_OPEN_IDX]);
GPIO_set_pin(motores_ports[motor][MOTORES_CLOSE_IDX], motores_pins[motor][MOTORES_CLOSE_IDX]);
#else
motores_pwm_value[motor] = 0;
GPIO_set_pin(motores_ports[motor][MOTORES_OPEN_IDX], motores_pins[motor][MOTORES_OPEN_IDX]);
GPIO_set_pin(motores_ports[motor][MOTORES_CLOSE_IDX], motores_pins[motor][MOTORES_CLOSE_IDX]);
#endif
}
/*!
* @brief Liberar un motor
* @param motor Motor a liberar
*/
static void motor_release(motor_selection_en motor)
{
#ifndef MOTORES_USE_PWM
GPIO_clear_pin(motores_ports[motor][MOTORES_OPEN_IDX], motores_pins[motor][MOTORES_OPEN_IDX]);
GPIO_clear_pin(motores_ports[motor][MOTORES_CLOSE_IDX], motores_pins[motor][MOTORES_CLOSE_IDX]);
#else
motores_pwm_value[motor] = 0;
GPIO_clear_pin(motores_ports[motor][MOTORES_OPEN_IDX], motores_pins[motor][MOTORES_OPEN_IDX]);
GPIO_clear_pin(motores_ports[motor][MOTORES_CLOSE_IDX], motores_pins[motor][MOTORES_CLOSE_IDX]);
#endif
}
|
C
|
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
if (argc == 2)
{
//validate string input argv[1] consists of digits only
for (int i = 0, len = strlen(argv[1]); i < len; i++)
{
if (isdigit(argv[1][i]))
{
continue;
}
else
{
printf("Usage: ./caesar key\n");
return (1);
break;
}
}
}
else
{
printf("Usage: ./caesar key\n");
return (1);
}
//convert string argv[1] into int
int key = atoi(argv[1]);
//prompt user for plaintext string
string ptext = get_string("plaintext: ");
string ctext = ptext;
//generate ciphertext
for (int i = 0, len = strlen(ptext); i < len; i++)
{
if (isupper(ptext[i]))
{
ctext[i] = (((ptext[i] - 65) + key) % 26) + 65;
}
else if (islower(ptext[i]))
{
ctext[i] = (((ptext[i] - 97) + key) % 26) + 97;
}
}
//print ciphertext
printf("ciphertext: %s\n", ctext);
}
|
C
|
#ifndef INC_chacks_btree_H
#define INC_chacks_btree_H
struct btree_node {
void *data;
struct btree_node *l;
struct btree_node *r;
};
typedef int (*BTREE_NODE_EQUALS) (const void *a, const void *b);
/*
* Find node which matches data.
*/
extern int btree_find(const struct btree_node *n, const void *data,
BTREE_NODE_EQUALS fn);
extern struct btree_node *btree_insert(struct btree_node *n, void *data);
#endif
|
C
|
// oscbndlsend.c - test program to send OSC bundles
//
// this test is designed to run with either oscbndlrecv.c or lo_bndlrecv.c
// We'll send 5 bundles:
// at NOW+2.9: [/xyz/msg1 1009 "an arbitrary string at 2.9"],
// [/abcdefg/msg2 2009 "another arbitrary string at 2.9"]
// at NOW+2.8: [/xyz/msg1 1008 "an arbitrary string at 2.8"],
// [/abcdefg/msg2 2008 "another arbitrary string at 2.8"]
// at NOW+2.7: [/xyz/msg1 1007 "an arbitrary string at 2.7"],
// [/abcdefg/msg2 2007 "another arbitrary string at 2.7"]
// at NOW+2.6: [/xyz/msg1 1006 "an arbitrary string at 2.6"],
// [/abcdefg/msg2 2006 "another arbitrary string at 2.6"]
// at NOW+2.5: [/xyz/msg1 1005 "an arbitrary string at 2.5"],
// [/abcdefg/msg2 2005 "another arbitrary string at 2.5"]
// Then we'll send a nested bundle:
// at NOW+3: [/first 1111 "an arbitrary string at 3.0"],
// [#bundle NOW+3.1
// [/xyz/msg1 1011 "an arbitrary string at 3.1"],
// [/abcdefg/msg2 2011 "another arbitrary string at 3.1"]]
#include "o2.h"
#include "stdio.h"
#include "string.h"
#include "assert.h"
#ifdef WIN32
#include "usleep.h" // special windows implementation of sleep/usleep
#else
#include <unistd.h>
#endif
o2_message_ptr make_message(o2_time time, char *address, int i, char *s)
{
o2_send_start();
o2_add_int32(i);
o2_add_string(s);
// add the message to the bundle
return o2_message_finish(time, address, FALSE);
}
o2_message_ptr bundle2(o2_time time, o2_message_ptr m1, o2_message_ptr m2)
{
o2_send_start();
o2_add_message(m1);
o2_message_free(m1);
o2_add_message(m2);
o2_message_free(m2);
return o2_service_message_finish(time, "oscsend", "", FALSE);
}
void send_nested(o2_time now, o2_time touter, o2_time tinner, int base)
{
char s[128];
// make first message
sprintf(s, "first string at %g", touter);
o2_message_ptr out1 = make_message(now + touter, "/oscsend/first",
base + 1, s);
// make first inner message
sprintf(s, "msg1 string at %g", tinner);
o2_message_ptr in1 = make_message(now + tinner, "/oscsend/xyz/msg1",
base + 2, s);
// make second inner message
// use timestamp of 0, should deliver at max(touter, tinner) because
// of containing bundle
sprintf(s, "msg2 string at %g", tinner);
o2_message_ptr in2 = make_message(0.0, "/oscsend/abcdefg/msg2",
base + 3, s);
// make inner bundle
o2_message_ptr inner = bundle2(now + tinner, in1, in2);
// make outer bundle
o2_message_ptr outer = bundle2(now + touter, out1, inner);
// send it
o2_message_send(outer);
}
int main(int argc, const char * argv[])
{
printf("Usage: oscbndlrecv flags (see o2.h for flags, "
"use a for all, also u for UDP, M for master)\n");
int tcpflag = TRUE;
int master = FALSE;
if (argc == 2) {
o2_debug_flags(argv[1]);
tcpflag = (strchr(argv[1], 'u') == NULL);
master = (strchr(argv[1], 'M') != NULL);
}
if (argc > 2) {
printf("WARNING: o2server ignoring extra command line argments\n");
}
printf("tcpflag %d master %d\n", tcpflag, master);
o2_initialize("test");
// you can make this run without an O2 server by passing "master"
if (master)
o2_clock_set(NULL, NULL);
if (master) sleep(2); // wait for liblo server to come up if we are master
char s[128];
printf("Waiting for clock sync\n");
while (!o2_clock_is_synchronized) {
usleep(2000);
o2_poll();
}
int err = o2_osc_delegate("oscsend", "localhost", 8100, tcpflag);
assert(err == O2_SUCCESS);
printf("connected to port 8100\n");
o2_time now = o2_time_get();
printf("Sending simple message\n");
o2_send("/oscsend/test", 0.0, NULL);
printf("Sending messages\n");
for (int i = 9; i >= 5; i--) {
// make the bundle
o2_send_start();
// make first message
sprintf(s, "an arbitrary string at 2.%d", i);
o2_message_ptr msg1 = make_message(0.0, "/oscsend/xyz/msg1",
1000 + i, s);
// make second message
sprintf(s, "another arbitrary string at 2.%d", i);
o2_message_ptr msg2 = make_message(0.0, "/oscsend/abcdefg/msg2",
2000 + i, s);
// add the messages to the bundle
o2_send_start();
o2_add_message(msg1);
o2_message_free(msg1);
o2_add_message(msg2);
o2_message_free(msg2);
o2_message_ptr msg = o2_service_message_finish(now + 2 + i * 0.1,
"oscsend", "", FALSE);
// send it
o2_message_send(msg);
}
// now send nested bundles
// this tests timestamps on inner bundles, trying both 0 and a time:
// [@3.0 /first [@0 /msg1 /msg2]] -- should deliver all at 3.0
// [@3.1 /first [@3.2 /msg1 /msg2]] -- should dliever msg1, msg2 at 3.2
send_nested(now, 3.0, 0.0, 3000);
send_nested(now, 3.1, 3.2, 4000);
printf("after sending\n");
sleep(1); // if you exit() after send(), data might be lost
printf("removing oscsend\n");
o2_service_free("oscsend");
printf("calling o2_finish()\n");
o2_finish();
printf("sleep(1)\n");
sleep(1); // clean up sockets
printf("OSCSEND DONE\n");
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct aluno{
int ra;
char nome[20];
};
main(){
struct aluno al[3];
//ra
printf("Digite um primeiro RA: ");
scanf("%d", &al[0].ra);
printf("Digite um segundo RA: ");
scanf("%d", &al[1].ra);
printf("Digite um terceiro RA: ");
scanf("%d", &al[2].ra);
printf("Cadastrados: %d, %d, %d\n", al[0].ra, al[1].ra, al[2].ra);
//nome
printf("Digite um primeiro nome: ");
fflush(stdin);
gets(al[0].nome);
printf("Digite um segundo nome: ");
fflush(stdin);
gets(al[1].nome);
printf("Digite um terceiro nome: ");
fflush(stdin);
gets(al[2].nome);
printf("Cadastrados: %s, %s, %s", al[0].nome, al[1].nome, al[2].nome);
}
|
C
|
#include <stdio.h>
int main()
{
int i, n, f;
f=0;
scanf("%d", &n);
if(n % 2 == 0)
for(i=0;i<=n;i++)
f += i;
else
for(i=1;i<=n;i+=2)
f += i;
printf("%d", f);
return 0;
}
|
C
|
// Voltage Reading program for FFL Dewey Robot
// Author Ken Samuelson
// Date started 6/18/2017
// Last update by Ken Samuelson 8/19/2017
// Copyright Unpublished work Ken Samuelson 2017 all rights reserved.
#include "Arduino.h"
#include "def.h"
unsigned long voltageMillis = millis();
// voltagePin voltRead = ELECTRONICS;
int voltRead = 0;
void readVoltage(int reading) {
char floatStrCalc[10]= {'aaaaaaaa'};
char floatStrBus[10];
char StrBuff[15] = {'Hello'};
float voltFactor =1;
int pin = 0; // 0 = Electroinics Voltage
String name = "None"; //name of pin being addressed
switch (reading) {
case 0 :
strcpy(StrBuff,"Elect ");
name = "Elec ";
voltFactor = 41.322; // 24.75 / 1023 = .0242 = 1/41.322
// StrBuff[] = "Electronic ";
break;
case 1 :
strcpy(StrBuff,"Motor ");
name = "Motor ";
voltFactor = 41.62; // 24.75 / 1023 = .0242 = 1/41.322
// StrBuff[] = "Motor ";
break;
case 2 :
strcpy(StrBuff,"Proc ");
name = "Proc ";
voltFactor =104.9; // 5.04
// StrBuff[] = "Processor ";
break;
default :
name = "Unknown ";
break;
}
int busCounts = analogRead(reading);
// Serial.print("VoltageCount=");
// Serial.println(busCounts);
float calcVoltage = busCounts / voltFactor;
dtostrf(calcVoltage, 4, 2, floatStrCalc);
// Serial.print (reading);
Serial.print (StrBuff);
// Serial.print (floatStrCalc);
// Serial.println(" Voltage=" + floatStrCalc + " V");
Serial.print("Voltage=");
Serial.print(floatStrCalc);
Serial.println("V");
}
void voltageCheck(unsigned long currentMillis2){
// Check voltage evry (50 * 250 s) or ~12.5 seconds
// millis() - voltageMillis > 1000
if ((currentMillis2 - voltageMillis) > 15000) {
//Serial.println("Voltage= 5000 loop");
voltageMillis = currentMillis2; //millis();
// Serial.print("VoltageA1");
readVoltage(voltRead); // 0 is pin 0 for the Electronics - 1 will be for motors
voltRead = voltRead +1;
if (voltRead > 2)
voltRead = 0;
}
// else {
// voltageMillis++;
//
// }
}
|
C
|
/*
** my_putstr.c for my_putstr in /home/JB.Melet/CPool_Day04
**
** Made by JeanBaptiste Melet
** Login <JB.Melet@epitech.net>
**
** Started on Thu Mar 2 09:36:28 2017 JeanBaptiste Melet
** Last update Sun Apr 16 20:30:32 2017 JeanBaptiste Melet
*/
#include "printf.h"
int my_putstr(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
{
my_putchar(str[i]);
i = i + 1;
}
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <string.h>
/* Prototype */
int bingoGenerator(int length, int width, char randChoices[30][30], char bingoBoard[length][width][30]);
int randomizer(char choices[30][30], char randChoices[30][30]);
void bingoPrinter(int length, int width, char bingoBoard[length][width][30], FILE *fileplace);
int
main()
{
/* Declarations */
unsigned int leng, wdth;
FILE *fileData;
fileData = fopen("bingoCard.txt", "w");
char options[30][30] = {"Gender Bender", "Slave Leia", "Guy with Boombox", "Jon Snow", "Mother of Dragons",
"Deadpool", "Kid that parent dragged in", "Parent that kid dragged in", "Cardboard Costume",
"Pokemon Trainer", "Costume Coordinated Group", "Placeholder 12", "Placeholder 13",
"Placeholder 14", "Placeholder 15", "Placeholder 16", "Placeholder 17", "Placeholder 18",
"Placeholder 19", "Placeholder 20", "Placeholder 21", "Placeholder 22", "Placeholder 23",
"Placeholder 24", "Placeholder 25", "Placeholder 26", "Placeholder 27", "Placeholder 28",
"Placeholder 29", "Placeholder 30"};
char randOps[30][30];
printf("Please enter the length and width of your table: ");
scanf("%u", &leng);
wdth = leng;
//printf("How many tables are we making: ");
//scanf("%u", &numTables);
//printf("\n%s", options[3]);
//getch();
char bingoTables[leng][wdth][30];
//for(i = 0; i < numTables; i++){
//randOps[i][30] = randomizer(options);
randomizer(options, randOps);
//printf("\n%s", randOps[i]);
//printf("\n%s", "randomFuncCheck");
//getch();
//}
//for(i = 0; i < numTables; i++){
bingoGenerator(leng, wdth, randOps, bingoTables);
//printf("\n%s", bingoTables[1][1]);
//printf("\n%s", "tableFuncCheck");
//getch();
//}
//for(i = 0; i < numTables; i++){
bingoPrinter(leng, wdth, bingoTables, fileData);
//}
printf("Live Long and May the Force Be Ever in Your Favor!");
return 0;
}
int randomizer(char choices[30][30], char randChoices[30][30]){
//time_t seed;
size_t arrSz = 30;
unsigned int i;
srand(time(0));
for(i=0; i < arrSz; i++){
strcpy(randChoices[i], choices[rand() % (arrSz +1)]);
//printf("\n%s", randChoices[i]);
//printf("\n%s", "randomTest");
//getch();
}
return 0;
}
int bingoGenerator(int length, int width, char randChoices[30][30], char bingoBoard[length][width][30]){
unsigned int i, j;
//for(k=0; k < tableNum; k++){
for(i=0; i < length; i++){
if (i < 1){
for(j=0; j < width; j++){
strcpy(bingoBoard[i][j], randChoices[j]);
}
}
else{
for(j=0; j < width; j++){
strcpy(bingoBoard[i][j], randChoices[(j + width)*i]);
}
}
}
return 0;
}
void bingoPrinter(int length, int width, char bingoTables[length][width][30], FILE *fileplace){
unsigned i, j;
fprintf(fileplace, "|\tB\t|\tI\t|\tN\t|\tG\t|\tO\t|\n");
fprintf(fileplace, "|+++++++++++++++|+++++++++++++++"
"|+++++++++++++++|+++++++++++++++|+++++++++++++++|\n");
for(i=0; i < length; i++){
for(j=0; j < width; j++){
if (j < 1){
//printf("%s", bingoTables[i][j]);
fprintf(fileplace, "%s\t", bingoTables[i][j]);
}
else if(j == (width - 1)){
//printf("\t%s\n", bingoTables[i][j]);
fprintf(fileplace,"\t\t%s\t\n", bingoTables[i][j]);
}
else{
//printf("\t%s", bingoTables[i][j]);
fprintf(fileplace, "\t%s\t", bingoTables[i][j]);
}
}
}
}
|
C
|
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char usrInput[256], *prog_argv[64];
int i, status;
pid_t sxpid;
//gethostname(hostn, sizeof(hostn));
//user = (char *)getenv("USER"); // Get name of user instead of $ prompt
while(1)
{ printf("$"); // PROMPT
// User Input
if (!fgets(usrInput, sizeof(usrInput), stdin)) break;
if (strncmp("exit", usrInput, 4) == 0)
{ exit(0);} // QUIT
else if (strncmp("cd", usrInput, 2) == 0)
{ char *cdInput = strtok(usrInput, " \n"); // CD
cdInput = strtok(NULL, " \n");
//getcwd(cwd,sizeof(cwd));
//strcat(cwd,"/");
//strcat(cwd,cdInput);
if (!cdInput)
fprintf(stderr, "cd missing argument\n"); // Input validation and segmentation fault prevention
else
chdir(cdInput);
continue;}
char *sInput = (char *)malloc((sizeof(usrInput)+1) * sizeof(char));
i=0;
sInput = strtok(usrInput, " \n"); // Parse user input
while ( sInput != NULL )
{ prog_argv[i++] = sInput;
sInput = strtok(NULL, " \n");}
prog_argv[i] = NULL; // Null at end of array
sxpid = fork();
if (sxpid<0)
{ perror("Fork error");
exit(99);}
else if (sxpid==0) // CHILD
{ execvp(prog_argv[0], prog_argv);
//perror("Error calling exec()");
exit(1);}
else // FATHER
waitpid (sxpid, &status, 0);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "lisp_def.c"
//prototype definitions
int __fn_main_0();
int __fn_main_1();
int __fn_main_print_hello_world_0();
void print_hello_world_0 ();
int __fn_main_hello_name_0();
void hello_name_0 (char* name);
int __fn_main_sum_up_to_n_0();
int __fn_main_sum_up_to_n_1();
int sum_up_to_n_0 (int n);
int __fn_main_sum_up_to_n_2_0();
int __fn_main_sum_up_to_n_2_1();
int sum_up_to_n_2_0 (int n);
int __fn_main_multiplication_table_0();
int __fn_main_multiplication_table_1();
int __fn_main_multiplication_table_2();
int __fn_main_multiplication_table_3();
int multiplication_table_0 ();
//variable definitions
struct {} __main;
struct {} __print_hello_world_0;
struct {char name[10];} __hello_name_0;
struct {int n;
int current;
int result;} __sum_up_to_n_0;
struct {int n;
int current;
int result;} __sum_up_to_n_2_0;
struct {int i;
int current;} __multiplication_table_0;
//function definitions
int __fn_main_0(){printf("%d\n",sum_up_to_n_0(5)
);;}
int __fn_main_1(){printf("%d\n",sum_up_to_n_2_0(5)
);;}
int __fn_main_print_hello_world_0(){printf("%s\n","Hello World!");;}
void print_hello_world_0 () {
__fn_main_print_hello_world_0();}
int __fn_main_hello_name_0(){printf("%s\n",__hello_name_0.name);;}
void hello_name_0 (char* name) {memcpy(__hello_name_0.name, name, 10);
__fn_main_hello_name_0();}
int __fn_main_sum_up_to_n_0(){__sum_up_to_n_0.result = (__sum_up_to_n_0.current + __sum_up_to_n_0.result);;
return __sum_up_to_n_0.current = (__sum_up_to_n_0.current + 1);;;}
int __fn_main_sum_up_to_n_1(){__sum_up_to_n_0.current = 1;;
__sum_up_to_n_0.result = 0;;
while ((__sum_up_to_n_0.current <= __sum_up_to_n_0.n)) {__fn_main_sum_up_to_n_0();};
return __sum_up_to_n_0.result;;}
int sum_up_to_n_0 (int n) {__sum_up_to_n_0.n = n;
return __fn_main_sum_up_to_n_1();}
int __fn_main_sum_up_to_n_2_0(){__sum_up_to_n_2_0.result = __if_val_int(((((__sum_up_to_n_2_0.current % 3)) == 0) || (((__sum_up_to_n_2_0.current % 5)) == 0)),(__sum_up_to_n_2_0.result + __sum_up_to_n_2_0.current),__sum_up_to_n_2_0.result);;
return __sum_up_to_n_2_0.current = (__sum_up_to_n_2_0.current + 1);;;}
int __fn_main_sum_up_to_n_2_1(){__sum_up_to_n_2_0.current = 1;;
__sum_up_to_n_2_0.result = 0;;
while ((__sum_up_to_n_2_0.current <= __sum_up_to_n_2_0.n)) {__fn_main_sum_up_to_n_2_0();};
return __sum_up_to_n_2_0.result;;}
int sum_up_to_n_2_0 (int n) {__sum_up_to_n_2_0.n = n;
return __fn_main_sum_up_to_n_2_1();}
int __fn_main_multiplication_table_0(){printf("%d %s %d %s %d\n",__multiplication_table_0.current, "x", __multiplication_table_0.i, ": ", (__multiplication_table_0.current * __multiplication_table_0.i));;}
int __fn_main_multiplication_table_1(){__fn_main_multiplication_table_0();
return __multiplication_table_0.current = (__multiplication_table_0.current + 1);;;}
int __fn_main_multiplication_table_2(){while ((__multiplication_table_0.current <= 10)) {__fn_main_multiplication_table_1();};
__multiplication_table_0.current = 0;;
return __multiplication_table_0.i = (__multiplication_table_0.i + 1);;;}
int __fn_main_multiplication_table_3(){__multiplication_table_0.i = 0;;
__multiplication_table_0.current = 0;;
while ((__multiplication_table_0.i <= 12)) {__fn_main_multiplication_table_2();};
return 0;;}
int multiplication_table_0 () {
return __fn_main_multiplication_table_3();}
int main() {
;
;
;
;
;
print_hello_world_0()
;
hello_name_0("Alexandro")
;
__fn_main_0();
__fn_main_1();
multiplication_table_0()
;
return 0;
}
|
C
|
//Nome do programa: deithel.c
//Nome do Autor: Eduardo Felizardo Cândido
//Data de Criação: 29/06/2019
//Descrição ou Finalidade:
/*5.9 Tarifa de estacionamento.
Um estacionamento cobra uma tarifa mínima de R$ 2,00 por uma permanência de até três horas, e R$ 0,50 adicionais por hora para cada hora, ou parte dela, por até três horas. A tarifa máxima para qualquer período de 24 horas é de R$ 10,00. Suponha que nenhum carro estacione por mais de 24 horas de cada vez. Escreva um programa que calcule e imprima as tarifas de estacionamento para cada um dos três clientes que utilizaram esse estacionamento ontem. Você deverá informar as horas de permanência de cada cliente. Seu programa deverá imprimir os resultados em um formato tabular e deverá calcular e imprimir o total recebido ontem. O programa deverá usar a função calcularTaxas para determinar o valor devido por cliente. Sua saída deverá aparecer no seguinte formato:
Carro Horas Taxa
1 1,5 2,00
2 4,0 2,50
3 24,0 10,00
Total 29,5 14,50 */
#include <stdio.h>
float estacionamento_taxa(float taxa);
int main(void) //inicio da função main.
{
/* declaração das varáveis */
int i;
float somaH = 0, somaT = 0, x = 0;
/* entrada de dados */
//printf("Digite a hora de permanencia: ");
//scanf("%f", &x);
/* processamento */
printf("%s\t%s\t%s\n", "Carro", "Horas", "Taxa");
for(i = 1; i < 4; i++)
{
printf("Digite a hora de permanencia: ");
scanf("%f", &x);
printf("%d\t%.2f\t%.2f\n", i, x, estacionamento_taxa(x));
somaH += x;
somaT += estacionamento_taxa(x);
}
/* saída de dados */
printf("%s\t%.2f\t%.2f\n", "TOTAL", somaH, somaT);
} //fim da função main.
float estacionamento_taxa(float hora)
{
float taxa = 2.00;
if(hora < 3)
{
return taxa;
}
else if (hora > 3 && hora <= 6)
{
return (taxa + ((hora - 3) * 0.5));
}
else
{
return 10.00;
}
}
|
C
|
/********************** debugput.h ************************
*
* Display debug output on host via ARM DCC
*
* A low priority thread empties the debugOutput queue to the
* host debugger communication port
*
* Data printed to the queue when full are discarded
* (Never blocks waiting for the host)
*
* Does not support output from interrupt handlers
*
* Any ChibiOS panic messages are output to the host
*
* This code is an example of using the openocd debug message system.
*
* Before the message output is seen in the debug window, the functionality
* will need enabling:
*
** GDB **
* From the gdb prompt: monitor target_request debugmsgs enable
*
** Telnet **
*From the Telnet prompt: target_request debugmsgs enable
*
*Spen
*spen@spen-soft.co.uk
*
***************************************************************/
#include <ch.h>
//max length of debugPrint() string.
//0 omits debugPrint() entirely
//<0 avoids allocation of global buffer by evaluating printf twice
#define debugPrintBufSize -250
Thread *debugPutInit(char *outq, size_t outqSize);
/*
allocate output queue of outqSize bytes and start background thread
return background thread
*/
#define debugPrintInit(q) debugPutInit(q, sizeof q)
int debugPutc(int c);
/*
returns -1 if output fails
*/
size_t debugPut(const uint8_t *block, size_t n);
/*
truncate any block > 255 bytes
returns # of characters actually output (including the trailing newline)
*/
size_t debugPuts(const char *str);
#if debugPrintBufSize
size_t debugPrint(const char *fmt, ...);
/*
printf style debugging output
outputs a trailing newline
returns # of characters actually output (including the trailing newline)
*/
#endif
|
C
|
/* Copyright (c) 1993 Association of Universities for Research
* in Astronomy. All rights reserved. Produced under National
* Aeronautics and Space Administration Contract No. NAS5-26555.
*
* hdecompress: decompress image using hcompress algorithm
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <stdarg.h>
#include "config.h"
int errno;
#define FAILURE (1)
/* MYFILE structure for compression to a file
* Defined this way so same code can be used for file or buffer.
*/
typedef FILE MYFILE;
#define mygetc getc
#define myputc putc
/*
* address buffer type (could be unsigned char if image size < 512 pixels)
*/
typedef short ADDRTYPE;
/* function prototypes */
/* hcompress routines */
static void hinv(int a[], int nx, int ny, int smooth, int scale, int *status);
static void hsmooth(int a[], int nxtop, int nytop, int ny, int scale);
static void decode(MYFILE *infile, int **a, int *nx, int *ny, int *scale, int *status);
static void dodecode(MYFILE *infile, int a[], int nx, int ny, unsigned char nbitplanes[3], int scale, int *status);
static void qtree_decode(MYFILE *infile, int a[], int n, int nqx, int nqy, int nbitplanes, int *status);
/* data I/O routines */
static int readint(MYFILE *infile, int *status);
static void qread(MYFILE *infile, char *a, int n, int *status);
static int myread(MYFILE *file, char buffer[], int n);
/* bit I/O */
static void start_inputing_bits(void);
static int input_bit(MYFILE *infile, int *status);
static int input_nbits(MYFILE *infile, int n, int *status);
/* secondary routines */
static void xunshuffle(int a[], int nx, int ny, int nydim, int *status);
static void yunshuffle(int a[], int nx, int ny, int nydim, int *status);
static int qaddr_expand(MYFILE *infile, ADDRTYPE *xthis, ADDRTYPE *ythis,
int nt, ADDRTYPE *xnext, ADDRTYPE *ynext, ADDRTYPE *xscr, ADDRTYPE *yscr);
static void qaddr_bitins(MYFILE *infile, ADDRTYPE *xthis, ADDRTYPE *ythis,
int nt, int a[], int n, int bit);
static void read_bdirect(MYFILE *infile, int b[], int n, int nx,
int ny, int bit);
static int input_huffman(MYFILE *infile);
static void erreof(const char *str, int *status);
static void printerr(const char *format, ...);
extern int hdecompress(int **a, int *nx, int *ny, int *scale, int smooth, MYFILE *infile, int *status)
{
if (*status != 0) return(*status);
/*
* Read from stdin, passing header through to stdout for FITS format,
* and decode. Returns address, size, scale,
* and (possibly) format
*/
decode(infile,a,nx,ny,scale,status);
/*
* Inverse H-transform
*/
hinv(*a,*nx,*ny,smooth,*scale,status);
return(*status);
}
/* hinv.c Inverse H-transform of NX x NY integer image
*
* Programmer: R. White Date: 16 June 1994
*/
/* smooth = 0 for no smoothing, else smooth during inversion
* scale is used if smoothing is specified
*/
static void hinv(int a[], int nx, int ny, int smooth, int scale, int *status)
{
int nmax, log2n, i, k;
int nxtop,nytop,nxf,nyf,c;
int bit0, bit1, bit2, mask0, mask1, mask2,
prnd0, prnd1, prnd2, nrnd0, nrnd1, nrnd2, lowbit0, lowbit1;
int h0, hx, hy, hc, sum1, sum2;
int *p00, *p10, *pend;
if (*status != 0) return;
/*
* log2n is log2 of max(nx,ny) rounded up to next power of 2
*/
nmax = (nx>ny) ? nx : ny;
log2n = log((float) nmax)/log(2.0)+0.5;
if ( nmax > (1<<log2n) ) {
log2n += 1;
}
/*
* set up masks, rounding parameters
*/
bit0 = 1 << (log2n - 1);
bit1 = bit0 << 1;
bit2 = bit0 << 2;
mask0 = -bit0;
mask1 = mask0 << 1;
mask2 = mask0 << 2;
prnd0 = bit0 >> 1;
prnd1 = bit1 >> 1;
prnd2 = bit2 >> 1;
nrnd0 = prnd0 - 1;
nrnd1 = prnd1 - 1;
nrnd2 = prnd2 - 1;
/*
* round h0 to multiple of bit2
*/
a[0] = (a[0] + ((a[0] >= 0) ? prnd2 : nrnd2)) & mask2;
/*
* do log2n expansions
*
* We're indexing a as a 2-D array with dimensions (nx,ny).
*/
nxtop = 1;
nytop = 1;
nxf = nx;
nyf = ny;
c = 1<<log2n;
for (k = log2n-1; k>0; k--) {
/*
* this somewhat cryptic code generates the sequence
* ntop[k-1] = (ntop[k]+1)/2, where ntop[log2n] = n
*/
c = c>>1;
nxtop = nxtop<<1;
nytop = nytop<<1;
if (nxf <= c) { nxtop -= 1; } else { nxf -= c; }
if (nyf <= c) { nytop -= 1; } else { nyf -= c; }
/*
* unshuffle in each dimension to interleave coefficients
*/
xunshuffle(a,nxtop,nytop,ny,status);
yunshuffle(a,nxtop,nytop,ny,status);
/*
* smooth by interpolating coefficients if SMOOTH != 0
*/
if (smooth) hsmooth(a,nxtop,nytop,ny,scale);
for (i = 0; i<nxtop-1; i += 2) {
pend = &a[ny*i+nytop-1];
for (p00 = &a[ny*i], p10 = p00+ny; p00 < pend; p00 += 2, p10 += 2) {
h0 = *(p00 );
hx = *(p10 );
hy = *(p00+1);
hc = *(p10+1);
/*
* round hc to multiple of bit0
*/
hc = (hc + ((hc >= 0) ? prnd0 : nrnd0)) & mask0;
/*
* round hx and hy to multiple of bit1
* h0 is already a multiple of bit2
* propagate bit0 of hc to hx,hy
*/
lowbit0 = hc & bit0;
if (lowbit0==0) {
/*
* lowbit0 = 0
*/
if (hx >= 0) {
hx = ((hx + prnd1) & mask1);
} else {
hx = ((hx + nrnd1) & mask1);
}
if (hy >= 0) {
hy = ((hy + prnd1) & mask1);
} else {
hy = ((hy + nrnd1) & mask1);
}
/*
* Propagate bits 0 and 1 of hc,hx,hy to h0.
* This could be simplified if we assume h0>0, but then
* the inversion would not be lossless for images with
* negative pixels.
*/
lowbit1 = (hc ^ hx ^ hy) & bit1;
h0 = (h0 >= 0) ? (h0 - lowbit1) : (h0 + lowbit1);
} else {
/*
* lowbit0 != 0
*/
if (hx >= 0) {
hx = ((hx + prnd1) & mask1) - lowbit0;
} else {
hx = ((hx + nrnd1) & mask1) + lowbit0;
}
if (hy >= 0) {
hy = ((hy + prnd1) & mask1) - lowbit0;
} else {
hy = ((hy + nrnd1) & mask1) + lowbit0;
}
lowbit1 = (hc ^ hx ^ hy) & bit1;
h0 = h0 + lowbit0 - lowbit1;
}
/*
* Divide sums by 2
*/
sum1 = h0+hx;
sum2 = hy+hc;
*(p10+1) = (sum1 + sum2) >> 1;
*(p10 ) = (sum1 - sum2) >> 1;
sum1 = h0-hx;
sum2 = hy-hc;
*(p00+1) = (sum1 + sum2) >> 1;
*(p00 ) = (sum1 - sum2) >> 1;
}
if (p00==pend) {
/*
* do last element in row if row length is odd
* p00+1, p10+1 are off edge
*/
h0 = *(p00 );
hx = *(p10 );
if (hx >= 0) {
hx = ((hx + prnd1) & mask1);
} else {
hx = ((hx + nrnd1) & mask1);
}
lowbit1 = hx & bit1;
h0 = (h0 >= 0) ? (h0 - lowbit1) : (h0 + lowbit1);
*p10 = (h0 + hx) >> 1;
*p00 = (h0 - hx) >> 1;
}
}
if (i<nxtop) {
/*
* do last row if column length is odd
* p10, p10+1 are off edge
*/
pend = &a[ny*i+nytop-1];
for (p00 = &a[ny*i]; p00 < pend; p00 += 2) {
h0 = *(p00 );
hy = *(p00+1);
if (hy >= 0) {
hy = ((hy + prnd1) & mask1);
} else {
hy = ((hy + nrnd1) & mask1);
}
lowbit1 = hy & bit1;
h0 = (h0 >= 0) ? (h0 - lowbit1) : (h0 + lowbit1);
*(p00+1) = (h0 + hy) >> 1;
*(p00 ) = (h0 - hy) >> 1;
}
if (p00==pend) {
/*
* do corner element if both row and column lengths are odd
* p00+1, p10, p10+1 are off edge
*/
*p00 = *p00 >> 1;
}
}
/*
* divide all the masks and rounding values by 2
*/
bit2 = bit1;
bit1 = bit0;
bit0 = bit0 >> 1;
mask1 = mask0;
mask0 = mask0 >> 1;
prnd1 = prnd0;
prnd0 = prnd0 >> 1;
nrnd1 = nrnd0;
nrnd0 = prnd0 - 1;
}
/*
* Last pass (k=0) has some differences:
*
* Shift by 2 instead of 1
*
* Use explicit values for all variables to avoid unnecessary shifts etc:
*
* N bitN maskN prndN nrndN
* 0 1 -1 0 0 (note nrnd0 != prnd0-1)
* 1 2 -2 1 0
* 2 4 -4 2 1
*/
/*
* Check nxtop=nx, nytop=ny
*/
c = c>>1;
nxtop = nxtop<<1;
nytop = nytop<<1;
if (nxf <= c) { nxtop -= 1; } else { nxf -= c; }
if (nyf <= c) { nytop -= 1; } else { nyf -= c; }
if (nxtop != nx || nytop != ny) {
printerr("hinv: error, final image size is %dx%d, not %dx%d\n",
nxtop, nytop, nx, ny);
*status = FAILURE;
return;
}
/*
* unshuffle in each dimension to interleave coefficients
*/
xunshuffle(a,nx,ny,ny,status);
yunshuffle(a,nx,ny,ny,status);
/*
* smooth by interpolating coefficients if SMOOTH != 0
*/
if (smooth) hsmooth(a,nx,ny,ny,scale);
for (i = 0; i<nx-1; i += 2) {
pend = &a[ny*i+ny-1];
for (p00 = &a[ny*i], p10 = p00+ny; p00 < pend; p00 += 2, p10 += 2) {
h0 = *(p00 );
hx = *(p10 );
hy = *(p00+1);
hc = *(p10+1);
lowbit0 = hc & 1;
if (lowbit0==0) {
/*
* lowbit0 = 0
*/
if (hx>=0) { hx = (hx+1) & -2; } else { hx = hx & -2; }
if (hy>=0) { hy = (hy+1) & -2; } else { hy = hy & -2; }
lowbit1 = (hc ^ hx ^ hy) & 2;
h0 = (h0 >= 0) ? (h0 - lowbit1) : (h0 + lowbit1);
} else {
/*
* lowbit0 = 1
*/
if (hx>=0) { hx = ((hx+1) & -2)-1; } else { hx = (hx & -2)+1; }
if (hy>=0) { hy = ((hy+1) & -2)-1; } else { hy = (hy & -2)+1; }
lowbit1 = (hc ^ hx ^ hy) & 2;
h0 = h0 + 1 - lowbit1;
}
/*
* Divide sums by 4
*/
sum1 = h0+hx;
sum2 = hy+hc;
*(p10+1) = (sum1 + sum2) >> 2;
*(p10 ) = (sum1 - sum2) >> 2;
sum1 = h0-hx;
sum2 = hy-hc;
*(p00+1) = (sum1 + sum2) >> 2;
*(p00 ) = (sum1 - sum2) >> 2;
}
if (p00==pend) {
/*
* do last element in row if row length is odd
* p00+1, p10+1 are off edge
*/
h0 = *p00;
hx = *p10;
if (hx >= 0) { hx = (hx + 1) & -2; } else { hx = hx & -2; }
lowbit1 = hx & 2;
h0 = (h0 >= 0) ? (h0 - lowbit1) : (h0 + lowbit1);
*p10 = (h0 + hx) >> 2;
*p00 = (h0 - hx) >> 2;
}
}
if (i<nx) {
/*
* do last row if column length is odd
* p10, p10+1 are off edge
*/
pend = &a[ny*i+ny-1];
for (p00 = &a[ny*i]; p00 < pend; p00 += 2) {
h0 = *(p00 );
hy = *(p00+1);
if (hy >= 0) { hy = (hy + 1) & -2; } else { hy = hy & -2; }
lowbit1 = hy & 2;
h0 = (h0 >= 0) ? (h0 - lowbit1) : (h0 + lowbit1);
*(p00+1) = (h0 + hy) >> 2;
*(p00 ) = (h0 - hy) >> 2;
}
if (p00==pend) {
/*
* do corner element if both row and column lengths are odd
* p00+1, p10, p10+1 are off edge
*/
*p00 = *p00 >> 2;
}
}
}
static void xunshuffle(int a[], int nx, int ny, int nydim, int *status)
{
int j;
int nhalf;
int *p1, *p2, *pt, *pend, *tmp;
if (*status != 0) return;
/*
* get temporary storage for shuffling elements
*/
tmp = (int *) malloc(((ny+1)/2)*sizeof(int));
if (tmp == (int *) NULL) {
printerr("hinv: insufficient memory\n");
*status = FAILURE;
return;
}
nhalf = (ny+1)>>1;
for (j = 0; j<nx; j++) {
/* unshuffle(&a[nydim*j],ny,1,tmp); */
/*
* copy 2nd half of array to tmp
*/
(void) memcpy(tmp, &a[j*nydim+nhalf], (ny-nhalf)*sizeof(int));
/*
* distribute 1st half of array to even elements
*/
pend = &a[j*nydim];
for (p2 = &a[j*nydim+nhalf-1], p1 = &a[j*nydim+((nhalf-1)<<1)];
p2 >= pend; p1 -= 2, p2 -= 1) {
*p1 = *p2;
}
/*
* now distribute 2nd half of array (in tmp) to odd elements
*/
pend = &a[j*nydim+ny];
for (pt = tmp, p1 = &a[j*nydim+1]; p1<pend; p1 += 2, pt += 1) {
*p1 = *pt;
}
}
free(tmp);
}
/*
* unshuffle in y direction: take even elements from beginning of
* array, odd elements from end and interleave them. This is done
* using a somewhat complicated method for efficiency. The straightforward
* approach is slow because the scattered memory accesses don't
* take advantage of the cache (I think.) This version does
* operations a row at a time so that consecutive memory locations
* are accessed.
*/
static void yunshuffle(int a[], int nx, int ny, int nydim, int *status)
{
int j, k, tt, oddoffset, *tmp;
int *p, *pt;
unsigned char *flag;
if (*status != 0) return;
/*
* get temporary storage for shuffling elements
*/
tmp = (int *) malloc(ny*sizeof(int));
flag = (unsigned char *) malloc(nx*sizeof(unsigned char));
if(tmp == (int *) NULL || flag == (unsigned char *) NULL) {
printerr("hinv: insufficient memory\n");
*status = FAILURE;
return;
}
/*
* initialize flag array telling whether row is done
*/
for (j=0; j<nx; j++) flag[j] = 1;
oddoffset = (nx+1)/2;
/*
* shuffle each row to appropriate location
* row 0 is already in right location
*/
for (j=1; j<nx; j++) {
if (flag[j]) {
flag[j] = 0;
/*
* where does this row belong?
*/
if (j >= oddoffset) {
/* odd row */
k = ((j-oddoffset)<<1) + 1;
} else {
/* even row */
k = j<<1;
}
if (j != k) {
/*
* copy the row
*/
(void) memcpy(tmp,&a[nydim*j],ny*sizeof(int));
/*
* keep shuffling until we reach a row that is done
*/
while (flag[k]) {
flag[k] = 0;
/*
* do the exchange
*/
for (p = &a[nydim*k], pt=tmp; p < &a[nydim*k+ny]; p++, pt++) {
tt = *p;
*p = *pt;
*pt = tt;
}
if (k >= oddoffset) {
k = ((k-oddoffset)<<1) + 1;
} else {
k = k<<1;
}
}
/*
* copy the last row into place
* this should always end up with j=k
*/
(void) memcpy(&a[nydim*k],tmp,ny*sizeof(int));
if (j != k) {
printerr("error: yunshuffle failed!\nj=%d k=%d\n", j, k);
*status = FAILURE;
return;
}
}
}
}
free(tmp);
free(flag);
}
/* hsmooth.c Smooth H-transform image by adjusting coefficients toward
* interpolated values
*
* Programmer: R. White Date: 13 April 1992
*/
#define min(a,b) (((a)<(b)) ? (a) : (b))
#define max(a,b) (((a)>(b)) ? (a) : (b))
static void hsmooth(int a[], int nxtop, int nytop, int ny, int scale)
{
int i, j;
int ny2, s10, s00, diff, dmax, dmin, s, smax;
int hm, h0, hp, hmm, hpm, hmp, hpp, hx2, hy2;
int m1,m2;
/*
* Maximum change in coefficients is determined by scale factor.
* Since we rounded during division (see digitize.c), the biggest
* permitted change is scale/2.
*/
smax = (scale >> 1);
if (smax <= 0) return;
ny2 = ny << 1;
/*
* We're indexing a as a 2-D array with dimensions (nxtop,ny) of which
* only (nxtop,nytop) are used. The coefficients on the edge of the
* array are not adjusted (which is why the loops below start at 2
* instead of 0 and end at nxtop-2 instead of nxtop.)
*/
/*
* Adjust x difference hx
*/
for (i = 2; i<nxtop-2; i += 2) {
s00 = ny*i; /* s00 is index of a[i,j] */
s10 = s00+ny; /* s10 is index of a[i+1,j] */
for (j = 0; j<nytop; j += 2) {
/*
* hp is h0 (mean value) in next x zone, hm is h0 in previous x zone
*/
hm = a[s00-ny2];
h0 = a[s00];
hp = a[s00+ny2];
/*
* diff = 8 * hx slope that would match h0 in neighboring zones
*/
diff = hp-hm;
/*
* monotonicity constraints on diff
*/
dmax = max( min( (hp-h0), (h0-hm) ), 0 ) << 2;
dmin = min( max( (hp-h0), (h0-hm) ), 0 ) << 2;
/*
* if monotonicity would set slope = 0 then don't change hx.
* note dmax>=0, dmin<=0.
*/
if (dmin < dmax) {
diff = max( min(diff, dmax), dmin);
/*
* Compute change in slope limited to range +/- smax.
* Careful with rounding negative numbers when using
* shift for divide by 8.
*/
s = diff-(a[s10]<<3);
s = (s>=0) ? (s>>3) : ((s+7)>>3) ;
s = max( min(s, smax), -smax);
a[s10] = a[s10]+s;
}
s00 += 2;
s10 += 2;
}
}
/*
* Adjust y difference hy
*/
for (i = 0; i<nxtop; i += 2) {
s00 = ny*i+2;
s10 = s00+ny;
for (j = 2; j<nytop-2; j += 2) {
hm = a[s00-2];
h0 = a[s00];
hp = a[s00+2];
diff = hp-hm;
dmax = max( min( (hp-h0), (h0-hm) ), 0 ) << 2;
dmin = min( max( (hp-h0), (h0-hm) ), 0 ) << 2;
if (dmin < dmax) {
diff = max( min(diff, dmax), dmin);
s = diff-(a[s00+1]<<3);
s = (s>=0) ? (s>>3) : ((s+7)>>3) ;
s = max( min(s, smax), -smax);
a[s00+1] = a[s00+1]+s;
}
s00 += 2;
s10 += 2;
}
}
/*
* Adjust curvature difference hc
*/
for (i = 2; i<nxtop-2; i += 2) {
s00 = ny*i+2;
s10 = s00+ny;
for (j = 2; j<nytop-2; j += 2) {
/*
* ------------------ y
* | hmp | | hpp | |
* ------------------ |
* | | h0 | | |
* ------------------ -------x
* | hmm | | hpm |
* ------------------
*/
hmm = a[s00-ny2-2];
hpm = a[s00+ny2-2];
hmp = a[s00-ny2+2];
hpp = a[s00+ny2+2];
h0 = a[s00];
/*
* diff = 64 * hc value that would match h0 in neighboring zones
*/
diff = hpp + hmm - hmp - hpm;
/*
* 2 times x,y slopes in this zone
*/
hx2 = a[s10 ]<<1;
hy2 = a[s00+1]<<1;
/*
* monotonicity constraints on diff
*/
m1 = min(max(hpp-h0,0)-hx2-hy2, max(h0-hpm,0)+hx2-hy2);
m2 = min(max(h0-hmp,0)-hx2+hy2, max(hmm-h0,0)+hx2+hy2);
dmax = min(m1,m2) << 4;
m1 = max(min(hpp-h0,0)-hx2-hy2, min(h0-hpm,0)+hx2-hy2);
m2 = max(min(h0-hmp,0)-hx2+hy2, min(hmm-h0,0)+hx2+hy2);
dmin = max(m1,m2) << 4;
/*
* if monotonicity would set slope = 0 then don't change hc.
* note dmax>=0, dmin<=0.
*/
if (dmin < dmax) {
diff = max( min(diff, dmax), dmin);
/*
* Compute change in slope limited to range +/- smax.
* Careful with rounding negative numbers when using
* shift for divide by 64.
*/
s = diff-(a[s10+1]<<6);
s = (s>=0) ? (s>>6) : ((s+63)>>6) ;
s = max( min(s, smax), -smax);
a[s10+1] = a[s10+1]+s;
}
s00 += 2;
s10 += 2;
}
}
}
/* decode.c read codes from infile and construct array
*
* Programmer: R. White Date: 16 June 1994
*/
static char code_magic[2] = { (char)0xDD, (char)0x99 };
static void decode(MYFILE *infile, int **a, int *nx, int *ny, int *scale, int *status)
{
int nel, sumall;
unsigned char nbitplanes[3];
char tmagic[2];
if (*status != 0) return;
/*
* File must start with special 2-byte magic code
*/
qread(infile, tmagic, sizeof(tmagic), status);
/*
* check for correct magic code value
*/
if (memcmp(tmagic,code_magic,sizeof(code_magic)) != 0) {
printerr("bad file format\n");
*status = FAILURE;
return;
}
*nx =readint(infile,status); /* x size of image */
*ny =readint(infile,status); /* y size of image */
*scale=readint(infile,status); /* scale factor for digitization */
/*
* allocate memory for array
* use calloc so it gets initialized to zero
*/
nel = (*nx) * (*ny);
*a = (int *) calloc(nel,sizeof(int));
if (*a == (int *) NULL) {
printerr("decode: insufficient memory\n");
*status = FAILURE;
return;
}
/* sum of all pixels */
sumall=readint(infile,status);
/* # bits in quadrants */
qread(infile, (char *) nbitplanes, sizeof(nbitplanes), status);
dodecode(infile, *a, *nx, *ny, nbitplanes, *scale, status);
/*
* put sum of all pixels back into pixel 0
*/
if (*scale > 1) {
(*a)[0] = sumall * (*scale);
} else {
(*a)[0] = sumall;
}
}
/* dodecode.c Decode stream of characters on infile and return array
*
* This version encodes the different quadrants separately
*
* Programmer: R. White Date: 16 June 1994
*/
static void dodecode(MYFILE *infile, int a[], int nx, int ny,
unsigned char nbitplanes[3], int scale, int *status)
{
int i, nel, nx2, ny2;
if (*status != 0) return;
nel = nx*ny;
nx2 = (nx+1)/2;
ny2 = (ny+1)/2;
/*
* Initialize bit input
*/
start_inputing_bits();
/*
* read bit planes for each quadrant
*/
qtree_decode(infile, &a[0], ny, nx2, ny2, nbitplanes[0], status);
qtree_decode(infile, &a[ny2], ny, nx2, ny/2, nbitplanes[1], status);
qtree_decode(infile, &a[ny*nx2], ny, nx/2, ny2, nbitplanes[1], status);
qtree_decode(infile, &a[ny*nx2+ny2], ny, nx/2, ny/2, nbitplanes[2], status);
/*
* make sure there is an EOF symbol (nybble=0) at end
*/
if (input_nbits(infile,4,status) != 0) {
printerr("dodecode: bad bit plane values\n");
*status = FAILURE;
return;
}
/*
* now get the sign bits and do scaling at same time
* Re-initialize bit input
*/
start_inputing_bits();
if (scale>1) {
for (i=0; i<nel; i++) {
if (a[i] != 0) {
if (input_bit(infile,status) != 0) {
a[i] = -scale*a[i];
} else {
a[i] = scale*a[i];
}
}
}
} else {
/* no scaling if scale <= 1 */
for (i=0; i<nel; i++) {
if (a[i] != 0) {
if (input_bit(infile,status) != 0) a[i] = -a[i];
}
}
}
}
/* Bit input routines */
/* Bit buffer */
static int buffer; /* Bits waiting to be input */
static int bits_to_go; /* Number of bits still in buffer */
/* Initialize bit input */
static void start_inputing_bits(void)
{
/*
* Buffer starts out with no bits in it
*/
bits_to_go = 0;
}
/* Input a bit */
static int input_bit(MYFILE *infile, int *status)
{
if (*status != 0) return(0);
if (bits_to_go == 0) {
/* Read next byte if no bits left in buffer */
buffer = mygetc(infile);
if (buffer == EOF) {
erreof("input_bit", status);
return(0);
}
bits_to_go = 8;
}
/*
* Return the next bit
*/
bits_to_go -= 1;
return((buffer>>bits_to_go) & 1);
}
/* Input N bits (N must be <= 24) */
static int input_nbits(MYFILE *infile, int n, int *status)
{
int c;
/* local copies */
int lbuffer;
int lbits_to_go;
if (*status != 0) return(0);
lbuffer = buffer;
lbits_to_go = bits_to_go;
while (lbits_to_go < n) {
/*
* need another byte's worth of bits
*/
lbuffer <<= 8;
c = getc(infile);
if (c == EOF) {
erreof("input_nbits", status);
return(0);
}
lbuffer |= c;
lbits_to_go += 8;
}
/*
* now pick off the first n bits
*/
lbits_to_go -= n;
c = (lbuffer>>lbits_to_go) & ((1<<n)-1);
bits_to_go = lbits_to_go;
buffer = lbuffer;
return( c );
}
/* qtree_decode.c Read stream of codes from infile and construct bit planes
* in quadrant of 2-D array using binary quadtree coding.
* New version using address approach.
*
* Programmer: R. White Date: 12 September 1994
*/
/*
* input 1 bit without EOF error checking
* (EOFs get picked up in dodecode after calls to qtree_decode are done)
*/
#define input_bit_noerr(infile) (bits_to_go ? \
((buffer>>(--bits_to_go)) & 1) : \
(((buffer = mygetc(infile))>>(bits_to_go = 7)) & 1))
/*
* input N bits without EOF error checking
*/
#define input_nbits_noerr(infile,n) ((bits_to_go<n) ? \
(((buffer = (buffer<<8) | getc(infile)) \
>> (bits_to_go += 8-n)) & ((1<<n)-1)) : \
((buffer>>(bits_to_go -= n)) & ((1<<n)-1)) )
static void qtree_decode(MYFILE *infile, int a[], int n, int nqx, int nqy, int nbitplanes, int *status)
{
int log2n, k, bit, b, nqmax;
int nqx2, nqy2;
/*
* address buffers
*/
ADDRTYPE *xaddr1, *xaddr2, *yaddr1, *yaddr2, *xscr, *yscr;
ADDRTYPE *xthis, *ythis, *xnext, *ynext, *ptmp;
int nt;
if (*status != 0) return;
/*
* log2n is log2 of max(nqx,nqy) rounded up to next power of 2
*/
nqmax = (nqx>nqy) ? nqx : nqy;
log2n = log((float) nqmax)/log(2.0)+0.5;
if (nqmax > (1<<log2n)) {
log2n += 1;
}
/*
* allocate buffers for addresses
*/
nqx2=(nqx+1)/2;
nqy2=(nqy+1)/2;
xaddr1 = (ADDRTYPE *) malloc(nqx2*nqy2*sizeof(ADDRTYPE));
yaddr1 = (ADDRTYPE *) malloc(nqx2*nqy2*sizeof(ADDRTYPE));
xaddr2 = (ADDRTYPE *) malloc(((nqx2+1)/2)*((nqy2+1)/2)*sizeof(ADDRTYPE));
yaddr2 = (ADDRTYPE *) malloc(((nqx2+1)/2)*((nqy2+1)/2)*sizeof(ADDRTYPE));
xscr = (ADDRTYPE *) malloc(nqmax*sizeof(ADDRTYPE));
yscr = (ADDRTYPE *) malloc(nqmax*sizeof(ADDRTYPE));
if ((xaddr1 == (ADDRTYPE *) NULL) || (yaddr1 == (ADDRTYPE *) NULL) ||
(xaddr2 == (ADDRTYPE *) NULL) || (yaddr2 == (ADDRTYPE *) NULL) ||
(xscr == (ADDRTYPE *) NULL) || (yscr == (ADDRTYPE *) NULL)) {
printerr("qtree_decode: insufficient memory\n");
*status = FAILURE;
return;
}
/*
* now decode each bit plane, starting at the top
* A is assumed to be initialized to zero
*/
for (bit = nbitplanes-1; bit >= 0; bit--) {
/*
* Was bitplane was quadtree-coded or written directly?
*/
b = input_nbits_noerr(infile,4);
if(b == 0) {
/*
* bit map was written directly
*/
read_bdirect(infile,a,n,nqx,nqy,bit);
} else if (b != 0xf) {
printerr("qtree_decode: bad format code %x\n",b);
*status = FAILURE;
return;
} else {
/*
* bitmap was quadtree-coded, do log2n expansions
* read first code
*/
b = input_huffman(infile);
/*
* if code is zero, implying all bits are zero, just
* skip the rest for this plane
*/
if (b != 0) {
/*
* initialize pointers to buffer pairs
* want to end up writing to buffer 1
*/
if ((log2n & 1) == 0) {
xthis = xaddr1;
ythis = yaddr1;
xnext = xaddr2;
ynext = yaddr2;
} else {
xthis = xaddr2;
ythis = yaddr2;
xnext = xaddr1;
ynext = yaddr1;
}
nt = 0;
if ((b & 1) != 0) { xthis[nt] = 1; ythis[nt++] = 1; }
if ((b & 2) != 0) { xthis[nt] = 0; ythis[nt++] = 1; }
if ((b & 4) != 0) { xthis[nt] = 1; ythis[nt++] = 0; }
if ((b & 8) != 0) { xthis[nt] = 0; ythis[nt++] = 0; }
/*
* now do log2n expansions, reading codes from file as necessary
*/
for (k = 1; k<log2n-1; k++) {
nt = qaddr_expand(infile, xthis, ythis, nt,
xnext, ynext, xscr, yscr);
/* swap buffers */
ptmp = xthis; xthis = xnext; xnext = ptmp;
ptmp = ythis; ythis = ynext; ynext = ptmp;
}
/*
* now copy last set of 4-bit codes to bitplane bit of array a
*/
qaddr_bitins(infile, xthis, ythis, nt, a, n, bit);
}
}
}
free(xaddr1);
free(yaddr1);
free(xaddr2);
free(yaddr2);
free(xscr);
free(yscr);
}
/*
* do one quadtree address expansion step
* current address list in xthis, ythis is expanded and put into xnext, ynext
* return value is new number of elements
*/
static int qaddr_expand(MYFILE *infile, ADDRTYPE *xthis, ADDRTYPE *ythis, int nt, ADDRTYPE *xnext, ADDRTYPE *ynext, ADDRTYPE *xscr, ADDRTYPE *yscr)
{
int b, i, j, k, m;
ADDRTYPE ylast, xoff, yoff;
/*
* read 1 quad for each element of xthis,ythis
* keep second row expansions in xscr,yscr and copy them to next buffer
* after each row is finished.
*/
ylast = ythis[0];
k = 0;
for (i = 0, j = 0; i < nt; i++) {
if (ylast != ythis[i]) {
for (m = 0; m < k; m++, j++) {
xnext[j] = xscr[m];
ynext[j] = yscr[m];
}
k = 0;
ylast = ythis[i];
}
b = input_huffman(infile);
xoff = xthis[i] << 1;
yoff = ythis[i] << 1;
if ((b & 1) != 0) { xnext[j] = xoff | 1; ynext[j++] = yoff | 1; }
if ((b & 2) != 0) { xnext[j] = xoff ; ynext[j++] = yoff | 1; }
if ((b & 4) != 0) { xscr[k] = xoff | 1; yscr[k++] = yoff ; }
if ((b & 8) != 0) { xscr[k] = xoff ; yscr[k++] = yoff ; }
}
for (m = 0; m < k; m++, j++) {
xnext[j] = xscr[m];
ynext[j] = yscr[m];
}
return (j);
}
/*
* Read quads and insert in address locations in bitplane BIT of array A.
*/
static void qaddr_bitins(MYFILE *infile, ADDRTYPE *xthis, ADDRTYPE *ythis, int nt, int a[], int n, int bit)
{
int b, i, *p, bitval;
bitval = 1 << bit;
for (i = 0; i < nt; i++) {
b = input_huffman(infile);
p = &a[ (n * ythis[i] + xthis[i]) << 1 ];
if ((b & 8) != 0) *p |= bitval;
if ((b & 4) != 0) *(p+1) |= bitval;
if ((b & 2) != 0) *(p+n) |= bitval;
if ((b & 1) != 0) *(p+n+1) |= bitval;
}
}
/*
* Read 4-bit codes from infile, expanding each value to 2x2 pixels and
* inserting into bitplane BIT of B.
*/
static void read_bdirect(MYFILE *infile, int b[], int n, int nx, int ny, int bit)
{
int i, tmp, bitval;
int *p00, *pend;
bitval = 1 << bit;
for (i = 0; i<nx; i += 2) {
p00 = &b[n*i];
pend = p00 + ny;
for ( ; p00 < pend; p00 += 2) {
tmp = input_nbits_noerr(infile,4);
if ((tmp & 8) != 0) *(p00 ) |= bitval;
if ((tmp & 4) != 0) *(p00+1 ) |= bitval;
if ((tmp & 2) != 0) *(p00+n ) |= bitval;
if ((tmp & 1) != 0) *(p00+n+1) |= bitval;
}
}
}
/*
* Huffman decoding for fixed codes
*
* Coded values range from 0-15
*
* Huffman code values (hex):
*
* 3e, 00, 01, 08, 02, 09, 1a, 1b,
* 03, 1c, 0a, 1d, 0b, 1e, 3f, 0c
*
* and number of bits in each code:
*
* 6, 3, 3, 4, 3, 4, 5, 5,
* 3, 5, 4, 5, 4, 5, 6, 4
*/
/*
* table of Huffman code translated values
* -1 means no such code
*/
static int tabhuff[31] =
/* 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f */
{ 1, 2, 4, 8, -1, -1, -1, -1, 3, 5, 10, 12, 15, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, 7, 9, 11, 13 };
/* 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e */
static int input_huffman(MYFILE *infile)
{
int c;
/*
* get first 3 bits to start
*/
c = input_nbits_noerr(infile,3);
if (c < 4) return(tabhuff[c]);
/*
* get the next bit
*/
c = input_bit_noerr(infile) | (c<<1);
if (c < 13) return(tabhuff[c]);
/*
* get yet another bit
*/
c = input_bit_noerr(infile) | (c<<1);
if (c < 31) return(tabhuff[c]);
/*
* the 6th bit decides
*/
if (input_bit_noerr(infile)) {
/*
* c = 63
*/
return(14);
} else {
/*
* c = 62
*/
return(0);
}
}
/* qread.c Read binary data
*
* Programmer: R. White Date: 11 March 1991
*/
static int readint(MYFILE *infile, int *status)
{
int a,i;
unsigned char b[4];
if (*status != 0) return(0);
/* Read integer A one byte at a time from infile.
*
* This is portable from Vax to Sun since it eliminates the
* need for byte-swapping.
*/
for (i=0; i<4; i++) qread(infile,(char *) &b[i],1,status);
if (*status != 0) return(0);
a = b[0];
for (i=1; i<4; i++) a = (a<<8) + b[i];
return(a);
}
static void qread(MYFILE *infile, char *a, int n, int *status)
{
if (*status != 0) return;
if(myread(infile, a, n) != n) {
printerr("qread: %s\n", strerror(errno));
*status = FAILURE;
}
}
/*
* read n bytes from file into buffer
* returns number of bytes read (=n) if successful, <=0 if not
*/
static int myread(MYFILE *file, char buffer[], int n)
{
#ifdef TO_A_BUFFER
/*
* this version used when doing I/O to a buffer
*/
if (file->current + n > file->end) return(-1);
(void) memcpy(buffer, file->current, n);
file->current += n;
return(n);
#else
/*
* this version used when doing I/O to a file
*
* this version is for VMS C: each read may return
* fewer than n bytes, so multiple reads may be needed
* to fill the buffer.
*
* I think this is unnecessary for Sun Unix, but it won't hurt
* either, so I'll leave it in.
*/
int nread, total;
/* keep reading until we've read n bytes */
total = 0;
while ( (nread = fread(&buffer[total], 1, n-total, file)) > 0) {
total += nread;
if (total==n) return(total);
}
/* end-of-file or error occurred if we got to here */
return(nread);
#endif
}
/* Print error messages */
static void erreof(const char *str, int *status)
{
/*
* end of file is an error for this application
*/
printerr("%s: unexpected end-of-file\n", str);
*status = FAILURE;
}
static void printerr(const char *format, ...)
{
va_list args;
va_start (args, format);
vfprintf(stderr, format, args);
va_end(args);
}
|
C
|
#include<stdio.h>
void subset(int arr[], int subarray[], int start,
int arraysize, int index, int sub){
int i, j;
if(index == sub){
for(j = 0; j < sub; j++){
printf("%d", subarray[j]);
}
printf("\n");
return;
}
//&& arraysize - i + 1 >= sub - index
for(i = start; i <= arraysize ; i++){
//i+1 is the start
subarray[index] = arr[i];
subset(arr, subarray, i+1, arraysize, index+1, sub);
}
}
void printsubset(int arr[], int arraysize){
int i;
int subarray[arraysize];
for (i = 1; i <= arraysize; i++)
{
/* code */
subset(arr, subarray, 0, arraysize - 1, 0, i);
}
}
int main(){
int arr[20], arraysize, sub, i;
printf("Enter the size of array\n");
scanf("%d", &arraysize);
printf("Enter the element of the array\n");
for(i = 0; i < arraysize; i++){
scanf("%d", &arr[i]);
}
printf("\n\n");
printsubset(arr, arraysize);
return 0;
}
|
C
|
#include<stdio.h>
main()
{
int i;
char a[10],b[10];
printf("enter the string...");
scanf("%s",a);
printf("%s\n",a);
for(i=0;a[i];i++)
printf("%c ",a[i]);
printf("\n");
for(i=0;a[i];i++)
b[i]=a[i];
b[i]=a[i];
for(i=0;b[i];i++)
printf("%c ",b[i]);
printf("\n");
for(i=0;a[i];i++)
if(a[i]>='a' && a[i]<='z')
a[i]=a[i]-32;
for(i=0;a[i];i++)
printf("%c ",a[i]);
printf("\n");
}
|
C
|
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <netdb.h>
int hostname_to_ip(char* domain, struct sockaddr_in *_addr);
void get_domain(char *address, char **domain, char **destination, char **file);
int main(int argc, char** argv){
char buffer[1025];
int portNum, sockfd = 0;
struct sockaddr_in serv_addr;
char *domain,*destination,*file;
if(argc < 2){
portNum = atoi(argv[2]);
}
else{
portNum = 80;
}
get_domain(argv[1], &domain, &destination, &file);
printf("%s\n%s\n%s\n", domain, destination, file);
hostname_to_ip(domain, &serv_addr);
printf("%s resolved %s\n", domain, inet_ntoa(serv_addr.sin_addr));
printf("Connecting to server\n");
if((sockfd = socket(AF_INET, SOCK_STREAM, 0))< 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
if(connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0){
printf("ERROR cannot connect to server\n");
return 1;
}
printf("Connected\n");
printf("Disconnecting...\n");
close(sockfd);
printf("Disconnected\n");
return 0;
}
//http://www.binarytides.com/hostname-to-ip-address-c-sockets-linux/
int hostname_to_ip(char *domain, struct sockaddr_in *_addr){
struct addrinfo hint, *serv_addr, *iter;
struct sockaddr_in *h;
int rv;
memset(&hint, 0, sizeof hint);
hint.ai_family = AF_INET; //Force ipv4
hint.ai_socktype = SOCK_STREAM; //TCP
//resolving domain
if((rv = getaddrinfo(domain, "http", &hint, &serv_addr)) != 0){
//Print the error
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
//Dummy variable for testing purpose
char *ip;
ip = (char*)malloc(sizeof(char)*100);
//Loop through all the result
for(iter = serv_addr; iter != NULL; iter->ai_next){
h = (struct sockaddr_in*)iter->ai_addr;
if(strcpy(ip,inet_ntoa(h->sin_addr)) != NULL){
//Stop the loop when the connection is successful
*_addr = *h;
break;
}
}
freeaddrinfo(serv_addr);
free(ip);
return 0;
}
//Separate the domain and file from the url
void get_domain(char *address, char **domain, char **destination, char **file){
char *dom, *dest, *fl;
char *temp;
dom = strtok_r(address, "/", &dest);
if(strcmp(dest,"") == 0){
dest = (char*)malloc(sizeof(char)*2);
strcpy(dest, "/");
}
fl = (char*)malloc(sizeof(dest));
temp = dest;
while(strcmp(temp, "") != 0){
strcpy(fl, temp);
fl = strtok_r(fl, "/", &temp);
}
if(fl == NULL){
fl = (char*)malloc(sizeof(char)*4);
strcpy(fl, "any");
}
*domain = dom;
*destination = dest;
*file = fl;
}
|
C
|
/** @file */
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <stdbool.h>
#include "functions.h"
Table* AddTable(Table** pHead, int number)
{
bool exists = false; //istnienie stolika
Table* p;
//dodawanie na poczatek
if (*pHead == NULL || (*pHead)->number >= number)
{
//jezeli dany stolik ju istnieje
if ((*pHead) != NULL && (*pHead)->number == number)
{
exists = true;
}
//jezeli dany stolik jeszcze nie istnieje
if (!exists)
{
//stworz nowy stolik
Table* NewTable = (Table*)malloc(sizeof(Table));
NewTable->number = number;
NewTable->pHeadClient = NULL;
NewTable->pNextTable = (*pHead);
(*pHead) = NewTable;
}
return (*pHead);
}
//jezeli numer stolika jest wiekszy
else
{
p = *pHead;
while (p->pNextTable != NULL && p->pNextTable->number < number)
{
p = p->pNextTable;
}
if (p->pNextTable != NULL && p->pNextTable->number == number)
{
exists = true;
}
if (!exists)
{
Table* NewTable = (Table*)malloc(sizeof(Table));
NewTable->number = number;
NewTable->pHeadClient = NULL;
NewTable->pNextTable = p->pNextTable;
p->pNextTable = NewTable;
}
return p->pNextTable;
}
}
void AddClient(Client** pHead, const char* surname, int hour, int number, int discount)
{
bool exists = false;
Client* p;
//dodawanie na pocztek
if (*pHead == NULL || (*pHead)->hour >= hour)
{
//jezeli stolik na dana godzine juz jest zajety
if ((*pHead) != NULL && (*pHead)->hour == hour)
{
exists = true;
printf("Ju mamy rezerwacj na t godzin\n");
}
//jezeli stolik na dana godzine jest wolny
if (!exists)
{
//stworz nowa rezerwacje
Client* NewClient = (Client*)malloc(sizeof(Client));
NewClient->surname = malloc(strlen(surname) + 1);
strcpy(NewClient->surname, surname);
NewClient->hour = hour;
NewClient->number = number;
NewClient->discount = discount;
NewClient->pNextClient = (*pHead);
(*pHead) = NewClient;
}
}
//jezeli godzina jest pozniejsza
else
{
p = *pHead;
while (p->pNextClient != NULL && p->pNextClient->hour < hour)
{
p = p->pNextClient;
}
if (p->pNextClient != NULL && p->pNextClient->hour == hour)
{
exists = true;
printf("Ju mamy rezerwacj na t godzin\n");
}
if (!exists)
{
//stworz now rezerwacj
Client* NewClient = (Client*)malloc(sizeof(Client));
NewClient->surname = malloc(strlen(surname) + 1);
strcpy(NewClient->surname, surname);
NewClient->hour = hour;
NewClient->number = number;
NewClient->discount = discount;
NewClient->pNextClient = p->pNextClient;
p->pNextClient = NewClient;
}
}
}
void ShowClient(Client* pHead)
{
while (pHead)
{
printf("Surname: %s \n",pHead->surname);
printf("Hour: %d \n", pHead->hour);
printf("Discount: %d%%\n", pHead->discount);
printf("Number of people: %d \n\n", pHead->number);
pHead = pHead->pNextClient;
}
}
void ShowTable(Table* pHead)
{
while (pHead)
{
printf("Table number: %d\n\n", pHead->number);
ShowClient(pHead->pHeadClient);
pHead = pHead->pNextTable;
}
}
Table* CheckNumber(Table* pHead, int number)
{
if (pHead)
{
//dodawanie do najmniejszego mozliwego stolika
while (pHead->pNextTable != NULL && pHead->number < number)
{
pHead = pHead->pNextTable;
}
if (pHead->number >= number)
{
//zwracam wskaznik zeby dodac pozniej klienta do wlasnie tego stolika
return pHead;
}
}
return NULL;
}
int CheckHour(Client* pHead, int hour)
{
int decision;
//godziny pracy restauracji
if (hour < 6 || hour > 22)
{
decision = 0; //0 to brak miejsca, 1 jest miejsce
return decision;
}
else
{
while (pHead->pNextClient != NULL && pHead->hour != hour)
{
pHead = pHead->pNextClient;
decision = 1;
}
if (pHead->hour == hour)
{
decision = 0;
}
return decision;
}
}
int ExtractNumber(char* nazwa)
{
char numer = *(nazwa + 5);
int num = numer - '0';
return num;
}
void Upload(Table** pHead, char* files[], int num)
{
for (int i = 0; i < num; i++)
{
//otwarcie pliku w trybie do odczytu
FILE* plik_r = fopen(files[i], "r");
if (plik_r)
{
//numer stolika odzyskany z nazwy pliku
int number = ExtractNumber(files[i]);
char surname[10];
int hour;
int people;
int discount;
//wczytywanie kolejnych wartoci
while (fscanf(plik_r, "%s %d %d %d", surname, &hour, &people, &discount) != EOF)
{
Table* temp = AddTable(pHead, number);
AddClient(&(temp->pHeadClient), surname, hour, people, discount);
}
fclose(plik_r);
}
}
}
void Check(Table* pHead)
{
printf("Na ile osob: ");
int number;
scanf("%d", &number);
//Sprawdzenie czy jest stolik na tyle osb
Table* temp = CheckNumber(pHead, number);
//Jezeli jest
if (temp != NULL)
{
printf("Na ktora godzine: ");
int hour;
scanf("%d", &hour);
//Sprawdzenie czy jest wolna godzina
int x = CheckHour(temp->pHeadClient, hour);
if (x == 1)
{
printf("Na jakie nazwisko: ");
char surname[10];
scanf("%s",surname);
printf("Jaka znizke naliczyc: ");
int discount;
scanf("%d", &discount);
AddClient(&(temp->pHeadClient),surname,hour,number,discount);
}
else
{
printf("%s", "Nie mozna zarezerwowac na ta godzine\n\n");
}
}
//Nie ma takiego stolika
else
{
printf("%s", "Nie mozna zarezerwowac na tyle osob\n\n");
}
}
void SaveToFile(Table* pHead, char* files[], int num)
{
for (int i = 0; i < num; i++)
{
//otwarcie pliku w trybie do zapisu
FILE* plik_w = fopen(files[i], "w");
if (plik_w)
{
if (pHead)
{
while (pHead->pNextTable != NULL && pHead->number != ExtractNumber(files[i]))
{
pHead = pHead->pNextTable;
}
Client* p = pHead->pHeadClient;
while (p)
{
fprintf(plik_w, "%s %d %d %d\n", p->surname, p->hour, p->number, p->discount);
p = p->pNextClient;
}
}
fclose(plik_w);
}
else
{
printf("Bad odczytania pliku!\n");
}
}
}
void DeleteClient(Client** pHead)
{
Client* tmp = NULL;
while (*pHead)
{
tmp = (*pHead)->pNextClient;
free((*pHead)->surname);
free(*pHead);
*pHead = tmp;
}
}
void DeleteTable(Table** pHead)
{
Table* tmp = NULL;
while (*pHead)
{
tmp = (*pHead)->pNextTable;
DeleteClient(&((*pHead)->pHeadClient));
free(*pHead);
*pHead = tmp;
}
}
|
C
|
/*
Trabalho 1 Parte 2
Gabriel Carvalho Silva
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(0)); /*Generates the seed for the random number*/
int secretNumber = rand() % 101; /*Secret Number Declaration and Generation*/
int usrGuess, usrAttempts = 1; /*a variable to store each guess the user makes and another for how many guesses the user makes*/
/*Welcome message*/
printf("A secret number between 0 and 100 was selected.\nTo win this game, find out which number it is!\n");
/*The program loop. It only stops when the user manages to guess the secret number*/
do
{
/*reads the user guess*/
printf("Your guess: ");
scanf("%d", &usrGuess);
if(usrGuess != secretNumber){
/*if the user miss the right number, the next attempt will be counted*/
usrAttempts++;
/*Then, a hint stating whether the secret number is smaller or greater than the guessed number will appear*/
if(usrGuess > secretNumber){
printf("The secret number is smaller than the one you guessed!Try again\n");
} else{
printf("The secret number is greater than the one you guessed!Try again\n");
}
}
} while (usrGuess != secretNumber);
printf("\nCongratulations, you guessed it right!\nNumber of attempts: %d\n\n", usrAttempts);
return 0;
}
|
C
|
/* Creating of Test Data Version 0.1 from 12.11.01 12:15 Uhr */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "kbs_RandomStringFile.h"
#include "kbs_RandomString.h"
#include "randomlib.h"
#include "kbs_Types.h"
#include "kbs_Error.h"
/*--------------------------------------------------------------------------*/
void kbs_make_RandomStringFile(Kbs_Char *testdatafile) {
filesize = 0;
file_ptr = fopen(testdatafile, "wb+");
if (file_ptr == NULL) {
printf("kbs_make_RandomSeqFile - %s failed\n", testdatafile);
exit(EXIT_FAILURE);
}
}
/*--------------------------------------------------------------------------*/
void kbs_open_RandomStringFile(Kbs_Char *testdatafile) {
file_ptr = fopen(testdatafile, "rb");
if (file_ptr == NULL) {
printf("kbs_open_RandomSeqFile - %s failed\n", testdatafile);
exit(EXIT_FAILURE);
}
}
/*--------------------------------------------------------------------------*/
void kbs_close_RandomStringFile(void){
fclose(file_ptr);
}
/*--------------------------------------------------------------------------*/
void kbs_generate_RandomUStringFile(Kbs_Uint alphabetSize, Kbs_Char *filename, Kbs_Ulong seqSize) {
Kbs_Ulong i;
Kbs_Uchar *seq;
kbs_make_RandomStringFile(filename);
seq = (Kbs_Uchar *) malloc(seqSize * sizeof(Kbs_Uchar));
kbsRandomize();
for (i=0; i<seqSize; i++) {
seq[i] = kbs_genRand_UChar(alphabetSize);
}
fwrite(seq, sizeof(Kbs_Uchar), seqSize, file_ptr);
kbs_close_RandomStringFile();
printf("Random file %s generated\n", filename);
}
/*--------------------------------------------------------------------------*/
Kbs_Char *kbs_generate_RandomStringFileName(Kbs_Uint alphabetSize, Kbs_Ulong fileSize) {
Kbs_Char *filename;
filename = (Kbs_Char *) malloc(sizeof(Kbs_Char) * 100);
memset(filename, '\0', 100);
sprintf(filename,"rand_a%d_s%lu", alphabetSize, fileSize);
return filename;
}
/*--------------------------------------------------------------------------*/
Kbs_Char *kbs_generate_PeriodicStrFileName(const Kbs_Uint alphaSize, const Kbs_Ulong periodLen, const Kbs_Ulong strLen) {
Kbs_Char *filename;
filename = (Kbs_Char *) malloc(sizeof(Kbs_Char) * 120);
memset(filename, '\0', 100);
Kbs_Int offset = sprintf(filename,"periodic_a%u", (unsigned int )alphaSize);
offset += sprintf(filename+offset,"_p%lu", (unsigned long )periodLen);
offset += sprintf(filename+offset,"_s%lu", (unsigned long )strLen);
return filename;
}
/*--------------------------------------------------------------------------*/
void kbs_generate_NURandomFiles(Kbs_Uint n, Kbs_Ulong atomarSize, Kbs_Uint alphabetSize){
Kbs_Uint i;
Kbs_Char *filename;
for (i=1; i<=n; i++) {
filename = kbs_generate_RandomStringFileName(alphabetSize, i*atomarSize);
kbs_generate_RandomUStringFile(alphabetSize, filename, i*atomarSize);
free(filename);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
float r,h,g,A,V;
const float Pi=3.1416;
printf("Ingresar el radio y la altura \n");
scanf("%f,",&r);
scanf("%f,",&h);
g=sqrt(r*r+h*h);
A=(2*Pi*r*(g/2))+(Pi*r*r);
V=(Pi*r*r*h)/3;
printf("Area total %.2f y Volumen total %.2f",A,V);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.