language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* * Copyright (C) 2016 Thomas Costigliola */ #include <stdlib.h> #include <stdbool.h> #include "threadpool.h" struct threadpool * threadpool_new(int thread_count, int queue_size) { if(thread_count < 1 || queue_size < 1 || queue_size < thread_count) { /* Do not allow empty pools and queues smaller than the number of threads */ return NULL; } struct threadpool *p = (struct threadpool *)calloc(1, sizeof(struct threadpool)); p->thread_count = thread_count; p->queue_size = queue_size; p->queue_count = 0; sem_init(&p->queuesem, 0, p->queue_size); sem_init(&p->joinsem, 0, 1); pthread_mutex_init(&p->jobsmtx, NULL); pthread_mutex_init(&p->wkrsmtx, NULL); // create the first worker thread node p->wn = (struct threadpool_worker_node *)calloc(1, sizeof(struct threadpool_worker_node)); p->wn->pool = p; p->wn->next = p->wn; p->wn->workerid = 0; sem_init(&p->wn->sem, 0, 0); pthread_create(&p->wn->thread, NULL, threadpool_worker, (void *)p->wn); // create additional worker thread nodes struct threadpool_worker_node *w; for(int i = 1; i < thread_count; i++) { w = (struct threadpool_worker_node *)calloc(1, sizeof(struct threadpool_worker_node)); w->pool = p; w->next = p->wn->next; w->workerid = i; p->wn->next = w; sem_init(&w->sem, 0, 0); pthread_create(&w->thread, NULL, threadpool_worker, (void *)w); } // create first job node p->jt = p->jn = (struct threadpool_job_node *)calloc(1, sizeof(struct threadpool_job_node)); p->jt->func = NULL; p->jt->arg = NULL; p->jt->next = NULL; // create additional job nodes struct threadpool_job_node *j; for(int i = 1; i < queue_size; i++) { j = (struct threadpool_job_node *)calloc(1, sizeof(struct threadpool_job_node)); j->func = NULL; j->arg = NULL; j->next = p->jt->next; p->jt->next = j; } return p; } void threadpool_delete(struct threadpool *p) { struct threadpool_job_node *j; struct threadpool_worker_node *w; // post a null job for each worker for(int i = 0; i < p->thread_count; i++) { threadpool_queue_wait(p, NULL, NULL); } // wait for all workers to terminate for(int i = 0; i < p->thread_count; i++) { pthread_join(p->wn->thread, NULL); p->wn = p->wn->next; } // free the job nodes j = p->jt; for(int i = 0; i < p->queue_size; i++) { j = j->next; free(p->jt); p->jt = j; } // free the worker thread nodes w = p->wn; for(int i = 0; i < p->thread_count; i++) { w = w->next; sem_destroy(&p->wn->sem); free(p->wn); p->wn = w; } sem_destroy(&p->queuesem); sem_destroy(&p->joinsem); free(p); } void * threadpool_worker(void *node) { struct threadpool_worker_node *n = (struct threadpool_worker_node *)node; struct threadpool *p = n->pool; struct threadpool_job_node *j; bool alive = true; workfunc func; void *arg; while(alive) { /* This semaphore starts at 0, the queuing function will post on it to activate this worker thread allowing the thread to advance and decrementing the semaphore back to 0. When its job is finished it waits again on the null semaphore unless it has already been queued again. */ sem_wait(&n->sem); /* Lock the job queue and select the next job */ pthread_mutex_lock(&p->jobsmtx); func = p->jt->func; arg = p->jt->arg; j = p->jt->next; p->jt->next = p->jn->next; p->jn->next = p->jt; p->jt = j; pthread_mutex_unlock(&p->jobsmtx); sem_post(&p->queuesem); if(func == NULL) { alive = false; } else { func(arg, n->workerid); } pthread_mutex_lock(&p->jobsmtx); p->queue_count--; if(p->queue_count == 0) { /* Wakeup a waiting join operation */ sem_post(&p->joinsem); } pthread_mutex_unlock(&p->jobsmtx); } return NULL; } /* Add a job to work queue and return: 0 on success, -1 if the queue is full */ int threadpool_queue(struct threadpool *p, workfunc func, void *arg) { /* Wait for the job queue to be writeable */ pthread_mutex_lock(&p->jobsmtx); if(p->jn == NULL) { // the jobe queue is full pthread_mutex_unlock(&p->jobsmtx); return -1; } /* We know this won't block since we verified there are slots in the queue */ sem_wait(&p->queuesem); if(p->queue_count == 0) { /* The queue was empty, make sure joins block now until it becomes empty again */ sem_wait(&p->joinsem); } p->queue_count++; p->jn->func = func; p->jn->arg = arg; p->jn = p->jn->next; pthread_mutex_unlock(&p->jobsmtx); pthread_mutex_lock(&p->wkrsmtx); sem_post(&p->wn->sem); p->wn = p->wn->next; pthread_mutex_unlock(&p->wkrsmtx); return 0; } int threadpool_queue_wait(struct threadpool *p, workfunc func, void *arg) { /* Wait on a free queue slot before continuing */ sem_wait(&p->queuesem); /* Wait for the job queue to be writeable */ pthread_mutex_lock(&p->jobsmtx); if(p->queue_count == 0) { /* The queue was empty, make sure joins block now until it becomes empty again */ sem_wait(&p->joinsem); } p->queue_count++; p->jn->func = func; p->jn->arg = arg; p->jn = p->jn->next; pthread_mutex_unlock(&p->jobsmtx); pthread_mutex_lock(&p->wkrsmtx); sem_post(&p->wn->sem); p->wn = p->wn->next; pthread_mutex_unlock(&p->wkrsmtx); return 0; } int threadpool_join(struct threadpool *p) { sem_wait(&p->joinsem); sem_post(&p->joinsem); return 0; } int threadpool_clear_queue(struct threadpool *p) { }
C
#include<string.h> #include<stdio.h> int main() { char ch[100]; int l,i,n=0; while(gets(ch)){ l=strlen(ch); for(i=0;i<l;i++){ if(ch[i]=='"'){ if(n%2==0) printf("``"); else printf("''"); n++; } else printf("%c",ch[i]); } printf("\n"); } return 0; }
C
/* ** EPITECH PROJECT, 2020 ** my_strincl ** File description: ** my_strincl */ #include <stdbool.h> #include <string.h> bool my_strincl(char const *str, char const *part) { size_t i = 0; int len = strlen(str); if (len < strlen(part)) return false; for (; str[i] && str[i] != part[0]; i++); if (i == len) return false; for (size_t j = 0; str[i] && part[j]; i++, j++) if (str[i] != part[j]) return false; return true; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> int main() { int shm_fd; char *start="ds"; char isPalin[20]; char *ptr; int SIZE=1024; shm_fd = shm_open(start,O_RDWR,0666); ptr = mmap(0,SIZE,PROT_READ,MAP_SHARED,shm_fd,0); strcpy(isPalin,ptr); printf("%s", isPalin); int len=strlen(ptr); int i=0; while(i < len/2) { isPalin[i]=isPalin[len-i-1]; i++; } if(strcmp(isPalin,ptr)==0) printf("\nIS PALINDROME!!\n"); else printf("\nNO!!!\n"); shm_unlink(start); }
C
/* * Tri_Tri_Intersection.h * newshell_prj * * Created by Norbert Stoop on 11.05.09. * Copyright 2009 __MyCompanyName__. All rights reserved. * */ #include "Tri_Tri_Intersection.h" /* Triangle/triangle intersection test routine, * by Tomas Moller, 1997. * See article "A Fast Triangle-Triangle Intersection Test", * Journal of Graphics Tools, 2(2), 1997 * updated: 2001-06-20 (added line of intersection) * * int tri_tri_intersect(float V0[3],float V1[3],float V2[3], * float U0[3],float U1[3],float U2[3]) * * parameters: vertices of triangle 1: V0,V1,V2 * vertices of triangle 2: U0,U1,U2 * result : returns 1 if the triangles intersect, otherwise 0 * * Here is a version withouts divisions (a little faster) * int NoDivTriTriIsect(float V0[3],float V1[3],float V2[3], * float U0[3],float U1[3],float U2[3]); * * This version computes the line of intersection as well (if they are not coplanar): * int tri_tri_intersect_with_isectline(float V0[3],float V1[3],float V2[3], * float U0[3],float U1[3],float U2[3],int *coplanar, * float isectpt1[3],float isectpt2[3]); * coplanar returns whether the tris are coplanar * isectpt1, isectpt2 are the endpoints of the line of intersection */ // this edge to edge test is based on Franlin Antonio's gem: // "Faster Line Segment Intersection", in Graphics Gems III, pp. 199-202 //The edge notation is as follos: /* 2 / \ / \ / \ / 2 1 \ / \ / 0 \ 0 ------------- 1 We can find out which node is at edge e1 and e2: e1+e2 can be either 2 (=> node 0), 1 (node 1) or 3 (node 2). */ int NEXT[3]={1,2,0}; int twoedges2node[3] = {1,0,2}; bool edge_edge_test(RealVectorValue const& V0, RealVectorValue const& U0, RealVectorValue const& U1, unsigned int i0, unsigned int i1, double Ax, double Ay) { real_type Bx=U0(i0)-U1(i0); real_type By=U0(i1)-U1(i1); real_type Cx=V0(i0)-U0(i0); real_type Cy=V0(i1)-U0(i1); real_type f=Ay*Bx-Ax*By; real_type d=By*Cx-Bx*Cy; if((f>0 && d>=0 && d<=f) || (f<0 && d<=0 && d>=f)) { real_type e=Ax*Cy-Ay*Cx; if(f>0) { if(e>=0 && e<=f) return true; } else { if(e<=0 && e>=f) return true; } } else return false; } bool edge_against_tri_edges(RealVectorValue const& V0, RealVectorValue const& V1, RealVectorValue const& U0, RealVectorValue const& U1, RealVectorValue const& U2, unsigned int i0, unsigned int i1) { real_type Ax=V1(i0)-V0(i0); real_type Ay=V1(i1)-V0(i1); // test edge U0,U1 against V0,V1 if ( edge_edge_test(V0,U0,U1,i0,i1,Ax,Ay) ) return true; // test edge U1,U2 against V0,V1 if ( edge_edge_test(V0,U1,U2,i0,i1,Ax,Ay) ) return true; // test edge U2,U1 against V0,V1 if ( edge_edge_test(V0,U2,U0,i0,i1,Ax,Ay) ) return true; return false; } bool point_in_tri(RealVectorValue const& V0, RealVectorValue const& U0, RealVectorValue const& U1, RealVectorValue const& U2, unsigned int i0, unsigned int i1) { // is T1 completly inside T2? // check if V0 is inside tri(U0,U1,U2) real_type a=U1(i1)-U0(i1); real_type b=-(U1(i0)-U0(i0)); real_type c=-a*U0(i0)-b*U0(i1); real_type d0=a*V0(i0)+b*V0(i1)+c; a=U2(i1)-U1(i1); b=-(U2(i0)-U1(i0)); c=-a*U1(i0)-b*U1(i1); real_type d1=a*V0(i0)+b*V0(i1)+c; a=U0(i1)-U2(i1); b=-(U0(i0)-U2(i0)); c=-a*U2(i0)-b*U2(i1); real_type d2=a*V0(i0)+b*V0(i1)+c; if(d0*d1>0.0) { if(d0*d2>0.0) return true; } return false; } bool coplanar_tri_tri(RealVectorValue const& N, RealVectorValue const& V0, RealVectorValue const& V1, RealVectorValue const& V2, RealVectorValue const& U0, RealVectorValue const& U1, RealVectorValue const& U2) { unsigned int i0,i1; // first project onto an axis-aligned plane, that maximizes the area // of the triangles, compute indices: i0,i1. real_type A0=std::fabs(N(0)); real_type A1=std::fabs(N(1)); real_type A2=std::fabs(N(2)); if(A0>A1) { if(A0>A2) { i0=1; // A[0] is greatest i1=2; } else { i0=0; // A[2] is greatest i1=1; } } else // A[0]<=A[1] { if(A2>A1) { i0=0; // A[2] is greatest i1=1; } else { i0=0; // A[1] is greatest i1=2; } } // test all edges of triangle 1 against the edges of triangle 2 if( edge_against_tri_edges(V0,V1,U0,U1,U2,i0,i1) ) return true; if( edge_against_tri_edges(V1,V2,U0,U1,U2,i0,i1) ) return true; if( edge_against_tri_edges(V2,V0,U0,U1,U2,i0,i1) ) return true; // finally, test if tri1 is totally contained in tri2 or vice versa if( point_in_tri(V0,U0,U1,U2,i0,i1) ) return true; if( point_in_tri(U0,V0,V1,V2,i0,i1) ) return true; return false; } void isect2(RealVectorValue const& VTX0, RealVectorValue const& VTX1, RealVectorValue const& VTX2, real_type VV0, real_type VV1, real_type VV2, real_type D0, real_type D1, real_type D2, real_type & isect0, real_type & isect1) { real_type tmp; // RealVectorValue diff; tmp=D0/(D0-D1); isect0 = VV0+(VV1-VV0)*tmp; // diff = VTX1-VTX2; // diff *= tmp; // isectpoint0 = diff+VTX0; tmp=D0/(D0-D2); isect1 = VV0+(VV2-VV0)*tmp; // diff = VTX2-VTX0; // diff *= tmp; // isectpoint1 = VTX0 + diff; } bool compute_intervals_isectline(RealVectorValue const& VERT0, RealVectorValue const& VERT1, RealVectorValue const& VERT2, real_type VV0, real_type VV1, real_type VV2, real_type D0, real_type D1, real_type D2, real_type D0D1, real_type D0D2, real_type & isect0, real_type & isect1, int& edge0, int& edge1) { if(D0D1>0.0f) { // here we know that D0D2<=0.0 // that is D0, D1 are on the same side, D2 on the other or on the plane isect2(VERT2,VERT0,VERT1,VV2,VV0,VV1,D2,D0,D1,isect0,isect1); edge0 = 2; edge1 = 1; } else if(D0D2>0.0f) { // here we know that d0d1<=0.0 isect2(VERT1,VERT0,VERT2,VV1,VV0,VV2,D1,D0,D2,isect0,isect1); edge0 = 0; edge1 = 1; } else if(D1*D2>0.0f || D0!=0.0f) { // here we know that d0d1<=0.0 or that D0!=0.0 isect2(VERT0,VERT1,VERT2,VV0,VV1,VV2,D0,D1,D2,isect0,isect1); edge0 = 0; edge1 = 2; } else if(D1!=0.0f) { isect2(VERT1,VERT0,VERT2,VV1,VV0,VV2,D1,D0,D2,isect0,isect1); edge0 = 0; edge1 = 1; } else if(D2!=0.0f) { isect2(VERT2,VERT0,VERT1,VV2,VV0,VV1,D2,D0,D1,isect0,isect1); edge0 = 2; edge1 = 1; } else { // triangles are coplanar return true; } return false; } void line_line_cpp(RealVectorValue const & V0, RealVectorValue const & V1, RealVectorValue const & U0, RealVectorValue const & U1, RealVectorValue& cpt, double& s1, double &s2) { RealVectorValue u = V1-V0; RealVectorValue v = U1 - U0; RealVectorValue w = V0 - U0; double a = u*u; // always >= 0 double b = u*v; double c = v*v; // always >= 0 double d = u*w; double e = v*w; double D = a*c - b*b; // always >= 0 double sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0 double tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0 // compute the line parameters of the two closest points if (D < EPSILON) { // the lines are almost parallel sN = 0.0; // force using point P0 on segment S1 sD = 1.0; // to prevent possible division by 0.0 later tN = e; tD = c; } else { // get the closest points on the infinite lines sN = (b*e - c*d); tN = (a*e - b*d); if (sN < 0.0) { // sc < 0 => the s=0 edge is visible sN = 0.0; tN = e; tD = c; } else if (sN > sD) { // sc > 1 => the s=1 edge is visible sN = sD; tN = e + b; tD = c; } } if (tN < 0.0) { // tc < 0 => the t=0 edge is visible tN = 0.0; // recompute sc for this edge if (-d < 0.0) sN = 0.0; else if (-d > a) sN = sD; else { sN = -d; sD = a; } } else if (tN > tD) { // tc > 1 => the t=1 edge is visible tN = tD; // recompute sc for this edge if ((-d + b) < 0.0) sN = 0; else if ((-d + b) > a) sN = sD; else { sN = (-d + b); sD = a; } } // finally do the division to get sc and tc sc = (fabs(sN) < EPSILON ? 0.0 : sN / sD); tc = (fabs(tN) < EPSILON ? 0.0 : tN / tD); // get the difference of the two closest points cpt = w + (sc * u) - (tc * v); // = S1(sc) - S2(tc) s1 = sc; s2 = tc; //s1t=sc; //s2t=tc; } bool triangle_triangle_interval_overlap( RealVectorValue const & V0, RealVectorValue const & V1, RealVectorValue const & V2 , RealVectorValue const & U0, RealVectorValue const & U1, RealVectorValue const & U2 , bool & coplanar, RealVectorValue & cpt, int& iedge1, int& iedge2, int& inode1, int& inode2 , bool epsilon_test) { // compute plane equation of triangle(V0,V1,V2) RealVectorValue E1 = V1-V0; RealVectorValue E2 = V2-V0; RealVectorValue N1 = E1.cross(E2); real_type d1 = -N1*V0; // plane equation 1: N1.X+d1=0 // put U0,U1,U2 into plane equation 1 to compute signed distances to the plane real_type du0 = N1*U0+d1; real_type du1 = N1*U1+d1; real_type du2 = N1*U2+d1; // coplanarity robustness check if (epsilon_test) { if( std::fabs(du0) < EPSILON ) du0=0.0; if( std::fabs(du1) < EPSILON ) du1=0.0; if( std::fabs(du2) < EPSILON ) du2=0.0; } real_type du0du1=du0*du1; real_type du0du2=du0*du2; if(du0du1>0.0f && du0du2>0.0f) // same sign on all of them + not equal 0 ? return false; // no intersection occurs // compute plane of triangle (U0,U1,U2) E1 = U1-U0; E2 = U2,U0; RealVectorValue N2 = E1.cross(E2); real_type d2 = -N2*U0; // plane equation 2: N2.X+d2=0 // put V0,V1,V2 into plane equation 2 real_type dv0 = N2*V0+d2; real_type dv1 = N2*V1+d2; real_type dv2 = N2*V2+d2; // coplanarity robustness check if (epsilon_test) { if( std::fabs(dv0) < EPSILON ) dv0=0.0; if( std::fabs(dv1) < EPSILON ) dv1=0.0; if( std::fabs(dv2) < EPSILON ) dv2=0.0; } real_type dv0dv1 = dv0*dv1; real_type dv0dv2 = dv0*dv2; if(dv0dv1>0.0f && dv0dv2>0.0f) // same sign on all of them + not equal 0 ? return false; // no intersection occurs // compute direction of intersection line RealVectorValue D = N1.cross(N2); // compute and index to the largest component of D real_type max=std::fabs(D(0)); unsigned int index=0; real_type b=std::fabs(D(1)); real_type c=std::fabs(D(2)); if(b>max) max=b,index=1; if(c>max) max=c,index=2; // this is the simplified projection onto L real_type vp0 = V0(index); real_type vp1 = V1(index); real_type vp2 = V2(index); real_type up0 = U0(index); real_type up1 = U1(index); real_type up2 = U2(index); real_type isect1[2], isect2[2]; // RealVectorValue isectpointA1, isectpointA2; // compute interval for triangle 1 int edge1[2]; //Gives us the two edges which could be intersecting for triangle 1 int edge2[2]; //Same for triangle 2 coplanar=compute_intervals_isectline(V0,V1,V2,vp0,vp1,vp2,dv0,dv1,dv2, dv0dv1,dv0dv2,isect1[0],isect1[1],edge1[0],edge1[1]); if(coplanar) return coplanar_tri_tri(N1,V0,V1,V2,U0,U1,U2); //RealVectorValue isectpointB1, isectpointB2; // compute interval for triangle 2 compute_intervals_isectline(U0,U1,U2,up0,up1,up2,du0,du1,du2, du0du1,du0du2,isect2[0],isect2[1],edge2[0],edge2[1]); // sort so that a<=b unsigned int smallest1 = 0; if (isect1[0] > isect1[1]) { std::swap(isect1[0], isect1[1]); smallest1=1; } unsigned int smallest2 = 0; if (isect2[0] > isect2[1]) { std::swap(isect2[0], isect2[1]); smallest2=1; } if(isect1[1]<isect2[0] || isect2[1]<isect1[0]) return false; // at this point, we know that the triangles intersect const RealVectorValue* nodes1[3]; nodes1[0] = &V0; nodes1[1] = &V1; nodes1[2] = &V2; const RealVectorValue* nodes2[3]; nodes2[0] = &U0; nodes2[1] = &U1; nodes2[2] = &U2; //This array tells us which node is shared by two edges. We use the above notation for edge numbering inode1=-1; //Flag that tells us if it is a node-face or edge-edge intersection inode2=-1; if(isect2[0]<isect1[0]) { //isectpt1 = smallest1==0 ? isectpointA1 : isectpointA2; iedge1 = smallest1==0 ? edge1[0] : edge1[1]; if(isect2[1]<isect1[1]) { // isectpt2 = smallest2==0 ? isectpointB2 : isectpointB1; iedge2 = smallest2==0 ? edge2[0] : edge2[1]; //Now lets find the closest point projection from iedge1 on iedge2 double s1,s2; line_line_cpp(*nodes1[iedge1], *nodes1[NEXT[iedge1]], *nodes2[iedge2], *nodes2[NEXT[iedge2]], cpt,s1,s2); } else { // isectpt2 = smallest1==0 ? isectpointA2 : isectpointA1; //This means that both intersection points are from triangle 1. Ie. a node from triangle 1 is penetrating the //face of triangle 2. Let's find out which node it is: inode1 = twoedges2node[edge1[0]+edge1[1]-1]; //Find the closest point project. cpt is the point on triangle 2 closest to the inode1 if (inode1==0) cpt = V0 - dv0*N2/N2.size(); else if (inode1==1) cpt = V1 - dv1*N2/N2.size(); else cpt = V2 - dv2*N2/N2.size(); } } else { //isectpt1 = smallest2==0 ? isectpointB1 : isectpointB2; iedge2 = smallest2==0 ? edge2[0] : edge2[1]; if(isect2[1]>isect1[1]) { // isectpt2 = smallest1==0 ? isectpointA2 : isectpointA1; iedge1 = smallest1==0 ? edge1[0] : edge1[1]; //Find the closest point projection between the two edges: double s1,s2; line_line_cpp(*nodes1[iedge1], *nodes1[NEXT[iedge1]], *nodes2[iedge2], *nodes2[NEXT[iedge2]], cpt,s1,s2); } else { // isectpt2 = smallest2==0 ? isectpointB2 : isectpointB1; //This means a node from triangle 2 is penetrating the //face of triangle 1. Let's find out which node it is: inode2 = twoedges2node[edge2[0]+edge2[1]-1]; //Find the closest point project. cpt is the point on triangle 1 closest to the inode2 if (inode2==0) cpt = U0 - du0*N1/N1.size(); else if (inode1==1) cpt = U1 - du1*N1/N1.size(); else cpt = U2 - du2*N1/N1.size(); } } return true; } void cpt_point_triangle(RealVectorValue& P, RealVectorValue const & V0, RealVectorValue const & V1, RealVectorValue const & V2, RealVectorValue& CPT, double& v, double &w) { RealVectorValue ab = V1-V0; RealVectorValue ac = V2-V0; RealVectorValue ap = P-V0; double d1 = ab*ap; double d2 = ac*ap; if (d1<= 0.0f && d2 <= 0.0f) { v=0; w=0; CPT = V0; return; } RealVectorValue bp = P-V1; double d3 = ab*bp; double d4 = ac*bp; if (d3 >= 0.0f && d4 <= d3) { v=1; w=0; CPT = V1; return; } double vc = d1*d4 - d3*d2; if (vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f) { v = d1 / (d1-d3); w = 0; CPT = V0+v*ab; return; } RealVectorValue cp = P - V2; double d5 = ab*cp; double d6 = ac*cp; if (d6 >= 0.0f && d5 <= d6) { v=0; w=1; CPT = V2; return; } double vb = d5*d2 - d1*d6; if (vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f) { w = d2/(d2-d6); v=0.; CPT = V0 + w*ac; return; } double va = d3*d6 - d5*d4; if (va <= 0.0f && (d4-d3) >= 0.0f && (d5 - d6) >= 0.0f) { w = (d4 - d3)/((d4-d3) + (d5-d6)); v = 1.-w; CPT = V1 + w*(V2-V1); return; } double denom = 1.0 / (va + vb + vc); v = vb*denom; w = vc*denom; CPT = V0 + ab*v + ac*w; return; }
C
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <string.h> /* * simple program implementing cat */ int main(int argc, char **argv) { pid_t my_id; char buffer[4096]; my_id = getpid(); fprintf(stderr,"pid: %d -- I am my-cat and I have started\n",my_id); memset(buffer,0,sizeof(buffer)); while(read(0,buffer,sizeof(buffer)) > 0) { fprintf(stderr,"pid: %d read some data\n",getpid()); buffer[4095] = 0; /* safety first */ write(1,buffer,strlen(buffer)); fprintf(stderr,"pid: %d wrote some data\n",getpid()); memset(buffer,0,sizeof(buffer)); } fprintf(stderr,"pid: %d -- I am my-cat and I am exiting\n",my_id); exit(0); }
C
#include <stdio.h> int A(int Id, int find[]){ for(int i=0; find[i] != 0; i++){ if(Id == find[i]){ return i; } } return -1; } double payment(int itemID[], double price[], int orderItemID[],int orderQuantity[], int onSaleItemID[]){ double total = 0.0; for(int i=0; orderItemID[i] != 0; i++){ int check = A(orderItemID[i], itemID); if(check >= 0){ double profit = orderQuantity[i]*price[check]; if( A(orderItemID[i], onSaleItemID) >= 0){ profit *= 0.8; } total += profit; } } if (total < 490.0) total += 80; return total; }
C
//program to check armstrong number of n digits #include<stdio.h> #include<conio.h> #include<math.h> void main() { int number,originalnumber,remainder,result=0,n=0; printf("enter an integer: "); scanf("%d",&number); originalnumber=number; while(originalnumber!=0) { originalnumber/=10; ++n; } originalnumber=number; while(originalnumber!=0) { remainder=originalnumber%10; result+=pow(remainder,n); originalnumber/=10; } if(result==number) printf("%d is an armstrong number.",number); else printf("%d is not an armstrong number.",number); getch(); }
C
#include "rog.h" #include "mainMenu.h" void generateFirstLevel(gameSet* game) { game->levels[game->currentLevel] = createLevel(1); game->currentLevel++; } void generateNextLevel(gameSet* game) { game->levels[game->currentLevel] = createLevel(game->currentLevel+1); copyPlayerStats(game->levels[game->currentLevel-1]->user, game->levels[game->currentLevel]->user); game->currentLevel++; } //Draws the entire game, character and monsters as well as the HUD void render(gameSet * game) { printFrame(); printGameHud(game->levels[game->currentLevel - 1]); drawLevel(game->levels[game->currentLevel - 1]); } int gameLoop(gameSet* game) { //Variables int ch = '\0'; Level* level; Coords newPosition; Player* temp; //printFrame(); if(game->currentLevel==0) generateFirstLevel(game); level = game->levels[game->currentLevel-1]; //Main game loop, every pass is based on the keyboard input at the end of last and counts as a full turn while(ch != 'q'){ //Cheat key to go down one floor if(ch == 'f'){ //Have reached the bottom, untold riches await! if(game->currentLevel==game->maxLevel){ clear(); mvprintw(1,1,"You have cleared the game!"); getch(); return -1; } //Else, generate a new level generateNextLevel(game); level = game->levels[game->currentLevel-1]; } //Handle all the logic and update the game newPosition = handleInput(ch, level->user); checkPosition(newPosition, level); moveMonsters(level); //Draw the entire game render(game); //Return if player has died this turn if(level->user->hp <= 0){ clear(); mvprintw(1,1,"You have died, press any button to return to main menu"); getch(); return -1; } //Get new input from player ch = getch(); refresh(); } }
C
#include<stdio.h> main(){ double resp, receive, value[7]; int i; scanf("%lf",&resp); receive = resp; for(i = 0;i<7;i++){ value[i] = 0; } while(receive>99){value[6] = value[6] + 1;receive = receive - 100;} while(receive>49){value[5] = value[5] + 1;receive = receive - 50;} while(receive>19){value[4] = value[4] + 1;receive = receive - 20;} while(receive>9 ){value[3] = value[3] + 1;receive = receive - 10;} while(receive>4 ){value[2] = value[2] + 1;receive = receive - 5;} while(receive>1.99 ){value[1] = value[1] + 1;receive = receive - 2;} while(receive>0.99 ){value[0] = value[0] + 1;receive = receive - 1;} printf("%.0lf\n",resp); printf("%.0lf nota(s) de R$ 100,00\n",value[6]); printf("%.0lf nota(s) de R$ 50,00\n",value[5]); printf("%.0lf nota(s) de R$ 20,00\n",value[4]); printf("%.0lf nota(s) de R$ 10,00\n",value[3]); printf("%.0lf nota(s) de R$ 5,00\n",value[2]); printf("%.0lf nota(s) de R$ 2,00\n",value[1]); printf("%.0lf nota(s) de R$ 1,00\n",value[0]); }
C
#include<stdio.h> void main() { char a[100],b[100]; int i,c=0,d=0,k; scanf("%s",a); scanf("%s",b); for(i=0;a[i]!='\0';i++) { c++; } for(i=0;b[i]!='\0';i++) { d++; } if(c>=d) { k=d; } else if(c<d) { k=c; } for(i=0;a[i]!='\0';i++) { if(i<k) { printf("%c",a[i]); } } for(i=0;b[i]!='\0';i++) { if(i<k) { printf("%c",b[i]); } } }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int a,b,c; printf("a, b, c uzunluklarini giriniz : "); scanf("%d %d %d", &a, &b, &c); printf("\n-------------------------------------\n\n"); if(b+c>a) if(a>abs(b-c)) { if(a+c>b) if(b>abs(a-c)) { if(a+b>c) if(c>abs(a-b)) printf("Bu bir ucgendir..\n"); printf("Bu ucgen tipi : "); if(a==b) if(c!=b && c!=a) printf("Bu bir ikizkenar ucgendir.\n\n"); if(b==c) if(a!=c && a!=b) printf("Bu bir ikizkenar ucgendir.\n\n"); if(c==a) if(b!=c&&b!=a) printf("Bu bir ikizkenar ucgendir.\n\n"); if(a != b && b != c ) if (a != c) printf("Bu bir cesitkenar ucgendir.\n\n"); if(a==b&&b==c) if(c==a) printf("Bu bir eskenar ucgendir.\n\n"); } } else printf("Bu bir ucgen degildir..\n"); return 0; }
C
#include <stdio.h> int main() { for (int i = 1111; i <= 9999; i++) { if ((i / 1000) % 10 == (i / 100) % 10 && (i / 10) % 10 == i % 10) // This is to check for AA BB wala condition. { for (int j = 1; j <= i; j++) // iss loop se har j ka value ke liye j*j krke check krte hai ki kya wo i ke equal hai agar hai toh loop break kro nai toh chalne do. { if (j * j == i) { printf("%d\n", j); break; } } } } }
C
#include<string.h> #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<pthread.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> pthread_t t1,t2; char recvBuff[1024]; //read buffer char s[1024]; //write buffer int inet_pton(int,const char *,void *); void* serv_read(void *args) { void *a; int *sock_fd; sock_fd=(int *)args; while(1) { read((*sock_fd),recvBuff,100); printf("\n TEACHER : %s",recvBuff); if(strcmp(recvBuff,"_exit_\n")==0) { printf("\n BYE"); return a; } printf("\n>>>>>"); } } void* serv_write(void *args) { int *sock_fd; void *a; sock_fd=(int*)args; while(1) { printf("\t\t\t\t\t NOTE: TO EXIT type '_exit_' "); printf("\n>>>>>"); fgets(s,100,stdin); write((*sock_fd),s,100); if(strcmp(s,"_exit_\n")==0) { printf("\n BYE"); return a; } printf("STUDENT: %s",s); } pthread_join(t1,NULL); } int main(int argc,char *argv[]) { int sock_fd; struct sockaddr_in serv_addr; int conn_status; if(argc!=2 && argc<2) { printf("\n USAGE: %s <ip of server> \n",argv[0]); return 1; } else if(argc>2) { printf("INVALID NUMBER OF ARGUMENTS"); return 1; } memset(recvBuff,'0',sizeof(recvBuff)); //creating the socket if((sock_fd=socket(AF_INET,SOCK_STREAM,0))<0) { printf("\n ERROR IN CREATING THE SOCKET"); return 1; } memset(&serv_addr,'0',sizeof(serv_addr)); //creating the address of the socket serv_addr.sin_family = AF_INET; serv_addr.sin_port= htons(4300); if((inet_pton(AF_INET,argv[1],&serv_addr.sin_addr)) <= 0) { printf("\n inet_pton error occurred \n"); return 1; } //connection establishment conn_status = connect(sock_fd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)); //checking connection status if(conn_status==-1) { printf("CONNECTION FAILED"); return 1; } printf("\nCONNECTION SUCCESSFULL"); pthread_create(&t1,NULL,serv_read,(void *)(&sock_fd)); //thread for server text reading pthread_create(&t2,NULL,serv_write,(void *)(&sock_fd)); // thread for sending text to the server pthread_join(t2,NULL); //waiting for one of the threads /* while(1) { read(sock_fd,recvBuff,100); if(strcmp(recvBuff,"_exit_\n")==0) { printf("\n BYE"); return 1; } printf("\nTEACHER : %s",recvBuff); printf("\n\t\t\t\t\t NOTE: TO EXIT type '_exit_' "); printf("\n>>>>>"); fgets(s,100,stdin); write(sock_fd,s,100); if(strcmp(s,"_exit_\n")==0) { printf("\n BYE"); return 1; } printf("\nSTUDENT: %s",s); } */ /*recieving the data from the server recv(sock_fd,s,sizeof(s),0); printing the server response printf("\n THE SERVER SENT THE FOLLOWING DATA : %s ",s); */ close(sock_fd); //closing the socket return 1; }
C
#include <sys/types.h> #include <sys/stat.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <sys/sysmacros.h> #include <string.h> int main(int argc, char *argv[]){ struct stat sb; if (argc != 2) { fprintf(stderr, "Usage: %s <pathname>\n", argv[0]); exit(EXIT_FAILURE); } if (stat(argv[1], &sb) == -1) { perror("Error stat"); exit(EXIT_FAILURE); } char* hard = malloc(sizeof(char)*(strlen(argv[1]))); char* sym = malloc(sizeof(char)*(strlen(argv[1]))); strcpy(hard, argv[1]); strcpy(sym, argv[1]); hard = strcat(hard, ".hard"); sym = strcat(sym, ".sym"); if(S_ISREG(sb.st_mode)){ if(link(argv[1],hard) == -1){ printf("No se ha podido crear el enlace duro\n"); } else { printf("Se ha podido crear el enlace duro\n"); } if(symlink(argv[1],sym) == -1){ printf("No se ha podido crear el enlace simbolico\n"); } else { printf("Se ha podido crear el enlace simbolico\n"); } } else { printf("no es un archivo ordinario\n"); } return 1; }
C
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> // malloc() int main() { int a = 0; // ǥ unsigned int int_size1 = sizeof a; unsigned int int_size2 = sizeof(int); unsigned int int_size3 = sizeof(a); size_t int_size4 = sizeof(a); size_t float_size = sizeof(float); printf("Size of int type is %u bytes.\n", int_size1); printf("Size of int type is %zu bytes.\n", int_size4); printf("Size of float type is %zu bytes.\n", float_size); int int_arr[30]; int *int_ptr = NULL; int_ptr = (int*)malloc(sizeof(int) * 30); printf("Size of array = %zu bytes.\n", sizeof(int_arr)); // 4bytes x 30 = 120bytes printf("Size of pointer = %zu bytes.\n", sizeof(int_ptr)); char c = 'a'; char string[10]; // maximally 9 characters + '/0' (null character) size_t char_size = sizeof(char); size_t str_size = sizeof(string); printf("Size of char type is %zu bytes.\n", char_size); // 1byte x 10 = 10bytes printf("Size of string type is %zu bytes.\n", str_size); return 0; }
C
#include<sys/types.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<error.h> #include<sys/wait.h> int main(int argc, char **argv) { int fds[2]; pid_t pid; if(pipe(fds) == -1) perror("pipe"); pid=fork(); if(pid == 0) { if(dup2(fds[1], STDOUT_FILENO) == -1) perror("dup2"); if(close(fds[0]) == -1) perror("close"); if(close(fds[1]) == -1) perror("close"); execlp("grep", "grep", "-n", argv[1], argv[2], NULL); perror("execlp"); } else { if(dup2(fds[0], STDIN_FILENO) == -1) perror("dup2"); if(close(fds[0]) == -1) perror("close"); if(close(fds[1]) == -1) perror("close"); //if(waitpid(pid, NULL, 0) == -1) //perror("waitpid"); execlp("cut", "cut", "-d:", "-f1", NULL); perror("execlp"); } return 0; }
C
#ifndef BST_H_ #define BST_H_ typedef struct text { int key_l; int key_r; //80 is standard column for programming +1 for end line char *line_l; char *line_r; struct text *left; struct text *middle; struct text *right; //For inserting into 3 nodes int key_m; struct text *parent; } text_t; text_t *create_text(void); int length_text( text_t *txt ); char *get_line( text_t *txt, int index ); void append_line( text_t *txt, char *new_line ); char *set_line( text_t *txt, int index, char *new_line ); void insert_line( text_t *txt, int index, char *new_line ); char *delete_line( text_t *txt, int index ); #endif // BST_H_
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* readers.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: eaptekar <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/08 12:32:26 by eaptekar #+# #+# */ /* Updated: 2018/10/11 19:12:45 by eaptekar ### ########.fr */ /* */ /* ************************************************************************** */ #include "parser.h" void check_scene(t_scene **scene) { check_vector((*scene)->cam, "scene->cam"); if ((*scene)->win_w < 320) (*scene)->win_w = 320; else if ((*scene)->win_w > 2260) (*scene)->win_w = 2260; if ((*scene)->win_h < 320) (*scene)->win_h = 320; else if ((*scene)->win_h > 1380) (*scene)->win_h = 1380; if ((*scene)->recursion_depth < 0) (*scene)->recursion_depth = 0; else if ((*scene)->recursion_depth > 20) (*scene)->recursion_depth = 20; } void check_light(t_light **light) { if ((*light)->type < 1 || (*light)->type > 3) ERROR("invalid light type"); if ((*light)->intensity < 0.01) (*light)->intensity = 0.01; else if ((*light)->intensity > 5) (*light)->intensity = 5; if ((*light)->type == 2) check_vector((*light)->ray, "light->position"); if ((*light)->type == 3) check_vector((*light)->ray, "light->direction"); } void set_vval(t_vector *field, char *buff) { t_vector *temp; temp = NULL; temp = get_vector(buff); if (!temp) return ; *field = *temp; free(temp); } char *reader_scene(t_scene *scene, char *cursor) { char buff[LINE_BUFF_SIZE]; move_cursor(&cursor); set_vval(&(scene->cam), FIND("position")); set_vval(&(scene->angle), FIND("direction")); scene->win_w = ft_atoi(FIND("window_x")); scene->win_h = ft_atoi(FIND("window_y")); scene->recursion_depth = ft_atoi(FIND("recursion")); check_scene(&scene); next_cbr(&cursor); return (cursor); } char *reader_light(t_scene *scene, char *cursor) { char buff[LINE_BUFF_SIZE]; t_light *light; if (scene->sources >= DEFAULT_ITEMS) ERROR("number of sources bigger then DEFAULT_ITEMS"); if (!(light = (t_light*)malloc(sizeof(t_light) + 1))) ERROR("malloc error: light"); move_cursor(&cursor); light->type = ft_atoi(FIND("type")); if (light->type == 2) set_vval(&(light->ray), FIND("position")); if (light->type == 3) set_vval(&(light->ray), FIND("direction")); light->intensity = ft_atof(FIND("intensity")); check_light(&light); next_cbr(&cursor); scene->light[scene->sources] = *light; scene->sources = scene->sources + 1; free(light); return (cursor); }
C
#include <stdio.h> #include <string.h> int main() { void *pvData = NULL; int *iData = NULL; float *fData = NULL; char *cData = NULL; printf("size of void pointer = %d\n", sizeof(pvData)); printf("size of int pointer = %d\n", sizeof(iData)); printf("size of float pointer = %d\n", sizeof(fData)); printf("size of char pointer = %d\n", sizeof(cData)); return 0; }
C
#include "contiki.h" #include "sys/timer.h" #include "dev/leds.h" #include "pt.h" //TODO PORQUE ESTE SI FUNCIONA SIN EL PROCESS_PAUSE ? /*---------------------------------------------------------------------------*/ PROCESS(test_etimer_process, "Test ET"); AUTOSTART_PROCESSES(&test_etimer_process); static struct leds{ int led; int clock; struct timer timer; struct pt *pt; }; static struct leds led1,led2, led3; /*---------------------------------------------------------------------------*/ static PT_THREAD(ledprocess(struct leds *leds)) { PT_BEGIN (leds -> pt); while(1) { leds_toggle(leds -> led); timer_set(&leds->timer,leds->clock * CLOCK_SECOND); PT_WAIT_UNTIL(leds->pt,timer_expired(&leds -> timer)); } PT_END(leds -> pt); } /*-----------------------------------------------------------------------------*/ PROCESS_THREAD(test_etimer_process, ev, data) { PROCESS_BEGIN(); led1.led=LEDS_BLUE; led1.clock=1; PT_INIT (led1.pt); led2.led=LEDS_GREEN; led2.clock=2; PT_INIT (led2.pt); led3.led=LEDS_RED; led3.clock=3; PT_INIT (led3.pt); while(1){ ledprocess(&led1); ledprocess(&led2); ledprocess(&led3); //PROCESS_WAIT_EVENT(); PROCESS_PAUSE(); } PROCESS_END(); }
C
#include<stdio.h> #include<stdlib.h> #include<math.h> #include "liste.h" #include "genList.h" int isPrime(int val){ int limite = 2, i; /* for(i=0; primeTab[i]<=lim; i++){ if((val % primeTab[i]) == 0) {return 0;} }*/ while((limite * limite) < val){ if((val % limite) == 0){return 0;} else {++limite;} } return 1; } void triTab(int tab[], int start, int taille){ int i, j, tmp; for(i=start; i<taille; i++){ for(j=i+1; j<taille && i<taille; j++){ if(tab[j] < tab[i]){ tmp = tab[j]; tab[j] = tab[i]; tab[i]=tmp;} } } } void inverseTriTab(int tab[], int start, int taille){ int i, j, tmp; for(i = start; i<taille; i++){ for(j=i+1; j<taille && i<taille; j++){ if(tab[j] > tab[i]){ tmp = tab[j]; tab[j] = tab[i]; tab[i] = tmp;} } } } /*Chercher le pivot le plus éloigné*/ int pivot(int tab[], int taille, int start){ int pos = 0, pivot = 0, find = 0, i, lim = taille - 1; for(i=start; i<lim; i++){ if(tab[i] < tab[i+1]){pos = i+1; find=1;} } if(find == 1){return pos;} else{/*printf("Aucun pivot trouvé, la liste est entièrement triée\n");*/ return taille-1;} } /*Dans la sous-liste je cherche le plus petit entier supérieur tab[j_pos]*/ int majorant(int tab[], int j_pos, int taille){ int i, majo = 9; /*chaque case de notre tableau devant contenir un chiffre d'ou le 9 comme valeur maximale*/ int find = 0, index = 0; for(i=j_pos; i<taille; i++){ if(tab[i] > tab[j_pos-1] && tab[i] < majo){ majo = tab[i]; find = 1; index = i;} } if(find == 1){ return index;} else {return -1;} } void intervertir(int tab[], int pos1, int pos2){ int tmp = 0; tmp = tab[pos1]; tab[pos1] = tab[pos2]; tab[pos2] = tmp; } int calculTailleEntier(int val){ int taille = 0, reste = 0, tmp = val; while(tmp > 0){ reste = tmp % 10; tmp = tmp/10; ++taille; } return taille; } int * intToTab(int val){ int taille = calculTailleEntier(val); int * res = malloc(taille * sizeof(int)); int i, tmp = val; for(i=taille-1; i>=0; i--){ res[i] = tmp % 10; tmp = tmp/10;} return res; } int tabToInt(int tab[], int taille){ int i, res = 0; for(i=0; i<taille; i++){res = res * 10 + tab[i];} // free(tab); return res; } /*L'objectif de cette fonction est de retourner le plus petit nombre supérieur *à celui donné en argument, avec la contrainte que celui-ci soit composé des *même chiffres que le nombre en input */ int sup(int tab[], int taille){ /*Le pivot est l'index où la monotonie de la suite se casse, *c-a-d tab[pivot-1] < tab[pivot] > tab[pivot + 1] */ int pivot_pos = pivot(tab, taille, 0); /*J'obtiens le pivot le plus éloigné*/ if(pivot_pos == taille-1){intervertir(tab, taille-1, taille-2); return tabToInt(tab, taille);} int pos_majorant = majorant(tab, pivot_pos, taille); if(pivot_pos < 0){printf("Aucun majorant au pivot n'a été trouvé, on retourne la valeur donnée en entrée.\n"); return tabToInt(tab, taille);} else{ intervertir(tab, pivot_pos-1, pos_majorant); triTab(tab, pivot_pos, taille); } return tabToInt(tab, taille); } /*Il faut écrire une fonction qui génère la liste générique des permutations pour les nombres de : *3 chiffres (999), 4 chiffres (9 999), 5 chiffres (99 999) et 6 chiffres (999 999)*/ void ** generePermutations(){ int i, * tmp = NULL, j, foo, depart, limite; void ** res = malloc(4*sizeof(void)); for(i = 3; i<=6; i++){ foo = 0; for(j=1; j<=i; j++){ foo = foo * 10 + j;} tmp = intToTab(foo); triTab(tmp, 0, i); depart = tabToInt(tmp, i); tmp = intToTab(foo); inverseTriTab(tmp, 0, i); limite = tabToInt(tmp, i); liste * l = NULL; l = ajoutEnQueue(l, depart); while(depart < limite){depart = sup(intToTab(depart), i); l = ajoutEnQueue(l, depart);} res[i - 3] = (void*)l; } return res; } int valPermute(int depart, int ordre, int taille){ int * tab_dep = intToTab(depart), tmp = ordre, index = taille-1; int * tab_permut = malloc(taille * sizeof(int)); while(tmp > 0){ tab_permut[index] = tab_dep[(tmp % 10) - 1]; tmp = tmp / 10; --index; } free(tab_dep); // La fonction intToTab effectue une allocation mémoire. return tabToInt(tab_permut, taille); //La fonction tabToInt effectue un free //Il ne faut donc pas effectuer un free sur le pointeur tab_permut } int decale35(int * tab, int taille){ int tmp = tab[0], i; for(i=0; i<taille-1; i++){ tab[i] = tab[i+1]; } tab[taille-1] = tmp; return tabToInt(tab, taille); } int isPrimeCircular(int val){ if(isPrime(val) == 1){ int * tmp = intToTab(val); int taille = calculTailleEntier(val); int per = decale35(tmp, taille); while(per != val){ if(isPrime(per) == 0){return 0;} per = decale35(tmp, taille); } return 1; } return 0; } int main(int argc, char ** argv){ int i, decompte = 0; for(i=100; i<1000000; i++){ if(isPrimeCircular(i) == 1){ ++decompte; printf("%d ", i); if(decompte % 10 == 0){ printf("\n");} } } printf("\n\nLe nombre total de nombre premier circulaire est decompte + 13 = %d + 13 = %d\n", decompte, decompte+13); return EXIT_SUCCESS; }
C
#include <libC.h> #include <lib.h> #include <stdarg.h> #define ULONG_MAX ((unsigned long)(~0L)) /* 0xFFFFFFFF */ #define LONG_MAX ((long)(ULONG_MAX >> 1)) /* 0x7FFFFFFF */ #define LONG_MIN ((long)(~LONG_MAX)) /* 0x80000000 */ //http://www.firmcodes.com/write-printf-function-c/ int printf(char *format, ...) { char *traverse; unsigned int i; char *s; //Module 1: Initializing print's arguments va_list arg; va_start(arg, format); for (traverse = format; *traverse != '\0'; traverse++) { while (*traverse != '%') { putChar(*traverse); traverse++; } traverse++; //Module 2: Fetching and executing arguments switch (*traverse) { case 'c': i = va_arg(arg, int); //Fetch char argument putChar(i); break; case 'd': i = va_arg(arg, int); //Fetch Decimal/Integer argument if (i < 0) { i = -i; putChar('-'); } puts(numtostr(i, 10)); break; case 's': s = va_arg(arg, char *); //Fetch string puts(s); break; case 'x': i = va_arg(arg, unsigned int); //Fetch Hexadecimal representation puts(numtostr(i, 16)); break; } } //Module 3: Closing argument list to necessary clean-up va_end(arg); return 0; } //http://www.firmcodes.com/write-printf-function-c/ char *numtostr(unsigned int num, int base) { static char Representation[] = "0123456789ABCDEF"; static char buffer[50]; char *ptr; ptr = &buffer[49]; *ptr = '\0'; do { *--ptr = Representation[num % base]; num /= base; } while (num != 0); return (ptr); } //https://code.woboq.org/gcc/libiberty/strtol.c.html long strtol(const char *nptr, char **endptr, register int base) { register const char *s = nptr; register unsigned long acc; register int c; register unsigned long cutoff; register int neg = 0, any, cutlim; /*Skip white space and pick up leading +/- sign if any. * If base is 0, allow 0x for hex and 0 for octal, else assume decimal; if base is already 16, allow 0x. */ do { c = *s++; } while (c == ' '); if (c == '-') { neg = 1; c = *s++; } else if (c == '+') c = *s++; if ((base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X')) { c = s[1]; s += 2; base = 16; } if (base == 0) base = c == '0' ? 8 : 10; cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX; cutlim = cutoff % (unsigned long)base; cutoff /= (unsigned long)base; for (acc = 0, any = 0;; c = *s++) { if ( c >= '0' && c <= '9' ) c -= '0'; else if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) c -= (c >= 'A' && c <= 'Z') ? 'A' - 10 : 'a' - 10; else break; if (c >= base) break; if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) any = -1; else { any = 1; acc *= base; acc += c; } } if (any < 0) { acc = neg ? LONG_MIN : LONG_MAX; } else if (neg) acc = -acc; if (endptr != 0) *endptr = (char *) (any ? s - 1 : nptr); return (acc); } //https://iq.opengenus.org/how-printf-and-scanf-function-works-in-c-internally/ int scanf (char * str, ...) { va_list vl; int i = 0, j=0, ret = 0; char buff[100] = {0}, c; char *out_loc; while(c != ' ') { if (getChar(&c)) { buff[i] = c; i++; } } va_start( vl, str ); i = 0; while (str && str[i]) { if (str[i] == '%') { i++; switch (str[i]) { case 'c': { *(char *)va_arg( vl, char* ) = buff[j]; j++; ret ++; break; } case 'd': { *(int *)va_arg( vl, int* ) = strtol(&buff[j], &out_loc, 10); j+=out_loc -&buff[j]; ret++; break; } case 'x': { *(int *)va_arg( vl, int* ) = strtol(&buff[j], &out_loc, 16); j+=out_loc - &buff[j]; ret++; break; } } } else { buff[j] = str[i]; j++; } i++; } va_end(vl); return ret; } //https://www.techiedelight.com/implement-strcmp-function-c/ // Function to implement strcmp function int strcmp(const char *X, const char *Y) { while (*X) { // if characters differ, or end of the second string is reached if (*X != *Y) { break; } // move to the next pair of characters X++; Y++; } // return the ASCII difference after converting `char*` to `unsigned char*` return *(const unsigned char*)X - *(const unsigned char*)Y; } int putChar(char c) { char buff[2] = {0}; buff[0] = c; return write(1,buff,2); } void puts(char * str) { while(*str) { putChar(*str); str++; } } int getChar(char * c) { char buffAux[2] = {0}; int ret = read(0, buffAux, 2); if (ret <= 0) return -1; *c = buffAux[0]; return ret; } // Función Hexa to Int //https://stackoverflow.com/questions/10156409/convert-hex-string-char-to-int uint32_t hex2int(char *hex) { uint32_t val = 0; while (*hex) { // get current character then increment uint8_t byte = *hex++; // transform hex character to the 4bit equivalent number, using the ascii table indexes if (byte >= '0' && byte <= '9') byte = byte - '0'; else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10; else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10; // shift 4 to make space for new digit, and add the 4 bits of the new digit val = (val << 4) | (byte & 0xF); } return val; }
C
#include<stdio.h> #define PI 3.14 int main(void) { int p_speed; int h_speed; int radius = 5; double round; double time; printf("Type the number\n"); printf("horse\n"); scanf("%d",&h_speed); printf("panda\n"); scanf("%d",&p_speed); round = radius * 2 * PI; time = round/(h_speed - p_speed); printf("시간:%lf\n",time); return 0; }
C
#include <stdio.h> #ifndef TREE_H #define TREE_H /* structures */ struct Node { void *data; struct Node *lt; struct Node *gte; }; struct Performance { unsigned int reads; unsigned int writes; unsigned int mallocs; unsigned int frees; }; /* function prototypes */ struct Performance *newPerformance(); void attachNode( struct Performance *performance, struct Node **node_ptr, void *src, unsigned int width ); int comparNode( struct Performance *performance, struct Node **node_ptr, int (*compar)(const void *, const void *), void *target ); struct Node **next( struct Performance *performance, struct Node **node_ptr, int direction ); void readNode( struct Performance *performance, struct Node **node_ptr, void *dest, unsigned int width ); void detachNode( struct Performance *performance, struct Node **node_ptr ); int isEmpty( struct Performance *performance, struct Node **node_ptr ); void addItem( struct Performance *performance, struct Node **node_ptr, int (*compar)(const void *, const void *), void *src, unsigned int width ); void freeTree( struct Performance *performance, struct Node **node_ptr ); int searchItem( struct Performance *performance, struct Node **node_ptr, int (*compar)(const void *, const void *), void *target, unsigned int width ); #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_cmdpath.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: afaraji <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/03 18:24:44 by afaraji #+# #+# */ /* Updated: 2020/11/03 18:24:49 by afaraji ### ########.fr */ /* */ /* ************************************************************************** */ #include "../inc/ft_21sh.h" #include "../inc/builtins.h" #include "../inc/parse.h" #include "../inc/ast.h" #include "../inc/exec.h" #include "../inc/ft_free.h" #include "../inc/readline.h" int do_prefix(t_cmd_prefix *prefix, t_variable *var, int env) { t_cmd_prefix *node; int ret; ret = 0; do_assignement(prefix, var, env); node = prefix; while (node) { if (node->io_redirect) { ret = do_redirect(node->io_redirect); if (ret != 0) return (ret); } node = node->prefix; } return (ret); } char **paths_from_env(void) { char **paths; char *tmp; int i; tmp = fetch_variables("PATH", -1); if (!tmp) return (NULL); paths = ft_strsplit(tmp, ':'); ft_strdel(&tmp); i = 0; if (!paths) return (NULL); while (paths[i]) { tmp = ft_strjoin(paths[i], "/"); free(paths[i]); paths[i] = tmp; i++; } paths[i] = NULL; return (paths); } char *get_cmdpath_error(int err_no, char *str) { int typ; if (err_no == 1) { typ = verify_type(str); if (typ == 1 || typ == 3) ft_print(STDERR, "shell: %s: is directory\n", str); else ft_print(STDERR, "shell: %s: No such file or directory\n", str); return (NULL); } if (err_no == 2) { ft_print(STDERR, "shell: command not found: %s\n", str); return (NULL); } return (NULL); } char *get_cmdpath(char *str) { char **paths; int i; char *tmp; if (!access(str, F_OK) && verify_type(str) == 2) return (ft_strdup(str)); if (is_path(str)) return (get_cmdpath_error(1, str)); if (!(paths = paths_from_env())) return (get_cmdpath_error(2, str)); i = 0; while (paths[i]) { tmp = ft_strjoin(paths[i], str); if (!access(tmp, F_OK)) { free_tab(paths); return (tmp); } ft_strdel(&tmp); i++; } free_tab(paths); return (get_cmdpath_error(2, str)); }
C
#include <unistd.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <stdlib.h> size_t ft_write(int fildes, const void *buf, size_t nbyte); size_t ft_strlen(const char *s); char *ft_strcpy(char * dst, const char * src); int ft_strcmp(const char *s1, const char *s2); ssize_t ft_read(int fildes, void *buf, size_t nbyte); char *ft_strdup(const char *s1); int main(void) { char *str; char *tab; char tab_0[7]; char tab_1[7]; char buffer_0[7]; char buffer_1[7]; int fd; int ret; str = "coucou"; tab = "coucou"; printf(" strlen<|%lu|\n", strlen(str)); printf("ft_strlen>|%lu|\n", ft_strlen(str)); write(1, " write<|coucou|\n", 18); ft_write(1, "ft_write<|coucou|\n", 18); printf(" strcpy<|%s|\n",strcpy(tab_0, str)); printf("ft_strcpy>|%s|\n",ft_strcpy(tab_1, str)); printf(" strcmp<|%d|\n", strcmp(tab, str)); printf("ft_strcmp>|%d|\n", ft_strcmp(tab, str)); tab = "culcul"; printf(" strcmp<|%d|\n", strcmp(tab, str)); printf("ft_strcmp>|%d|\n", ft_strcmp(tab, str)); fd = open("test", O_RDONLY); ret = read(fd, buffer_0, 6); printf(" read<ret:|%d| buff:|%s|\n", ret, buffer_0); ret = ft_read(fd, buffer_1, 6); printf("ft_read>ret:|%d| buff:|%s|\n", ret, buffer_1); fd = open("test.txt", O_RDONLY); ret = read(fd, buffer_0, 6); printf(" read<ret:|%d| buff:|%s|\n", ret, buffer_0); close(fd); fd = open("test.txt", O_RDONLY); ret = ft_read(fd, buffer_1, 6); printf("ft_read>ret:|%d| buff:|%s|\n", ret, buffer_1); close(fd); printf(" strdup<|%s|\n", strdup(str)); printf("ft_strdup>|%s|\n", ft_strdup(str)); return (0); }
C
#include <SDL2/SDL.h> #include <time.h> #define RUNS 1000 int main (int argc, char** argv) { SDL_Window* window = NULL; window = SDL_CreateWindow ( "sdl2box", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN ); SDL_Renderer* renderer = NULL; renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED); SDL_Rect r; r.x = 20; r.y = 20; r.w = 600; r.h = 440; // background black SDL_SetRenderDrawColor( renderer, 0, 0, 0, 255 ); SDL_RenderClear( renderer ); struct timespec start; clock_gettime(CLOCK_REALTIME, &start); // loop for benchmark for (int i=0; i<RUNS; i++) { // blue rect SDL_SetRenderDrawColor( renderer, 0, 0, 255, 255 ); SDL_RenderDrawRect( renderer, &r ); // green vertical SDL_SetRenderDrawColor( renderer, 0, 255, 0, 255 ); SDL_RenderDrawLine(renderer, 320, 40, 320, 440); // red horizontal SDL_SetRenderDrawColor( renderer, 255, 0, 0, 255 ); SDL_RenderDrawLine(renderer, 40, 240, 600, 240); } struct timespec end; clock_gettime(CLOCK_REALTIME, &end); int t_ms = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_nsec - start.tv_nsec) / 1000000; printf("Took %ims\n", t_ms); double timePerRunMs = ((double)t_ms) / ((double)RUNS); printf("One frame took %.3fms\n", timePerRunMs); // go.. SDL_RenderPresent(renderer); // Wait for 5 sec SDL_Delay( 5000 ); SDL_DestroyWindow(window); SDL_Quit(); return EXIT_SUCCESS; }
C
#ifndef FACTBASE_H #define FACTBASE_H typedef struct Fact { unsigned int id; char desc[256]; } Fact; typedef struct FactBaseElem { Fact fact; struct FactBaseElem *next; struct FactBaseElem *prev; } FactBaseElem; /* The FactBase datatype contains a pointer to both the first and the last fact in the list */ typedef struct FactBase { FactBaseElem *head; FactBaseElem *tail; } FactBase; Fact fact_new(char* desc); char* fact_get_desc(Fact fact); Fact fact_get_from_desc(FactBase fb, char* desc); bool fact_test_eq(Fact fact1, Fact fact2); FactBase FB_new(); bool FB_is_empty(FactBase fb); FactBase FB_insert_head(FactBase fb, Fact fact); FactBase FB_insert_tail(FactBase fb, Fact fact); FactBase FB_remove_head(FactBase fb); FactBase FB_remove_fact(FactBase fb, Fact fact_to_remove); void FB_display(FactBase fb, char* sep); #endif // FACTBASE_H
C
#include<stdio.h> #include<string.h> void main() { char s1[20],s2[20]; int a,i=0; printf("enter two string"); scanf("%s",s1); scanf("%s",s2); a=strlen(s1); a=a-1; while(s2[i]!='\0') { s1[a+1]=s2[i]; i++; b++; } printf("%s",s1); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* minishell.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ccatoire <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/30 13:54:45 by ccatoire #+# #+# */ /* Updated: 2018/08/30 13:54:47 by ccatoire ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" #include "unistd.h" // #include <sys/types.h> #include <dirent.h> #include <errno.h> //delete #include <string.h> //delete /* ** a.out looooool */ int check_exe(char *exe) { if (!access(exe, F_OK)) { if (!(whats_my_file(exe) == W_DIR)) return (OK); return (set_onrre(E_NOPERM, FAIL)); } return (set_onrre(E_NOFOUND, FAIL)); } char *find_exe(char *name, char *path) { char buff[BUFF_MAX]; size_t i; size_t stop; char absolut; i = 0; stop = 0; absolut = 0; if (check_exe(name) == OK) return (ft_strdup(name)); //dup pour eviter le double free vu que name est dans AV while (path && path[i] && !absolut) { stop = ft_strlen_till(&path[i], ':'); // ft_printf("path :\n%s\n", &path[i]); ft_bzero(buff, BUFF_MAX); ft_strncat(buff, &path[i], stop); ft_strcat(buff, "/"); ft_strcat(buff, name); // ft_printf("buff :\n%s\n", buff); if (check_exe(buff) == OK) return (ft_strdup(buff)); i += stop + 1; // PUTHR } return (NULL); } int a_out(char **av, t_list *env) { char *exe; char *path; pid_t pid; // PUTHR; // ft_printf("aout env =\n"); // ft_lstputstr(env); // ft_printf("aout av =\n"); // ft_putstab(av); // PUTHR; path = get_venv_val("PATH", env); if (!(exe = find_exe(av[0], path))) { // ft_tabsdel(av); return (FAIL); } // ft_printf("av0 = %s\n", av[0]); pid = fork(); if (pid == 0) { if (execve(exe, &av[0], ft_lsttotab(env)) == FAIL) //?? { // ft_printf("execve : %s\n", strerror(errno)); //ndawndkwand ft_tabsdel(av); return (set_onrre(E_IDK, FAIL)); } } else wait(0); // ft_tabsdel(av); ft_strdel(&exe); return (OK); }
C
#include<stdio.h> struct details { int name; int address; float date_of_birth; char blood_group; }; int main() { struct details d[2]; int i; for ( i = 0; i < 2; i++) { printf("enter the details %d name ",i+1); scanf("%d",&d[i].name); printf("enter the details %d address\n",i+1); scanf("%d",&d[i].address); printf("enter the details %f date of birth \n",i+1); scanf("%f",&d[i].date_of_birth); printf("enter the details %c blood group\n",i+1); scanf("%c\n",&d[i].blood_group); } for ( i = 0; i < 2; i++) { printf("\n details %d name:\n",i+1); printf("\n name :%d\n ",&d[i].name); printf("\n address: %d\n",&d[i].address); printf("\n date of birth: %f\n",&d[i].date_of_birth); printf("\n blood group :%c\n",&d[i].blood_group); } return 0; }
C
#ifndef __STACK_H__ #define __STACK_H__ typedef int stackElementT; typedef struct stack { int top; int size; stackElementT *contents; }stackT; int initStack(stackT *stack, int size); /* 初始化栈,大小为size*/ void destoryStack(stackT *stack); /* 销毁栈 */ int stackIsEmpty(stackT *stack); /* 栈是否为空 */ int stackPush(stackT *stack, stackElementT element); /* 入栈 */ int stackPop(stackT *stack, stackElementT *element); /* 出栈 */ #endif
C
#include<stdio.h> struct node{ int x; struct node *next; }; int main() { struct node head,link; head.x=10; head.next=&link; link.x=20; link.next=NULL; printf("head.x : %d\n",head.x); printf("head.next->x: %d",head.next->x); return 0; }
C
#include<stdio.h> #include<stdbool.h> #include<stdlib.h> struct node { int data; struct node* prev; struct node* next; }*head = NULL, *toe; typedef struct node NODE; int main(int argc, char const *argv[]) { /* code */ return 0; } void create(int n)// Creates or Extends list by 'n' { if (head == NULL) { head = (NODE*)malloc(sizeof(NODE)); scanf("%d", &head->data); head->prev = NULL; head->next = NULL; toe = head; --n; } for (int i = 0; i < n; ++i) { NODE* node = (NODE*)malloc(sizeof(NODE)); scanf("%d", &node->data); node->prev = toe; node->next = NULL; toe->next = node; toe = node; } } void display()// Print the Current list { printf("\n++++----++++----++++----++++----++++\n"); for (NODE* print = head; print != NULL; print = print->next) { printf("%d\t", print->data); } printf("\n++++----++++----++++----++++----++++\n"); } void display_end()// Prints list in reverse order { printf("\n++++----++++----++++----++++----++++\n"); for (NODE* print = toe; print != NULL; print = print->prev) { printf("%d\t", print->data); } printf("\n++++----++++----++++----++++----++++\n"); } int count()// Counts total number of elements in the list { int count = 0; for (NODE* i = head; i != NULL; i = i->next) { ++count; } return count; } void insert(int pos)// Inserts an extra node in the list { int n = count(); NODE* new_node = (NODE*)malloc(sizeof(NODE)); new_node->prev = NULL; new_node->next = NULL; scanf("%d", &new_node->data); if (n == 0) { pos = 0; } if (pos <= 0) { new_node->next = head; if (head != NULL) { head->prev = new_node; } head = new_node; } else if (pos >= n) { new_node->prev = toe; toe->next = new_node; toe = new_node; } else if (pos < n / 2) { NODE* ptr = head; for (int i = 1; i < pos; ++i) { ptr = ptr->next; } new_node->prev = ptr; new_node->next = ptr->next; ptr->next->prev = new_node; ptr->next = new_node; } else { NODE* ptr = toe; pos = n - pos; for (int i = 1; i < pos; ++i) { ptr = ptr->prev; } new_node->prev = ptr->prev; new_node->next = ptr; ptr->prev->next = new_node; ptr->prev = new_node; } } void delete_node(int pos)// Delete by Position { int n = count(); if ( n == 0) { return; } else if (pos < 0 || pos > n) { printf("Invalid Location"); return; } else if (pos == 1 || pos == 0) { NODE* temp = head->next; head->next->prev = NULL; head->next = NULL; free(head); head = NULL; head = temp; } else if (pos == n) { NODE* temp = toe->prev; toe->prev->next = NULL; free (toe); toe = NULL; toe = temp; } else if (pos < n / 2) { NODE* ptr = head; for (int i = 1; i < pos; ++i) { ptr = ptr->next; } ptr->prev->next = ptr->next; ptr->next->prev = ptr->prev; free (ptr); ptr = NULL; } else { NODE* ptr = toe; pos = n - pos; for (int i = 1; i <= pos; ++i) { ptr = ptr->prev; } ptr->next->prev = ptr->prev; ptr->prev->next = ptr->next; free (ptr); ptr = NULL; } } bool delete_number(int num)// Delete by Value { if (head != NULL && head->data == num) { NODE* temp = head->next; if (head->next != NULL) { head->next->prev = NULL; } free (head); head = temp; return true; } else if (head != NULL && toe->data == num) { NODE* temp = toe->prev; toe->prev->next = NULL; free (toe); toe = temp; return true; } else if (head != NULL) { NODE* ptr = head; while (ptr->data != num && ptr != toe) { ptr = ptr->next; } if (ptr != NULL && ptr->data == num) { ptr->prev->next = ptr->next; ptr->next->prev = ptr->prev; free (ptr); return true; } } return false;// false means number not found } void rotate_right()// Right Shift { if (head != NULL && head != toe) { head->prev = toe; toe->next = head; toe->prev->next = NULL; NODE* temp = toe->prev; toe->prev = NULL; head = toe; toe = temp; } } void rotate_left()// Left Shift { if (head != NULL && head != toe) { head->prev = toe; toe->next = head; head->next->prev = NULL; NODE* temp = head->next; head->next = NULL; toe = head; head = temp; } } bool palindrome()// Is list symetrical about the mid? { NODE *i = head, *j = toe; while (i != j && i != NULL && j != NULL) { if (i->data != j->data) { return false; } else { i = i->next; j = j->prev; } } return true; } void swap_node(int pos1, int pos2)// Interchanges Address of Two Nodes { int n = count(); if (pos1 == 1)// { NODE* replace = head; for (int i = 1; i < pos2; ++i) { replace = replace->next; } replace->prev->next = head; replace->next->prev = head; head->next->prev = replace; NODE* temp = head->next; head->prev = replace->prev; head->next = replace->next; replace->prev = NULL; replace->next = temp; head = replace; return; } else if (pos2 == n) { NODE* replace = head; for (int i = 1; i < pos1; ++i) { replace = replace->next; } replace->prev->next = toe; replace->next->prev = toe; toe->prev->next = replace; NODE* temp = toe->prev; toe->prev = replace->prev; toe->next = replace->next; replace->prev = temp; replace->next = NULL; toe = replace; return; } else if (pos1 > n || pos2 > n || pos1 < 0 || pos2 < 0) { return; } else { NODE* replace1 = head; for (int i = 1; i < pos1; ++i) { replace1 = replace1->next; } NODE* replace2 = head; for (int i = 1; i < pos2; ++i) { replace2 = replace2->next; } replace1->prev->next = replace2; replace1->next->prev = replace2; replace2->prev->next = replace1; replace2->next->prev = replace1; NODE* temp_prev = replace1->prev; NODE* temp_next = replace1->next; replace1->prev = replace2->prev; replace1->next = replace2->next; replace2->prev = temp_prev; replace2->next = temp_next; } } // SEARCH int linear(int search) { int pos = 0; NODE* identify = head; while (identify != NULL) { ++pos; if (identify->data == search) { return pos; } identify = identify->next; } return 0;// 0 means number not found } // SORT void bubble() { for (NODE* i = head; i != NULL; i = i->next) { for (NODE* j = head; j->next != NULL; j = j->next) { if (j->data > j->next->data) { int temp; temp = j->data; j->data = j->next->data; j->next->data = temp; } } } }
C
#pragma once // bn.h struct bn_s; typedef struct bn_s bn; /*enum bn_codes { BN_OK, BN_NULL_OBJECT, BN_NO_MEMORY, BN_DIVIDE_BY_ZERO }; */ bn *bn_new(); // BN bn *bn_init(bn const *orig); // BN // BN int bn_init_string(bn *t, const char *init_string); // BN // radix int bn_init_string_radix(bn *t, const char *init_string, int radix); // BN int bn_init_int(bn *t, int init_int); // BN ( ) int bn_delete(bn *t); // , +=, -=, *=, /=, %= int bn_add_to(bn *t, bn const *right); int bn_sub_to(bn *t, bn const *right); int bn_mul_to(bn *t, bn const *right); int bn_div_to(bn *t, bn const *right); int bn_mod_to(bn *t, bn const *right); // degree int bn_pow_to(bn *t, int degree); // reciprocal BN ( ) int bn_root_to(bn *t, int reciprocal); // x = l+r (l-r, l*r, l/r, l%r) bn* bn_add(bn const *left, bn const *right); bn* bn_sub(bn const *left, bn const *right); bn* bn_mul(bn const *left, bn const *right); bn* bn_div(bn const *left, bn const *right); bn* bn_mod(bn const *left, bn const *right); // BN radix // . const char *bn_to_string(bn const *t, int radix); // , <0; , 0; >0 int bn_cmp(bn const *left, bn const *right); int bn_neg(bn *t); // int bn_abs(bn *t); // int bn_sign(bn const *t); //-1 t<0; 0 t = 0, 1 t>0
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> //Լ:call bu reference //mainԼ a 氡. void change(int* p) { *p = 20; } //mainԼ μ ٲٱ void twochange(int* pa, int* pb) { int temp = *pa; *pa = *pb; *pb = temp; } //հ豸ϱ void sumCal(int* pa, int* psum) { *psum += *pa; } int main() { //Լ ͳѱ /*int a=10; change(&a); scanf("%d",&a); printf("a:%d\n", a);*/ //μٲٱ /*int a = 10, b = 20; twochange(&a, &b); printf("%d %d\n", a, b);*/ //ݺ ̿ؼ Է¹ . //Լ //int a,sum=0; //scanf(""); int a, sum = 0; while (1) { printf("?"); scanf("%d", &a); if (a == 0) break; sumCal(&a, &sum);//call by reperence } printf("հ:%d", sum); }
C
#ifndef BRIDGE_H #define BRIDGE_H #include <stdint.h> #define reg_t uint64_t #define print(string) print_string(string, uart_write_char) #define println(string) print(string "\n\r") #define print64(val) print_hex(val, uart_write_char, 8) #define print64_raw(val) print_hex_raw(val, uart_write_char, 8) #define TRUE (uint8_t)1 #define FALSE (uint8_t)0 void uart_write_char(char); void print_string(const char*, void(*f)(char)); void print_hex(reg_t, void(*f)(char), reg_t); void print_hex_raw(reg_t, void(*f)(char), reg_t); void newline(); #endif
C
#include <stdio.h> void calculate_the_maximum(int n, int k) { int max[3] = {0,0,0}; for(int i=1; i<=n; i++){ for(int j=i+1; j<=n; j++){ int temp[3] = {i&j,i|j,i^j}; if(temp[0]>max[0] && temp[0]<k){ max[0] = temp[0]; } if(temp[1]>max[1] && temp[1]<k){ max[1] = temp[1]; } if(temp[2]>max[2] && temp[2]<k){ max[2] = temp[2]; } } } for(int ii=0; ii<=2; ii++) printf("%d\n",max[ii]); }
C
#include "function_declaration.h" #include <malloc.h> #include <stdlib.h> #include <stdio.h> static VertexID visit_seq[MAX_VERTEX_NUM]; static VertexID seq; void init_gragh(gragh *G) //初始化图 { G->arcnum = G->vertexnum = 0; } #ifdef kinderfisher INFO new_info_kf() { int i = 0; char c; INFO info; printf("please input ID:\n"); while ((c = getchar()) != '$') info.id[i++] = c; printf("please input weight:\n"); scanf("%d", &info.weight); printf("please input length:\n"); scanf("%d", &info.length); printf("please input name:\n"); i = c = 0; getchar(); while ((c = getchar()) != '$') info.name[i++] = c; info.Is_carnivorous = 1; info.Is_Marine = 0; printf("please input speed of this one:\n"); scanf("%d", &info.speed); printf("please input color of this one:\n"); i = c = 0; getchar(); while ((c = getchar()) != '$') info.color[i++] = c; return info; } void visit_kf(INFOPTR info) { if (info == NULL) { printf("there isn't any information about it\n"); return; } printf("the id of kinderfisher is:%s\n", info->id); printf("the weight of it is:%d\n", info->weight); printf("the length of it is:%d\n", info->length); printf("the name of it is:%s\n", info->name); printf("the color of it is:%s\n", info->color); printf("the speed of it is:%d\n", info->speed); if (info->Is_carnivorous) printf("it's carnivorous\n"); else printf("it's non-carnivorous\n"); if (info->Is_Marine) printf("it's marine\n"); else printf("it's non-marine\n"); } void visit(gragh*G, int target) { int i; for (i = 0; i < G->vertexnum; i++) if (G->vertex[i].firstvertex == target) { printf("%d:\n", target); //visit_kf(&G->vertex[i].info); } } #endif //kinderfisher // #ifdef // #endif // // #ifdef // #endif // int locate_vertex(gragh *G, VertexID v) //返回顶点 v 在vertex数组中的下标,如果v不存在,返回-1 { if (!G->vertexnum) { printf("the gragh is empty\n"); return -1; } int i; for (i = 0; i < G->vertexnum; i++) if (v == G->vertex[i].firstvertex) return i; if (i == G->vertexnum) { printf("no matched target,\n"); return -1; } } bool insert_vertex(gragh *G, VertexID v) { G->vertex[v].firstvertex = v; G->vertex[v].firstarc = NULL; //G->vertex[v].info = new_info_kf(); return true; }//不能用来插入,只能用于创建图! bool insert_arc(gragh *G, VertexID des1, VertexID des2) { if (G == NULL || locate_vertex(G, des1) == -1 || locate_vertex(G, des2) == -1) { printf("there isn't such vertex in the gragh.\n"); return false; } int a = locate_vertex(G, des1), b = locate_vertex(G, des2); ANode *arcdes1 = G->vertex[a].firstarc; ANode *arcdes2 = G->vertex[b].firstarc; for (; arcdes1 != NULL; arcdes1 = arcdes1->nextarc) if (arcdes1->adjvex == des1) return false; arcdes1 = G->vertex[a].firstarc; ANode *ass1 = (ANode*)malloc(sizeof(ANode)); ANode *ass2 = (ANode*)malloc(sizeof(ANode)); ass1->adjvex = des2, ass1->nextarc = arcdes1; G->vertex[a].firstarc = ass1; ass2->adjvex = des1, ass2->nextarc = arcdes2; G->vertex[b].firstarc = ass2; } bool create_gragh(gragh *G) { if (G->arcnum != 0 && G->vertexnum != 0) { printf("the gragh has already exsist.\n"); return false; } int des1, des2; printf("please input the number of arc:"); scanf("%d", &G->arcnum); printf("please input the number of vertex:"); scanf("%d", &G->vertexnum); int i; printf("please input the information of everyone:\n"); for (i = 0; i < G->vertexnum; i++) { printf("%d:\n", i); insert_vertex(G, i); //G->vertex[i].info = new_info_kf(); putchar('\n'); }//插入结点 getchar(); for (i = 0; i < G->arcnum; i++) { printf("please input the VertexID of both ends of arc:\n"); printf("%d:\n",i); printf("first end:");scanf("%d", &des1);getchar(); printf("second end:");scanf("%d", &des2);getchar(); insert_arc(G, des1, des2); }//插入边 return true; } void DFS_VertexID(gragh*G, int src, VertexID* visited) { visit(G, src);visited[src] = 1; visit_seq[seq++] = src; ANode* next = G->vertex[src].firstarc; while(next) { if (!visited[next->adjvex]) DFS_VertexID(G, next->adjvex, visited); next = next->nextarc; } }//递归实现深度优先遍历并输出信息 void DFS(gragh*G, int src, VertexID* visited) { int i; seq = 0; for (i = 0; i < G->vertexnum; i++) visited[i] = 0; DFS_VertexID(G, src, visited); for (i = 0; i < seq; i++) { if(i != seq - 1) printf("%d-->",visit_seq[i]); else printf("%d\n", visit_seq[i]); } } void BFS_VertexID(gragh*G, int src, VertexID* visited, RQUEUE* Q) { VertexID visiting; visit(G, src); visited[src] = 1; visit_seq[seq++] = src; InitQueue(Q); EnterQueue(Q, src); ANode* W = NULL; while(!IsEmpty(Q)) { DeleteQueue(Q, &visiting); W = G->vertex[visiting].firstarc; while(W) { if(!visited[W->adjvex]) { visit(G, W->adjvex); visit_seq[seq++] = W->adjvex; visited[W->adjvex] = 1; EnterQueue(Q, W->adjvex); } W = W->nextarc; } } }//递归实现广度优先遍历并输出信息 void BFS(gragh*G, int src, VertexID* visited, RQUEUE* Q)//按广度优先输出遍历顺序并按该顺序输出信息 { int i; seq = 0; for (i = 0; i < G->vertexnum; i++) visited[i] = 0; BFS_VertexID(G, src, visited, Q); for (i = 0; i < seq; i++) { if(i != seq - 1) printf("%d-->",visit_seq[i]); else printf("%d\n", visit_seq[i]); } } void InitQueue(RQUEUE* Q)//初始化队列 { Q->rear = Q->front = 0; } bool EnterQueue(RQUEUE* Q, VertexID target)//数据进队 { ANode a; if (IsFull(Q)) {printf("the queue already full"); return 0;} Q->QueueElem[Q->rear] = target; Q->rear = (Q->rear+1) % MAX_VERTEX_NUM; return 1; } bool DeleteQueue(RQUEUE* Q, VertexID *target)//数据出队 { if (IsEmpty(Q)){printf("the queue is empty.\n"); return 0;} *target = Q->QueueElem[Q->front]; Q->front = (Q->front + 1) % MAX_VERTEX_NUM; return 1; } bool IsEmpty(RQUEUE* Q)//判断队是否空 { if (Q->front == Q->rear) return 1; else return 0; } bool IsFull(RQUEUE* Q)//判断队是否满 { if ((Q->rear + 1) % MAX_VERTEX_NUM == Q->front) return 1; else return 0; }
C
#include "../include/macro.h" #include "../include/menu.h" #include <stdio.h> #include <termios.h> static struct termios old, current; /* Initialize new terminal i/o settings */ void initTermios(int echo) { tcgetattr(0, &old); /* grab old terminal i/o settings */ current = old; /* make new settings same as old settings */ current.c_lflag &= ~ICANON; /* disable buffered i/o */ if (echo) { current.c_lflag |= ECHO; /* set echo mode */ } else { current.c_lflag &= ~ECHO; /* set no echo mode */ } tcsetattr(0, TCSANOW, &current); /* use these new terminal i/o settings now */ } /* Restore old terminal i/o settings */ void resetTermios(void) { tcsetattr(0, TCSANOW, &old); } /* Read 1 character - echo defines echo mode */ char getch_(int echo) { char ch; initTermios(echo); ch = getchar(); resetTermios(); return ch; } /* Read 1 character without echo */ char getch(void) { return getch_(0); } /* Read 1 character with echo */ char getche(void) { return getch_(1); } void control() { //printf(HIDE_CURSOR); char buff; //letter; int out = 0, row, column; //clock_t start, end; printMenu(0 , 0); while(!out) { buff = '\0'; row = 0; column = 0; while(buff != '\n') { buff = getche(); if(buff == 'D' && row == LINE_1 && column == COLUMN_1) column -= 1; if(buff == 'C' && row == LINE_1 && column == COLUMN_2) column +=1; if(buff == 'A' && row == LINE_2) row -=1; if(buff == 'B' && row == LINE_1) row +=1; if(!(row >=0 && row<=5)){ if(row>5) row = 5; else if (row<0) row=0; } if(!(column >= 0 && column <= 2)){ if(column>3) column = 2; else if (column < 0) column = 0; } } printMenu(row , column); } } /* void main_loop(){ control(); char command[127]; do{ }while(find_word_in_string("quit", command)) }*/
C
// *** // *** You MUST modify this file // *** #include <stdio.h> #include <stdlib.h> #include <string.h> #include "tree.h" // DO NOT MODIFY FROM HERE --->>> void deleteTreeNode(TreeNode * tr) { if (tr == NULL) { return; } deleteTreeNode (tr -> left); deleteTreeNode (tr -> right); free (tr); } void freeTree(Tree * tr) { if (tr == NULL) { // nothing to delete return; } deleteTreeNode (tr -> root); free (tr); } static void preOrderNode(TreeNode * tn, FILE * fptr) { if (tn == NULL) { return; } fprintf(fptr, "%d\n", tn -> value); preOrderNode(tn -> left, fptr); preOrderNode(tn -> right, fptr); } void preOrder(Tree * tr, char * filename) { if (tr == NULL) { return; } FILE * fptr = fopen(filename, "w"); preOrderNode(tr -> root, fptr); fclose (fptr); } // <<<--- UNTIL HERE // *** // *** You MUST modify the follow function // *** #ifdef TEST_BUILDTREE // Consider the algorithm posted on // https://www.geeksforgeeks.org/construct-a-binary-tree-from-postorder-and-inorder/ TreeNode * helper(int * inArray, int * postArray, int inStart, int inEnd, int *postIndex) { if (inStart > inEnd){return NULL;} // find the root based on postArray int root = postArray[*postIndex]; (*postIndex)--; TreeNode * tn = malloc(sizeof(TreeNode)); tn -> left = NULL; tn -> right = NULL; tn -> value = root; /* If this node has no children then return */ if (inStart == inEnd){return tn;} // find the index of root in inArray int inIndex; for (int x = inStart; x <= inEnd; x++) { if (inArray[x] == root) { inIndex = x; } } /* Using index in Inorder traversal, construct left and right subtress */ tn -> right = helper(inArray, postArray, inIndex + 1, inEnd, postIndex); tn -> left = helper(inArray, postArray, inStart, inIndex - 1, postIndex); return tn; } Tree * buildTree(int * inArray, int * postArray, int size) { int Index = size - 1; Tree * tr = malloc(sizeof(Tree)); tr -> root = helper(inArray, postArray, 0, size - 1, &Index); return tr; } #endif
C
/* ** player_position.c for zappy in /home/Dante/rendu/System_Unix/PSU_2016_zappy/Zappy_server/src ** ** Made by Dante Grossi ** Login <[email protected]> ** ** Started on Tue Jun 27 16:58:29 2017 Dante Grossi ** Last update Sat Jul 1 17:22:30 2017 Dante Grossi */ #include "viewer.h" static bool send_position(t_zappy *zappy, int idx) { bool ret; char *msg; t_node *node; t_client *client; node = zappy->players->head; while (node) { client = (t_client *)node->value; if (client->fd == idx) { if (!(msg = malloc(nb_len(client->cell->x) + nb_len(client->cell->y) + nb_len(client->angle) + nb_len(idx) + 6))) return (false); sprintf(msg, "ppo %d %d %d %d", idx, client->cell->x, client->cell->y, client->angle); ret = send_to(zappy->current, msg); free(msg); return (ret); } node = node->next; } ret = send_to(zappy->current, BADPARAMSVIEWER); return (ret); } bool player_position(t_zappy *zappy, const char **request) { bool ret; int idx; if (!request[1]) { ret = send_to(zappy->current, BADCMDVIEWER); return (ret); } if (!is_num(request[1])) { ret = send_to(zappy->current, BADPARAMSVIEWER); return (ret); } idx = atoi(request[1]); ret = send_position(zappy, idx); return (ret); }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #define BUFF_SIZE 8096 void help(); void copy_mmap(char* fd_from, char* fd_to); void copy_read_write(char* fd_from, char* fd_to); bool is_file_existing(const char* filename); int main(int argc, char** argv) { if (argc == 1 || argc > 4 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-H") == 0) { help(); return 0; } else { if (strcmp(argv[1], "-m") == 0 && argc == 4) { // With -m if (is_file_existing(argv[2])) { copy_mmap(argv[2], argv[3]); } else { printf("No such file named %s\n", argv[2]); help(); return 0; } } else { if (strcmp(argv[1], "-m") == 0) { printf("\nInvalid number of arguments\n"); help(); return 0; } if (*argv[1] == *"-") { printf("\ncopy: invalid option -- '%s'\n", argv[1]); help(); return 0; } if (argc != 3) { printf("\nInvalid number of arguments\n"); help(); return 0; } // Without -m if(is_file_existing(argv[1])) { copy_read_write(argv[1], argv[2]); } else { printf("No such file named %s\n", argv[1]); help(); return 0; } } } } void help() { printf("\ncopy [-m] <file_name> <new_file_name>\n"); printf("copy [-h]\n\n\n"); printf(" -m use memory map\n"); printf(" -h, --help display this help and exit\n\n"); } void copy_mmap(char* fd_from, char* fd_to) { int source, target; char *sourcePtr, *targetPtr; size_t sourceFileSize = 0; // Open source file source = open(fd_from, O_RDONLY); // Compute the size of the source file sourceFileSize = lseek(source, 0, SEEK_END); // Copy source file in memory sourcePtr = mmap(NULL, sourceFileSize, PROT_READ, MAP_PRIVATE, source, 0); // Create a file named 'argv[3]' with the rights 0666 target = open(fd_to, O_CREAT | O_RDWR, 0666); // Set the byte length ftruncate(target, sourceFileSize); // Copy target file in memory targetPtr = mmap(NULL, sourceFileSize, PROT_READ | PROT_WRITE, MAP_SHARED, target, 0); // Replace targetPtr content by the sourcePtr content memcpy(targetPtr, sourcePtr, sourceFileSize); // Delete memory allocated to sourcePtr and targetPtr munmap(sourcePtr, sourceFileSize); munmap(targetPtr, sourceFileSize); printf("%s successfully copied in %s ... \n", fd_from, fd_to); close(source); close(target); } void copy_read_write(char* fd_from, char* fd_to) { char buffer[BUFF_SIZE]; int readfile, source, target; // Open source file source = open(fd_from, O_RDONLY); // Create a file named 'argv[2]' with the rights 0666 target = open(fd_to, O_CREAT | O_WRONLY, 0666); readfile = read(source, buffer, sizeof(buffer)); write(target, buffer, readfile); printf("%s successfully copied in %s ... \n", fd_from, fd_to); close(source); close(target); } bool is_file_existing(const char* filename) { struct stat buffer; int exist = stat(filename, &buffer); if(exist == 0) { return true; } else { return false; } }
C
#include "Lib/Std_Types.h" #include "MCAL/TMR_interface.h" #include "MCAL/GIE_interface.h" #include "RTOS_interface.h" #include "RTOS_private.h" #include "RTOS_config.h" TaskControlBlock_t TaskBlocksArr[RTOS_TASK_NUM] = {{NULL}}; void RTOS_VidStart() { TMR_VidInit(); TMR_VidSetDutyCycle(0, 50); /* Set OCR0 = 127 */ TMR_VidSetCallBack(0, VidAlgorithm); GIE_VidEnable(); } void RTOS_VidCreateTask(u8 Copy_u8Priority, u16 Copy_u16Periodicity, u16 Copy_u16InitialDelay, void (*func)(void)) { if (Copy_u8Priority < RTOS_TASK_NUM) { TaskBlocksArr[Copy_u8Priority].Periodicity = Copy_u16Periodicity; TaskBlocksArr[Copy_u8Priority].TaskFunc = func; TaskBlocksArr[Copy_u8Priority].RunMe = 0; TaskBlocksArr[Copy_u8Priority].TaskCounter = Copy_u16InitialDelay; } } void RTOS_VidDispatcher() { /* Check on all tasks and excute any task with RunMe flag raised */ for (u8 i = 0; i < RTOS_TASK_NUM; i++) { /* Check if task exists */ if (TaskBlocksArr[i].TaskFunc != NULL) { /* Check if flag is raised */ if (TaskBlocksArr[i].RunMe == 1) { /* Downing Flag */ TaskBlocksArr[i].RunMe = 0; /*Run Task */ TaskBlocksArr[i].TaskFunc(); } } } } static void VidAlgorithm() { /* Iterating through all the tasks */ for (u8 i = 0; i < RTOS_TASK_NUM; i++) { /* Checking if task exists */ if (TaskBlocksArr[i].TaskFunc != NULL) { /* Check if counter equals 0 */ if (TaskBlocksArr[i].TaskCounter == 0) { /* Set flag */ TaskBlocksArr[i].RunMe = 1; /* Update counter periodicity */ TaskBlocksArr[i].TaskCounter = TaskBlocksArr[i].Periodicity; } /* if task is not ready */ else { /* Counter Decrement */ TaskBlocksArr[i].TaskCounter--; } } } } static void voidSleep() { SET_BIT(MCUCR, MCUCR_SE); __asm__ __volatile__("SLEEP" ::); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(){ struct chatting_list{ char chatting_room[100]; // 채팅방 이름 int unread; // 안읽은 메시지 int is_it_multi_room; // 채팅방 옵션 int key[20]; // 암호화/복호화 키 }list[100]; FILE *chatting_fp; //struct chatting_list list[100]; chatting_fp = fopen("./chatting_list.txt","rt"); int i = 0; while(fscanf(chatting_fp, "%s%d%d%s", list[i].chatting_room, &list[i].unread, &list[i].is_it_multi_room, list[i].key) != EOF){ i++; } i++; fclose(chatting_fp); scanf("%s%d%d%s", list[i].chatting_room, &list[i].unread, &list[i].is_it_multi_room, list[i].key); chatting_fp = fopen("./chatting_list.txt","at"); /* fprintf(chatting_fp, "%s %d %d %s;\n", list[i].chatting_room, list[i].unread, list[i].is_it_multi_room, list[i].key); */ for(i=0;i<6;i++) printf("%s %d %d %s\n", list[i].chatting_room, list[i].unread, list[i].is_it_multi_room, list[i].key); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fork.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jhur <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/23 13:55:26 by jhur #+# #+# */ /* Updated: 2020/07/23 13:55:28 by jhur ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" static char *ft_absolute_path(char **path, char **cmd, char *res, struct stat buf) { path = 0; if (res == 0 && lstat(cmd[0], &buf) == 0) { res = ft_strdup(cmd[0]); g_ret = 1; } return (res); } char *ft_pathjoin(char **path, char **cmd) { struct stat buf; char *res; int i; char *path_cmd; i = 0; res = 0; path_cmd = 0; while (path && path[i]) { path_cmd = ft_strjoin_sh(path[i], cmd[0]); if (lstat(path_cmd, &buf) == 0) { res = path_cmd; break ; } free(path_cmd); path_cmd = 0; i++; } ft_free(path); if (res == 0) res = ft_absolute_path(path, cmd, res, buf); return (res); } void child_process(char **info, int *pipefd) { if (pipefd[0] != 0) close(pipefd[0]); dup2(pipefd[1], 1); if (pipefd[1] != 1) close(pipefd[1]); ft_cmd(info); exit(0); } void parent_process(int *pipefd, char **path, char **cmd, int i) { int pipefd2[2]; close(pipefd[1]); dup2(pipefd[0], 0); close(pipefd[0]); pipefd2[0] = 0; pipefd2[1] = 1; if (cmd[i + 1] != 0) pipe(pipefd2); fork_process(pipefd2, cmd, path, i); } void fork_process(int *pipefd, char **cmd, char **path, int i) { int pid; int status; char **info; pid = fork(); if (pid == -1) { perror("fork failed"); exit(1); } else if (pid == 0) { info = get_info(cmd[i]); child_process(info, pipefd); } else { waitpid(pid, &status, 0); if (cmd[i + 1]) parent_process(pipefd, path, cmd, i + 1); } }
C
/* * cgi2scgi: A CGI to SCGI translator * */ /* configuration settings */ #ifndef HOST #define HOST "127.0.0.1" #endif #ifndef PORT #define PORT 4000 #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netinet/tcp.h> /* for TCP_NODELAY */ #define SCGI_PROTOCOL_VERSION "1" struct scgi_header { struct scgi_header *next; char *name; char *value; }; extern char **environ; static void die(void) { _exit(2); } static void die_perror(char *msg) { char buf[500]; snprintf(buf, sizeof buf, "error: %s", msg); perror(buf); die(); } static void die_msg(char *msg) { fprintf(stderr, "error: %s\n", msg); die(); } static int open_socket(void) { int sock, set; int tries = 4, retrytime = 1; struct in_addr host; struct sockaddr_in addr; /* create socket */ if (!inet_aton(HOST, &(host))) { die_perror("parsing host IP"); } addr.sin_addr = host; addr.sin_port = htons(PORT); addr.sin_family = AF_INET; retry: sock = socket(PF_INET, SOCK_STREAM, 0); if (sock == -1) { die_perror("creating socket"); } /* connect */ if (connect(sock, (struct sockaddr *)&addr, sizeof addr) == -1) { close(sock); if (errno == ECONNREFUSED && tries > 0) { sleep(retrytime); tries--; retrytime *= 2; goto retry; } die_perror("connecting to server"); } #ifdef TCP_NODELAY /* disable Nagle */ set = 1; setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set)); #endif return sock; } static int send_headers(FILE *fp) { int n; char **p; /* set the CONTENT_LENGTH header if it is not already set */ if (setenv("CONTENT_LENGTH", "0", 0) < 0) return 0; if (setenv("SCGI", SCGI_PROTOCOL_VERSION, 1) < 0) return 0; /* calculate the total length of the headers */ n = 0; for (p = environ; *p != NULL; *p++) { if (strchr(*p, '=') == NULL) continue; n += strlen(*p) + 1; } /* send header data as netstring */ if (fprintf(fp, "%u:", n) < 0) return 0; if (fputs("CONTENT_LENGTH", fp) < 0) return 0; if (fputc('\0', fp) == EOF) return 0; if (fputs(getenv("CONTENT_LENGTH"), fp) < 0) return 0; if (fputc('\0', fp) == EOF) return 0; for (p = environ; *p != NULL; *p++) { char *eq = strchr(*p, '='); if (eq == NULL) continue; if (!strncmp(*p, "CONTENT_LENGTH=", 15)) continue; n = eq - *p; if (fwrite(*p, 1, n, fp) < n) return 0; if (fputc('\0', fp) == EOF) return 0; if (fputs(eq + 1, fp) < 0) return 0; if (fputc('\0', fp) == EOF) return 0; } if (fputc(',', fp) == EOF) return 0; return 1; } static int copyfp(FILE *in, FILE *out) { size_t n, n2; char buf[8000]; for (;;) { n = fread(buf, 1, sizeof buf, in); if (n != sizeof buf && ferror(in)) return 0; if (n == 0) break; /* EOF */ n2 = fwrite(buf, 1, n, out); if (n2 != n) return 0; } return 1; } int main(int argc, char **argv) { int sock, fd; FILE *fp; sock = open_socket(); /* send request */ if ((fd = dup(sock)) < 0) die_perror("duplicating fd"); if ((fp = fdopen(fd, "w")) == NULL) die_perror("creating buffered file"); if (!send_headers(fp)) { die_msg("sending request headers"); } if (!copyfp(stdin, fp)) { die_msg("sending request body"); } if (fclose(fp) != 0) die_perror("sending request body"); /* send reponse */ if ((fd = dup(sock)) < 0 || (fp = fdopen(fd, "r")) == NULL) die_perror("creating buffered file from socket"); if (!copyfp(fp, stdout)) { die_msg("sending response"); } if (fclose(fp) != 0) die_perror("closing socket"); return 0; }
C
#include <stdio.h> int index_array[9] = {0,}; int order_array[9] = {0,}; void number_array(int N,int M,int count){ if(M ==count){ for (int i = 0; i < M; ++i) { if(order_array[i]) printf("%d ",order_array[i]); } printf("\n"); } else{ for (int i = 1; i <= N; ++i) { if(index_array[i] == 0){ index_array[i] = 1; order_array[count] = i; number_array(N,M,++count); order_array[count] = 0; index_array[i] = 0; count--; } } } } int main() { int N,M; scanf("%d %d",&N,&M); number_array(N,M,0); }
C
/*------------------------------------------------- //Date: 10.12.2020 //Autor: Vlaimir Draga //S. Prata. Chapter 14 //Programming exercise 10 //------------------------------------------------- /* Text programmming exersice. 10. Write a program that implements a menu by using an array of pointers to functions. For instance, choosing a from the menu would activate the function pointed to by the first element of the array. */ #include <stdio.h> #include <string.h> void func1(void); void func2(void); void func3(void); char showmenu(void); int main(void) { void (* fp[3])(void) = {func1, func2, func3}; char choice; while ((choice = showmenu()) != '\n') { switch (choice) { case 'a': fp[0](); break; case 'b': fp[1](); break; case 'c': fp[2](); break; default: break; } } return 0; } void func1(void) { printf("func1\n"); } void func2(void) { printf("func2\n"); } void func3(void) { printf("func3\n"); } char showmenu(void) { char answer; puts("Enter menu choice:"); puts("a) func1"); puts("b) func2"); puts("c) func3"); answer = getc(stdin); while(strchr("abc", answer) == NULL) { printf("Input only a,b or c"); answer = getchar(); } return answer; }
C
#include <stdio.h> int main(int argc,char *argv[]) { int integerOne, integerTwo, integerThree; printf("Input the first integer: "); scanf("%d",&integerOne); printf("Input the second integer: "); scanf("%d",&integerTwo); printf("Input the third integer: "); scanf("%d",&integerThree); if(integerOne > integerTwo && integerOne > integerThree) { printf("The max integer is: %d\n",integerOne); } else if( integerTwo > integerThree && integerTwo > integerOne) { printf("The max integer is: %d\n",integerTwo); } else if(integerThree > integerOne && integerThree > integerTwo) { printf("The max integer is: %d\n",integerThree); } return 0; }
C
/* * DA4B_T1.c * * Created: 4/18/2019 1:30:14 PM * Author : victor */ #define F_CPU 16000000UL #include <avr/io.h> #include <util/delay.h> #include <avr/interrupt.h> void adc_initializer(void); // void function we will use for ADC void slow_the_freak_up(void); // does this to begin slowing down the motor void whats_the_speed(void); // checks what is the speed with the potentiometer volatile unsigned int speed_motor; // variable used to control the speed of the motor volatile int stop_motor = 0; // if 1, the motor will stop int main(void) { DDRB = 0b1111; //Enable output on all of the B pins PORTB = 0b0000; // makes the fisrt value 0 adc_initializer(); // initialize ADC TCCR1B = 0b11010; // set CTC mode and 1024 prescaler ICR1 = 62258; // fast Pulse Width Modulation while(1) { whats_the_speed(); // checks what is the speed with the potentiometer OCR1A = speed_motor; // set OCR1A to the determined speed TCNT1 = 0x00; // reset the clock if(stop_motor == 0) // leads to the motor stopping { slow_the_freak_up(); // calls the function to slow down } } } void adc_initializer(void) //initialize ADC { ADMUX = (0<<REFS1)|(0<<REFS0); // ADC Enable ADCSRA = (1<<ADEN)| (1<<ADSC)| (1<<ADATE)| (0<<ADIF)| // ADC Start Conversion (0<<ADIE)| (1<<ADPS2)|(1<<ADPS1)| (1<<ADPS0); // ADC Auto Trigger Enable // ADC Interrupt Flag // ADC Interrupt Enable // ADC Prescaler Select Bits // ADC Prescaler select bits // ADC input // Timer/Counter1 Interrupt Mask Register } void slow_the_freak_up(void) { // does this to begin slowing down the motor while((TIFR1 & 0x2) != 0b0010); PORTB = 0x09; TIFR1 |= (1<<OCF1A); while((TIFR1 & 0x2) != 0b0010); PORTB = 0x03; TIFR1 |= (1<<OCF1A); while((TIFR1 & 0x2) != 0b0010); PORTB = 0X06; TIFR1 |= (1<<OCF1A); while((TIFR1 & 0x2) != 0b0010); PORTB = 0X0C; TIFR1 |= (1<<OCF1A); } void whats_the_speed(void) { // reads at what speeds the motor is while((ADCSRA&(1<<ADIF))==0); if (ADC >= 820){ stop_motor = 1;} if ((ADC < 820) && (ADC >= 617)) { stop_motor = 0; speed_motor = 0x1869;} if ((ADC < 617) && (ADC >= 414)) { stop_motor = 0; speed_motor = 0x124F;} if ((ADC < 414) && (ADC >= 211)) { stop_motor = 0; speed_motor = 0x0C34;} if ((ADC < 211) && (ADC >= 000)) { stop_motor = 0; speed_motor = 0x061A;} }
C
#include<stdio.h> #include<string.h> #include<pthread.h> #include<stdlib.h> #include<unistd.h> pthread_t tid1; pthread_t tid2; int status; FILE *fp; FILE *fq; int hitung(char* String, char *str){ int count=0; char* Temp = String; while(Temp != NULL){ Temp=strstr(Temp,str); if(Temp){ Temp++; count++; } } return count; } char kata[1000]; char kata2[1000]; void* count_Ifah(void *arg){ status = 0; fp = fopen("/home/ilham/modul3/Novel.txt", "r"); char kata[1000]; char cari[5]="Ifah"; int countifah=0; while(fgets(kata,1000,fp)!=NULL){ countifah+=hitung(kata,cari); } status=1; fclose(fp); printf("IFAH=%d\n", countifah); } void* count_Fina(void *arg){ while(status != 1){ } fq = fopen ("/home/ilham/modul3/Novel.txt", "r"); char cari[5]="Fina"; int countfina=0; while(fgets(kata2,2000,fq)!=NULL){ countfina+=hitung(kata2,cari); } fclose(fq); printf("Fina=%d\n", countfina); } int main(void){ pthread_create(&(tid1), NULL, &count_Fina, NULL); pthread_create(&(tid2), NULL, &count_Ifah, NULL); pthread_join(tid1, NULL); pthread_join(tid2,NULL); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jcsantos <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/10/05 13:44:19 by juasanto #+# #+# */ /* Updated: 2021/03/15 17:15:45 by jcsantos ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/libft.h" void ft_strdel(char **string) { if (string != NULL && *string != NULL) { free(*string); *string = NULL; } } int ft_add(char **read_fd, int fd, char **line) { int count; char *tmp1; count = 0; while (read_fd[fd][count] != '\n') count++; *line = ft_substr(read_fd[fd], 0, count); tmp1 = ft_strdup(&read_fd[fd][count + 1]); free(read_fd[fd]); read_fd[fd] = tmp1; return (1); } int fn_return(char **line, int fd, char **read_fd, ssize_t bytes_read) { if (bytes_read < 0) return (-1); else if (bytes_read == 0 && (read_fd[fd] == NULL || read_fd[fd][0] == '\0')) { *line = ft_strdup(""); ft_strdel(&read_fd[fd]); return (0); } else if (ft_strchr(read_fd[fd], '\n')) return (ft_add(read_fd, fd, line)); else { *line = ft_strdup(read_fd[fd]); ft_strdel(&read_fd[fd]); return (0); } } void read_buffer(char *buffer, int bytes_read, char **read_fd, int fd) { char *tmp; tmp = NULL; buffer[bytes_read] = '\0'; if (read_fd[fd] == NULL) read_fd[fd] = ft_strdup(buffer); else { tmp = ft_strjoin(read_fd[fd], buffer); free(read_fd[fd]); read_fd[fd] = tmp; } } int get_next_line(int fd, char **line) { char *buffer; ssize_t bytes_read; static char *read_fd[4096]; buffer = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1)); if (fd < 0 || line == 0 || BUFFER_SIZE < 1 || (!buffer)) return (-1); bytes_read = read(fd, buffer, BUFFER_SIZE); while (bytes_read > 0) { read_buffer(buffer, bytes_read, read_fd, fd); if (ft_strchr(read_fd[fd], '\n') != 0) break ; bytes_read = read(fd, buffer, BUFFER_SIZE); } free(buffer); return (fn_return(line, fd, read_fd, bytes_read)); }
C
#include<stdio.h> int main() { int T; scanf_s("%d", &T); int a, b, j, t; for (int i = 0; i < T; i++) { scanf_s("%d %d", &a, &b); if (a < b) { t = a; a = b; b = t; } j = 1; while (1) { if ((b * j)%a==0) { printf("%d\n", b*j); break; } j++; } } return 0; }
C
/* Name: number.c Purpose: Perform add operations on a natural given number */ #include <stdio.h> #include "number.h" /* Name: sum_of_first_with_for Purpose: Compute the sum of the first N natural numbers using for Params: IN num - number Returns: a variable int representing sum */ int sum_of_first_with_for(int num) { int sum = 0; int i; for (i = 1; i <= num; ++i) { sum += i; } return sum; } /* sum_of_first_with_for */ /* Name: sum_of_first_with_while Purpose: Compute the sum of the first N natural numbers using while Params: IN num - number Returns: a variable int representing sum */ int sum_of_first_with_while(int num) { int sum = 0; int i = 1; while (i <= num) { sum += i; ++i; } return sum; } /* sum_of_first_with_while */ /* Name: sum_of_first_even_with_for Purpose: Compute the sum of the first N natural even numbers using for Params: IN num - number Returns: a variable int representing sum of even numbers */ int sum_of_first_even_with_for(int num) { int sum = 0; int i; for (i = 1; i <= num; ++i) { if (i % 2 == 0) { sum += i; } } return sum; } /* sum_of_first_even_with_for */ /* Name: sum_of_first_odd_with_while Purpose: Compute the sum of the first N natural odd numbers using while Params: IN num - number Returns: a variable int representing sum of odd numbers */ int sum_of_first_odd_with_while(int num) { int sum = 0; int i = 1; while (i <= num) { if (i % 2 == 1) { sum += i; } ++i; } return sum; } /* sum_of_first_odd_with_while */
C
#include <stdio.h> #include <windows.h> #include <assert.h> void ReverseString(char *str) { assert(str); char *start = str; char *end = str + strlen(str) - 1; while (start < end){ char temp = *start; *start = *end; *end = temp; start++, end--; } } int main() { char str[] = "abcd1234"; printf("Befor: %s\n", str); ReverseString(str); printf("After: %s\n", str); system("pause"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "paises.h" #include <string.h> #include <time.h> ePais* nuevo_Pais() { return (ePais*) malloc(sizeof(ePais)); } //--------------------------------------------------------------------------------------------------- ePais* paisesParametros(char* idStr, char* nombreStr, char* recuperadosStr, char* infectadosStr, char* muertosStr) { ePais* nPais = NULL; nPais = nuevo_Pais(); if(muertosStr != NULL && idStr != NULL && nombreStr != NULL && recuperadosStr != NULL && infectadosStr != NULL) { if(pais_setId(nPais, atoi(idStr)) == -1 || pais_setNombre(nPais, nombreStr) == -1 || pais_setRecuperados(nPais, atoi(recuperadosStr)) == -1 || pais_setInfectados(nPais, atoi(infectadosStr)) == -1 || pais_setMuertos(nPais, atoi(muertosStr)) == -1) { borrar_pais(nPais); nPais = NULL; } else { pais_setId(nPais, atoi(idStr)); pais_setNombre(nPais, nombreStr); pais_setRecuperados(nPais, atoi(recuperadosStr)); pais_setInfectados(nPais, atoi(infectadosStr)); pais_setMuertos(nPais, atoi(muertosStr)); } } return nPais; } //--------------------------------------------------------------------------------------------------- int borrar_pais(ePais* this) { int exito = 1; if(this != NULL) { free(this); exito = 0; } return exito; } //--------------------------------------------------------------------------------------------------- //------------------------------------------ SETTERS ------------------------------------------------ int pais_setId(ePais* this, int id) { int exito = 1; if(this != NULL && id > 0) { this->id = id; exito = 0; } return exito; } //------------------------------------------------------------------ int pais_setNombre(ePais* this, char* nombre) { int exito = 1; if(this != NULL && nombre != NULL) { strncpy(this->nombre, nombre, 128); exito = 0; } return exito; } //------------------------------------------------------------------ int pais_setRecuperados(ePais* this, int recuperados) { int exito = 1; if(this != NULL && recuperados >= 0) { this->recuperados = recuperados; exito = 0; } return exito; } //------------------------------------------------------------------ int pais_setInfectados(ePais* this, int infectados) { int exito = 1; if(this != NULL && infectados >= 0) { this->infectados = infectados; exito = 0; } return exito; } //------------------------------------------------------------------ int pais_setMuertos(ePais* this, int muertos) { int exito = 1; if(this != NULL && muertos >= 0) { this->muertos = muertos; exito = 0; } return exito; } //--------------------------------------------------------------------------------------------------- //------------------------------------------ GETTERS ------------------------------------------------ int pais_getId(ePais* this, int* id) { int exito = 1; if(this != NULL && id != NULL) { *id = this->id; exito = 0; } return exito; } //------------------------------------------------------------------ int pais_getNombre(ePais* this, char* nombre) { int exito = 1; if(this != NULL && nombre != NULL) { strncpy(nombre, this->nombre, 128); exito = 0; } return exito; } //------------------------------------------------------------------ int pais_getRecuperados(ePais* this, int* recuperados) { int exito = 1; if(this != NULL && recuperados != NULL) { *recuperados = this->recuperados; exito = 0; } return exito; } //------------------------------------------------------------------ int pais_getInfectados(ePais* this, int* infectados) { int exito = 1; if(this != NULL && infectados != NULL) { *infectados = this->infectados; exito = 0; } return exito; } //------------------------------------------------------------------ int pais_getMuertos(ePais* this, int* muertos) { int exito = 1; if(this != NULL && muertos != NULL) { *muertos = this->muertos; exito = 0; } return exito; } //--------------------------------------------------------------------------------------------------- int mostrarPais(LinkedList* pLista, int indice) { int auxId; char auxNombre[128]; int auxRecuperados; int auxInfectados; int auxMuertos; int exito = 1; ePais* pPais; if(pLista != NULL && indice >= 0) { pPais = ll_get(pLista, indice); pais_getId(pPais, &auxId); pais_getNombre(pPais, auxNombre); pais_getRecuperados(pPais, &auxRecuperados); pais_getInfectados(pPais, &auxInfectados); pais_getMuertos(pPais, &auxMuertos); printf("%-5d \t%-30s %-20d \t%-20d \t%-30d \n", auxId, auxNombre, auxRecuperados, auxInfectados, auxMuertos); exito = 0; } else if(exito == 1) { printf("Error\n"); } return exito; } //--------------------------------------------------------------------------------------------------- //------------------------------------------ GETTERS ------------------------------------------------ int cantidad_getRecuperados(void) { int aleatorio; aleatorio = rand()% 50000 + 950001; return aleatorio; } //--------------------------------------------------------------------------------------------------- int cantidad_getInfectados(void) { int aleatorio; aleatorio = rand()% 40000 + 1960001; return aleatorio; } //--------------------------------------------------------------------------------------------------- int cantidad_getMuertos(void) { int aleatorio; aleatorio = rand()% 1000 + 49001; return aleatorio; } //--------------------------------------------------------------------------------------------------- //------------------------------------------ SETTERS ------------------------------------------------ void* set_cantRecuperados(void* recuperados) { ePais* recuperado = NULL; if(recuperados != NULL) { recuperado = (ePais*)recuperados; pais_setRecuperados(recuperado, cantidad_getRecuperados()); } return recuperado; } //--------------------------------------------------------------------------------------------------- void* set_cantInfectados(void* infectados) { ePais* infectado = NULL; if(infectados != NULL) { infectado = (ePais*)infectados; pais_setInfectados(infectado, cantidad_getInfectados()); } return infectado; } //--------------------------------------------------------------------------------------------------- void* set_cantMuertos(void* muertos) { ePais* muerto = NULL; if(muertos != NULL) { muerto = (ePais*)muertos; pais_setMuertos(muerto, cantidad_getMuertos()); } return muerto; } //--------------------------------------------------------------------------------------------------- int filtrarxExitosos(void* paisExitoso) { int auxReturn = 0; ePais* x; if(paisExitoso != NULL) { x = (ePais*) paisExitoso; if(x->muertos < 5000) { auxReturn = 1; } } return auxReturn; } //--------------------------------------------------------------------------------------------------- int filtrarxPerjudicados(void* paisPerjudicado) { int auxReturn = 0; ePais* x; if(paisPerjudicado != NULL) { x = (ePais*) paisPerjudicado; if(x->infectados >= (x->recuperados * 3)) { auxReturn = 1; } } return auxReturn; } //--------------------------------------------------------------------------------------------------- int ordenarPaisxInfectados(void* x, void* y) { int cambio; int infectadosUno; int infectadosDos; pais_getInfectados(x, &infectadosUno); pais_getInfectados(y, &infectadosDos); if(infectadosUno > infectadosDos) { cambio = 1; } else if(infectadosUno < infectadosDos) { cambio = -1; } return cambio; }
C
/* Do not remove the headers from this file! see /USAGE for more info. */ #define XP_FACTOR 250 void save_me(); private int level = 1; private int experience = 0; private int xp_modifier; private nosave int guild_xp_buff; void set_level(int x) { level = x; } int query_level() { return level; } void raise_level() { set_level(query_level() + 1); write("Congratulations! You gained a level!\n"); } int query_experience() { return experience; } void set_guild_xp_buff(int buff) { if (buff > guild_xp_buff) { guild_xp_buff = buff; tell(this_object(), "%^COMBAT_CONDITION%^You received an XP buff of " + buff + "%%^RESET%^.\n"); } } void clear_guild_xp_buff(int buff) { guild_xp_buff = 0; tell(this_object(), "%^COMBAT_CONDITION%^Your XP buff fades.%^RESET%^\n"); } int query_guild_xp_buff() { return guild_xp_buff; } void set_experience(int x) { experience = x; if (this_body()->query_link()) this_body()->save_me(); } void remove_experience(int x) { int old_level, min_xp, old_xp; old_level = query_level(); min_xp = 0; old_xp = experience; experience -= x; if (experience < min_xp) experience = min_xp; if ((old_xp - experience) > 0) tell(this_object(), "%^RED%^You lost " + (old_xp - experience) + " xp.%^RESET%^\n"); if (this_object()->query_link()) save_me(); } void add_experience(int x) { int old_level, new_level; old_level = query_level(); // TBUG("Adding XP to" + this_object() + ": " + x + " / Link: " + this_object()->query_link()); experience += x; tell(this_object(), "%^YELLOW%^You gained " + x + " xp.%^RESET%^\n"); if (this_object()->query_link()) save_me(); } int skill_xp_plus() { int total; foreach (int skill in values(this_object()->query_skills())) total += skill; return total; } //: FUNCTION calc_xp_for // int calc_xp_for(int player_level, int monster_level) // Decoupled function to allow external XP calculation. int calc_xp_for(int player_level, int monster_level) { int callerLevel = player_level > 0 ? player_level : 1; int xp; float multFactor = (((0.0 + monster_level) / callerLevel)); if (multFactor > 1.0) multFactor = ((multFactor - 1) * 2) + 1; xp = to_int(floor((1.0 + (monster_level / 1.0)) * ((XP_FACTOR / 15)) * (multFactor > 2.0 ? 2.0 : multFactor))); // TBUG("***: "+multFactor); // handling global xp modifier // xp = to_int(xp * GAME_D->query_global_xp_mult()); return xp > 0 ? xp : 1; } //: FUNCTION xp_value // int xp_value() // Calculate XP value for monsters (and players). The function reduces XP for monsters if the player // is too high level compared to the monster. It rewards players up to 20% if the monster is higher than // their level. The function always returns 1 point as a minimum (sad). varargs int xp_value(object xp_for) { int xp; if (!xp_for) xp_for = previous_object(); xp = calc_xp_for(xp_for->query_could_be_level(), this_object()->query_could_be_level()); xp = to_int(xp * (1.0 + (xp_for->query_guild_xp_buff() / 100.0))); // Only needed for debug // int callerLevel = previous_object()->query_could_be_level() > 0 ? previous_object()->query_could_be_level() : 1; // TBUG("Caller level:" + callerLevel + " This level: " + this_object()->query_level()); return xp; } int query_xp_modifier() { return xp_modifier; } void set_xp_modifier(int n) { xp_modifier = n; } int query_xp_for_level(int lev) { int level = query_level() - 1; if (lev) level = lev; return XP_FACTOR * pow(level, 2) - XP_FACTOR * level; } int query_next_xp() { return query_xp_for_level(query_level() + 1); } int query_level_for_xp(int xp) { if (!xp) xp = experience; return to_int(XP_FACTOR + sqrt(XP_FACTOR * XP_FACTOR - 4 * XP_FACTOR * (-xp))) / (2 * XP_FACTOR); } int query_could_be_level() { return (this_object()->is_body() ? query_level_for_xp(experience) : query_level()); }
C
// sets.h -- operators on sets of up to 32 elements // by: Douglas W. Jones // users of this must first include <stdint.h> // the set data type typedef uint32_t set32_t; // set32_t TO_SET32( int i ) #define TO_SET32(i) (((set32_t)1)<<(i)) // constructs a new set from one integer // bool IN_SET32( int i, set32_t s ) #define IN_SET32(i,s) (TO_SET32(i) & s) // test for set membership // set constructors for larger constant-valued sets #define TO_SET32_2(i,j) (TO_SET32(i) | TO_SET32(j)) #define TO_SET32_3(i,j,k) (TO_SET32(i) | TO_SET32_2(j,k)) #define TO_SET32_4(i,j,k,l) (TO_SET32_2(i,j) | TO_SET32_2(k,l)) // on sets, the & operator means set intersection // the | operator means set union
C
/** * @file * @brief Application to manage phone contacts * @author Alejandro Brugarolas * @since 2019-05 */ #include <stdio.h> #include "model/structs.h" #include "functions/Contact.h" /** * Shows all the options and calls the appropriate function depending of the chosen option */ void showMenu(contact *contacts) { int option = 0; while (option != 3) { printf("\n############### MENU BOLETÍN 4 EJERCICIO 1 ###############\n" "Indique que acción desea realizar\n" "\t1. Crear contacto nuevo\n" "\t2. Buscar contacto\n" "\t3. Salir\n"); printf("> "); scanf("%d", &option); fflush(stdin); switch (option) { case 1: contacts = addContactOption(contacts); break; case 2: findContactOption(contacts); break; case 3: printf("Saliendo..."); break; default: printf("Por favor seleccione una opción válida\n"); break; } } } int main() { contact *contacts = NULL; showMenu(contacts); destroyBook(contacts); }
C
//musl-libc #include "stdio.h" #include "stdlib.h" #include "signal.h" #include "sys/stat.h" #include "errno.h" #include "syscall.h" #include "time.h" #include "unistd.h" #include "string.h" //$(pwd)/include #include "vars.h" #include "pthread.h" #define THREAD_NUM 8 //#define TOTAL_MEM 0x3ffd0000 #define TOTAL_MEM 0x1ffd0000 //#define TOTAL_MEM 0xffd0000 //#define TOTAL_MEM 0x7fd0000 char *inner_start; char *outer_start; unsigned long offset; static void *func(void *arg) { char *src; char *dst; long id; id = (long)arg; src = inner_start + offset * id; dst = outer_start + offset * id; //printf("Copy Thread: %ld, src: 0x%lx, dst 0x%lx, size 0x%lx\n", id, (unsigned long)src, // (unsigned long)dst, offset); memcpy(dst, src, offset); return (void*)0; } int main(int argc, char* argv[]) { pthread_t thread[THREAD_NUM]; unsigned long i; unsigned long threads; threads = atoi(argv[1]); //printf("create %ld threads\n", threads); inner_start = (char*)&enclave_start; outer_start = (char*)0x600000000000; offset = TOTAL_MEM / threads; for(i = 0; i < threads; ++i) { //sleep(1); pthread_create(&(thread[i]), NULL, func, (void*)i); } for(i = 0; i < threads; ++i) pthread_join(thread[i], NULL); return 0; } #if 0 int main(int argc, char* argv[]) { int msg_cnt; msg_cnt = 0; while(1) { printf("This is the No.%d message from the app\n", ++msg_cnt); sleep(1); } return 0; } #endif
C
#include <stdio.h> int a[8] = { 0, 1, 2, 3, 0, 1, 2, 3 }; char b[5]; char c[3]; char d; int main() { char x[5], y[3], z[7]; printf("sizeof(char) %lu, sizeof(int) %lu, sizeof(long) %lu\n" "sizeof(a) %lu, sizeof(c) %lu\n" "address of a[0] %p\naddress of b[0] %p\n" "address of c[0] %p\naddress of d %p\n" "address of x[0] %p\naddress of y[0] %p\n" "address of z[0] %p\n", sizeof(char), sizeof(int), sizeof(long), sizeof(a), sizeof(c), &a[0], &b[0], &c[0], &d, x, y, z); }
C
#include <stdio.h> #include <string.h> #define BUFSIZE 100 int buf[BUFSIZE]; int bufp = 0; int value = EOF; int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } void ungetch(int c) { if (bufp >= BUFSIZE) printf("ungetch: too many characters\n"); else buf[bufp++] = c; } void ungetchs(char s[]) { int len = strlen(s); while (len > 0) { ungetch(s[--len]); } } int getchOne(void) { if (value != EOF) { int temp = value; value = EOF; return temp; } else return getchar(); } void ungetchOne(int c) { if (value != EOF) printf("ungetchOne: cannot ungetch more char\n"); else value = c; }
C
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <stdlib.h> #define MAX_LENGTH 256 struct Operands { int x, y; }; //Exercise 1. int main(void){ int fd[2]; pid_t pid; if (pipe(fd) == -1){ //Opens pipe. perror("Pipe error"); exit(1); } if ((pid = fork()) == -1){ perror("Fork error"); exit(1); } if (pid > 0){ //Parent process. //int nums[2]; //struct Operands op; char x[MAX_LENGTH], y[MAX_LENGTH]; printf("x & y : "); //scanf("%i %i", &nums[0], &nums[1]); //scanf("%i %i", &op.x, &op.y); scanf("%s %s", x, y); close(fd[0]); //Closes read. //write(fd[1], nums, 2 * sizeof(int)); //Writes to 'child read' an array of two integers. //write(fd[1], &op, 2 * sizeof(op)); //Struct should have the same size of two ints, but for the sake of consistency. write(fd[1], x, MAX_LENGTH); write(fd[1], y, MAX_LENGTH); close(fd[1]); //Closes write. } if (pid == 0){ //Child process. //int nums[2]; //struct Operands op; char x[MAX_LENGTH], y[MAX_LENGTH]; int lastDig, xInt, yInt; //Didn't bother to save as double. This being int results in integer quotient. close(fd[1]); //Closes write. //read(fd[0], nums, 2 * sizeof(int)); //Reads the two integers from 'child read'. //read(fd[0], &op, 2 * sizeof(op)); lastDig = read(fd[0], x, MAX_LENGTH); x[lastDig] = 0; lastDig = read(fd[0], y, MAX_LENGTH); y[lastDig] = 0; xInt = atoi(x); yInt = atoi(y); //printf("Sum: %i\nSub: %i\nMul: %d\nDiv: %d\n", nums[0] + nums[1], nums[0] - nums[1], nums[0] * nums[1], nums[0] / nums[1]); //printf("Sum: %i\nSub: %i\nMul: %d\nDiv: %d\n", op.x + op.y, op.x - op.y, op.x * op.y, op.x / op.y); printf("Sum: %i\nSub: %i\nMul: %d\nDiv: %d\n", xInt + yInt, xInt - yInt, xInt * yInt, xInt / yInt); close(fd[0]); //Closes read. } }
C
#include "pic.h" void pic_acknowledge(uint8_t _interrupt) { // If handled by slave, acknowledge this if (_interrupt >= PIC_SLAVE_START_INTERRUPT && _interrupt <= PIC_SLAVE_END_INTERRUPT) out_byte(PIC_SLAVE_COMMAND_PORT, PIC_ACKNOWLEDGE); out_byte(PIC_MASTER_COMMAND_PORT, PIC_ACKNOWLEDGE); } void pic_enable(uint8_t _vector) { uint8_t offset = _vector > 7 ? _vector - 8 : _vector; uint8_t data_port = _vector > 7 ? PIC_SLAVE_DATA_PORT : PIC_MASTER_DATA_PORT; // Read current configuration and change position uint8_t flags; in_byte(data_port, &flags); out_byte(data_port, flags | (1 << offset)); } void pic_disable(uint8_t _vector) { uint8_t offset = _vector > 7 ? _vector - 8 : _vector; uint8_t data_port = _vector > 7 ? PIC_SLAVE_DATA_PORT : PIC_MASTER_DATA_PORT; // Read current configuration and change position uint8_t flags; in_byte(data_port, &flags); out_byte(data_port, flags & ~(1 << offset)); }
C
// htab_move.c // Riesenie IJC-DU2, priklad b), 20. 4. 2021 // Autor: Tomas Valent // Prekladac: gcc 9.3 // Move konstruktor hash tabulky #include "htab.h" #include "htab_struct.h" htab_t *htab_move(size_t number, htab_t *t2) { htab_t *table = htab_init(number); //nova tabulka so zadanou velkostou if(table == NULL) return NULL; for(size_t i; i < table->arr_size; i++) //presun do novej tabulky { struct htab_item *tmp = table->arr[i]; if(table->arr[i] != NULL) { size_t hash = htab_hash_function(table->arr[i]->pair.key); size_t newIndex = hash % t2->arr_size; while(tmp) { t2->arr[newIndex] = tmp; if(tmp->next != NULL) tmp = tmp->next; else break; } } } return table; }
C
/* * myio.c * Trey Oehmler * CS315 Assignment 2 Fall 2018 */ #include "myio.h" #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/uio.h> #include <string.h> struct tfile *myopen(const char *path, int flags) { /* initalizes new tfile * returns ptr to tfile, or NULL on err */ int fd = open(path, flags, 0666); if (fd == -1) { return NULL; } struct tfile *ret_file = malloc(sizeof(struct tfile)); if (!ret_file) { return NULL; // malloc(2) error } ret_file->fd = fd; ret_file->rw_flag = 0; ret_file->file_off = 0; ret_file->rd_off = 0; ret_file->rd_count = 0; ret_file->wr_count = 0; return ret_file; } off_t myseek(struct tfile *file, off_t offset, int whence) { /* repositions file offset by calling lseek(2) * absolute or relative dependent on whence * rets new offset or -1 on error */ off_t new_off; if (file->rw_flag == 2) { myflush(file); } if (whence == SEEK_SET) { new_off = lseek(file->fd, offset, SEEK_SET); } else { // whence == SEEK_CUR new_off = lseek(file->fd, (offset + file->file_off), SEEK_SET); } if (new_off != -1) { file->file_off = new_off; file->rd_count = 0; file->rd_off = 0; file->rw_flag = 0; } return new_off; } ssize_t myflush(struct tfile *file) { /* write any data in wbuf to file * rets number of bytes written or -1 on err */ if (file->wr_count == 0) { return 0; } ssize_t bytes_wr = write(file->fd, file->wbuf, file->wr_count); if (bytes_wr != -1) { file->file_off += bytes_wr; file->wr_count = 0; } return bytes_wr; } ssize_t myread(struct tfile *file, void *outbuf, size_t count) { /* calls read() to fill rbuf of file * copies data to outbuf * returns number of bytes copied to outbuf */ ssize_t bytes_rd; if (file->rw_flag == 2) { myflush(file); } file->rw_flag = 1; int increment; if (count <= file->rd_count) { // copy to usrbuf from rbuf memcpy(outbuf, (char *)file->rbuf + file->rd_off, count); increment = count; } else if (count <= BUFFER_SIZE) { // move rem bytes to start of rbuf memmove(file->rbuf, (char *)file->rbuf + file->rd_off, file->rd_count); file->rd_off = 0; // call read(2) to fill rbuf size_t rd_req = BUFFER_SIZE - file->rd_count; bytes_rd = read(file->fd, (char *)file->rbuf + file->rd_count, rd_req); if (bytes_rd == -1) { return -1; } // copy to usrbuf from rbuf file->rd_count += bytes_rd; if (count > file->rd_count) { memcpy(outbuf, file->rbuf, file->rd_count); increment = file->rd_count; } else { memcpy(outbuf, file->rbuf, count); increment = count; } } else { // count > BUFFER_SIZE // call lseek(2) to reposition offset lseek(file->fd, file->file_off, SEEK_SET); // call read(2) to fill usrbuf w count bytes bytes_rd = read(file->fd, outbuf, count); if (bytes_rd == -1) { return -1; } // update offs / count for special case file->file_off += bytes_rd; file->rd_count = 0; file->rd_off = 0; return bytes_rd; } // update file_off, rd_off, rd_count file->file_off += increment; file->rd_count -= increment; file->rd_off += increment; return (ssize_t)increment; } ssize_t mywrite(struct tfile *file, void *inbuf, size_t count) { /* copies from inbuf to wbuf of file * write to file when neccesary * rets bytes written or -1 on error */ ssize_t bytes_wr; if (file->rw_flag == 1) { lseek(file->fd, file->file_off, SEEK_SET); file->rd_count = 0; file->rd_off = 0; } file->rw_flag = 2; if ((count + file->wr_count) > BUFFER_SIZE) { // write any remaining data in wbuf to file if (file->wr_count > 0) { bytes_wr = write(file->fd, file->wbuf, file->wr_count); if (bytes_wr == -1) { return -1; // write(2) error } file->file_off += bytes_wr; file->wr_count = 0; } } // perform syscall directly for overflow count if (count > BUFFER_SIZE) { bytes_wr = write(file->fd, inbuf, count); if (bytes_wr == -1) { return -1; // write(2) error } file->file_off += bytes_wr; return bytes_wr; } char *wr_start = (char *)file->wbuf + file->wr_count; memcpy(wr_start, inbuf, count); file->wr_count += count; return count; } int myclose(struct tfile *file) { /* flushes any remaining data in wbuf * closes a file by calling close(2) * returns 0 on successful close, -1 otherwise */ myflush(file); int ret = close(file->fd); if (ret < 0) { return -1; } else { free(file); return 0; } }
C
/* Vamos a entender el funcionamiento de la sentencia SWITCH con su DEFAULT. Es como comparar IF con su ELSE. Este es el esquema que sigue switch: switch (variable){ caso var1 : sentencias1;break; caso var2 : sentencias2;break; caso var3 : sentencias3;break; default: sentencias; } */ #include <stdio.h> //Existen muchos tipos de librerías, las cuales nos otorgan la capacidad de realizar funciones, y se añaden precedidas por #include. "stdio" significa "standard input output" y ".h" significa "header". Nos sirve para poder poner cosas en pantalla y guardar datos. int main (){ //Esta es la función principal (main) que vamos a crear. "Int" quiere decir que es un número entero. char vocal; //Establecemos la variable local vocal, que al ser un caracter sentenciamos como char. printf("Introduce una vocal: "); //Parte textual en la que pedimos al usuario que introduzca la vocal a elegir. scanf("%c",&vocal); //Mediante el scanf permitimos que el usuario pueda introducir la vocal deseada (%c), y guardarla como la variable vocal (&vocal). switch(vocal){ //Utilizamos switch para diferenciar cada caso. En caso de que se elija la a, imprimirá en pantalla una confirmación distinta a si elige la b o la e. case 'a': printf("Es la vocal a");break; //Caso de que elija la a: Se imprime en pantalla confirmación. Es importante el break al final, dado que aisla las funciones de cada caso. case 'e': printf("Es la vocal e");break; //Caso de que elija la e: Se imprime en pantalla confirmación. Es importante el break al final, dado que aisla las funciones de cada caso. case 'i': printf("Es la vocal i");break; //Caso de que elija la i: Se imprime en pantalla confirmación. Es importante el break al final, dado que aisla las funciones de cada caso. case 'o': printf("Es la vocal o");break; //Caso de que elija la o: Se imprime en pantalla confirmación. Es importante el break al final, dado que aisla las funciones de cada caso. case 'u': printf("Es la vocal u");break; //Caso de que elija la u: Se imprime en pantalla confirmación. Es importante el break al final, dado que aisla las funciones de cada caso. default: printf("%c no es una vocal.",vocal); //Es buena costumbre establecer un default, para el momento en el que no se cumpla ningún caso. } /* case 1: printf("Es el número 1");break; case 2: printf("Es el número 2");break; case 3: printf("Es el número 3");break; */ //Si trabajamos con números, no haría falta '' después de case. return 0; //Gracias a poner return 0; podemos saber que la función ha terminado correctamente, y que nuestro programa no ha fallado en un punto a mitad de ejecución. Es una buena costumbre utilizarlo. }
C
/* ================================================================ */ /* Generate random instance of set covering problem */ /* Programmed by Shunji Umetani <[email protected]> */ /* Date: 2014/04/15 */ /* ================================================================ */ /* including files ------------------------------------------------ */ #include <stdlib.h> #include <stdio.h> #include <time.h> #include <math.h> /* definitions ---------------------------------------------------- */ #define INVALID -1 #define NUM_EPSILON 0.00001 #define MAX_COST 100 /* forwarded declarations ----------------------------------------- */ /* randomized suffle */ void random_shuffle(int n, int *idx); /* compare integers */ int cmp_int(const void* v1, const void* v2); /* mt19937ar */ void init_genrand(unsigned long s); unsigned long genrand_int32(void); double genrand_real2(void); /* functions ------------------------------------------------------ */ /* ---------------------------------------------------------------- */ /* Main function */ /* ---------------------------------------------------------------- */ int main(int argc, char *argv[]){ clock_t proc_start_time, proc_end_time; clock_t write_start_time, write_end_time; int var_num; /* number of variables */ int cvr_num; /* number of cover constraints */ int el_num; /* number of elements in cover constraints */ int *cost; /* cost coefficient of j-th variable */ int *var_num_cvr; /* number of variables covering i-th constraint */ int **var_idx_cvr; /* index list of variables covering i-th constraint */ double density; int seed; int *scan_ptr, *array, *temp_array; int h,i,j; /* check number of arguments */ if(argc != 5){ fprintf(stderr,"Invalid arguments!\n"); fprintf(stderr,"Usage: %s cvr_num var_num density\n",argv[0]); fprintf(stderr,"\tcvr_num: number of covering constraints\n"); fprintf(stderr,"\tvar_num: number of variables\n"); fprintf(stderr,"\tdensity: density of constraint matrix\n"); fprintf(stderr,"\tseed: seed of random number generator\n"); return(EXIT_FAILURE); } /* get arguments */ if(sscanf(argv[1],"%d", &cvr_num) != 1){ fprintf(stderr,"Can't get number of covering constraints!\n"); return(EXIT_FAILURE); }else if(cvr_num <= 0){ fprintf(stderr,"Invalid number of covering constraints!\n"); return(EXIT_FAILURE); } if(sscanf(argv[2],"%d", &var_num) != 1){ fprintf(stderr,"Can't get number of variables!\n"); return(EXIT_FAILURE); }else if(var_num <= 0){ fprintf(stderr,"Invalid number of variables!\n"); return(EXIT_FAILURE); } if(sscanf(argv[3],"%lf", &density) != 1){ fprintf(stderr,"Can't get density of constraint matrix!\n"); return(EXIT_FAILURE); }else if(density > 1.0 - NUM_EPSILON || density < NUM_EPSILON){ fprintf(stderr,"Invalid value of density!\n"); return(EXIT_FAILURE); } if(sscanf(argv[4],"%d", &seed) != 1){ fprintf(stderr,"Can't get seed of random number generator!\n"); return(EXIT_FAILURE); } /* initialize seed */ init_genrand(seed); /* start processing */ proc_start_time = clock(); /* set cost coefficients */ cost = (int *)malloc(var_num * sizeof(int)); for(j = 0; j < var_num; j++){ cost[j] = (int)(genrand_real2() * MAX_COST) + 1; } qsort(cost, var_num, sizeof(int), cmp_int); /* allocate memory */ var_num_cvr = (int *)malloc(cvr_num * sizeof(int)); var_idx_cvr = (int **)malloc(cvr_num * sizeof(int *)); el_num = (long long int)ceil((double)cvr_num * (double)var_num * density); var_idx_cvr[0] = (int *)malloc(el_num * sizeof(int)); /* set var_num_cvr */ h = 0; for(i = 0; i < cvr_num; i++){ var_idx_cvr[0][h] = var_idx_cvr[0][h+1] = i; h += 2; } for(; h < el_num; h++){ var_idx_cvr[0][h] = (int)(genrand_real2() * cvr_num); } for(i = 0; i < cvr_num; i++){ var_num_cvr[i] = 0; } for(h = 0; h < el_num; h++){ i = var_idx_cvr[0][h]; var_num_cvr[i]++; } /* set var_idx_cvr */ for(i = 1; i < cvr_num; i++){ var_idx_cvr[i] = var_idx_cvr[i-1] + var_num_cvr[i-1]; } scan_ptr = (int *)malloc(cvr_num * sizeof(int)); array = (int *)malloc(var_num * sizeof(int)); temp_array = (int *)malloc(var_num * sizeof(int)); for(i = 0; i < cvr_num; i++){ scan_ptr[i] = 0; } h = j = 0; while(j < var_num && h < el_num){ i = h % cvr_num; if(scan_ptr[i] < var_num_cvr[i]){ var_idx_cvr[i][scan_ptr[i]] = j; scan_ptr[i]++; j++; } h++; } if(j < var_num && h >= el_num){ fprintf(stderr,"Fail to generate instance!\n"); return(EXIT_FAILURE); } for(i = 0; i < cvr_num; i++){ for(j = 0; j < var_num; j++){ temp_array[j] = j; } for(h = 0; h < scan_ptr[i]; h++){ temp_array[var_idx_cvr[i][h]] = INVALID; } h = 0; for(j = 0; j < var_num; j++){ if(temp_array[j] != INVALID){ array[h] = temp_array[j]; h++; } } random_shuffle(var_num-scan_ptr[i], array); for(h = scan_ptr[i]; h < var_num_cvr[i]; h++){ var_idx_cvr[i][h] = array[h]; } qsort(var_idx_cvr[i], var_num_cvr[i], sizeof(int), cmp_int); } /* end processing */ proc_end_time = clock(); /* start writing */ write_start_time = clock(); /* output instance data */ fprintf(stdout,"%d\t%d\n",cvr_num,var_num); for(j = 0; j < var_num; j++){ fprintf(stdout,"%d ",cost[j]); } fprintf(stdout,"\n"); for(i = 0; i < cvr_num; i++){ printf("%d\t",var_num_cvr[i]); for(h = 0; h < var_num_cvr[i]; h++){ printf("%d ",var_idx_cvr[i][h]+1); /* CAUTION!: convert index of variable j=[0,...,n-1] -> j=[1,...,n] */ } printf("\n"); } /* end writing */ write_end_time = clock(); /* free memory */ free(array); free(temp_array); free(scan_ptr); free(cost); free(var_num_cvr); free(var_idx_cvr[0]); free(var_idx_cvr); /* print abstract */ fprintf(stderr,"Instance -----\n"); fprintf(stderr,"Number of constraints:\t%d\n",cvr_num); fprintf(stderr,"Number of variables:\t%d\n",var_num); fprintf(stderr,"Density:\t\t%g\n",density); fprintf(stderr,"Seed:\t\t\t%d\n",seed); /* print CPU time */ fprintf(stderr,"CPU time -----\n"); fprintf(stderr,"Processing time:\t%.3f sec\n", (double)(proc_end_time - proc_start_time) / CLOCKS_PER_SEC); fprintf(stderr,"Writing time:\t\t%.3f sec\n", (double)(write_end_time - write_start_time) / CLOCKS_PER_SEC); return(EXIT_SUCCESS); } /* ---------------------------------------------------------------- */ /* Randomized shuffle */ /* ---------------------------------------------------------------- */ void random_shuffle(int n, int *idx){ int i,j,t; for(i = n-1; i > 0; i--){ j = (int)(i * genrand_real2()); t = idx[i]; idx[i] = idx[j]; idx[j] = t; } } /* ---------------------------------------------------------------- */ /* Compare integers */ /* ---------------------------------------------------------------- */ int cmp_int(const void* v1, const void* v2){ const int _v1 = *((const int*)v1); const int _v2 = *((const int*)v2); if(_v1 > _v2){ return(1); }else if(_v1 < _v2){ return(-1); }else{ return(0); } } /* ---------------------------------------------------------------- */ /* A C-program for MT19937, with initialization improved 2002/1/26. */ /* Coded by Takuji Nishimura and Makoto Matsumoto. */ /* */ /* Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,*/ /* All rights reserved. */ /* Copyright (C) 2005, Mutsuo Saito, */ /* All rights reserved. */ /* ---------------------------------------------------------------- */ /* Period parameters */ #define N 624 #define M 397 #define MATRIX_A 0x9908b0dfUL /* constant vector a */ #define UPPER_MASK 0x80000000UL /* most significant w-r bits */ #define LOWER_MASK 0x7fffffffUL /* least significant r bits */ static unsigned long mt[N]; /* the array for the state vector */ static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */ /* initializes mt[N] with a seed */ void init_genrand(unsigned long s){ mt[0]= s & 0xffffffffUL; for(mti=1; mti<N; mti++){ mt[mti] = (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array mt[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ mt[mti] &= 0xffffffffUL; /* for >32 bit machines */ } } /* generates a random number on [0,0xffffffff]-interval */ unsigned long genrand_int32(void){ unsigned long y; static unsigned long mag01[2]={0x0UL, MATRIX_A}; /* mag01[x] = x * MATRIX_A for x=0,1 */ if(mti >= N){ /* generate N words at one time */ int kk; if(mti == N+1) /* if init_genrand() has not been called, */ init_genrand(5489UL); /* a default initial seed is used */ for(kk=0;kk<N-M;kk++){ y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL]; } for(;kk<N-1;kk++){ y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL]; } y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; mti = 0; } y = mt[mti++]; /* Tempering */ y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680UL; y ^= (y << 15) & 0xefc60000UL; y ^= (y >> 18); return y; } /* generates a random number on [0,1)-real-interval */ double genrand_real2(void){ return genrand_int32()*(1.0/4294967296.0); /* divided by 2^32 */ } /* ================================================================ */ /* End of file */ /* ================================================================ */
C
#include "pid.h" #include "hg_math.hpp" #include "hg_defines.h" #include <math.h> void PID_Init(PID_Controller *PID,float P,float I,float D) { PID->dt = 0.0f; PID->error_int = 0.0f; PID->error_now = 0.0f; PID->error_pre = 0.0f; PID->error_last = 0.0f; PID->feedback = 0.0f; PID->int_limit = 1000.0f; PID->kp = P; PID->ki = I; PID->kd = D; PID->output = 0; PID->setpoint = 0; PID->last_derivative = NAN; } float PID_Calc_Inc(PID_Controller *PID,float sp,float feedback,float dt) { register float Incpid; PID->feedback = feedback; PID->setpoint = sp; PID->error_now = PID->setpoint - feedback; PID->dt = dt; if(PID->dt == 0.0f) { PID->error_last = PID->error_pre; PID->error_pre = PID->error_now; } else { Incpid = PID->kp * (PID->error_now - PID->error_pre); Incpid = Incpid + PID->ki * PID->error_now * PID->dt; Incpid = Incpid + PID->kd * (PID->error_now - 2 * PID->error_pre + PID->error_last) / PID->dt; PID->output += Incpid; PID->error_last = PID->error_pre; PID->error_pre = PID->error_now; } return PID->output; } float PID_Calc_Loc(PID_Controller *PID,float sp,float feedback,float dt) { PID->setpoint = sp; PID->error_now = PID->setpoint - feedback; PID->dt = dt; PID->error_int += PID->error_now * PID->dt; if (PID->error_int > PID->int_limit) { PID->error_int = PID->int_limit; } else if (PID->error_int < -(PID->int_limit)) { PID->error_int = -(PID->int_limit); } if(PID->dt == 0.0f) { PID->error_pre = PID->error_now; PID->error_last = PID->error_pre; PID->output = 0; } else { PID->output = PID->kp * PID->error_now + PID->ki * PID->error_int + PID->kd * ((PID->error_now - PID->error_pre) / PID->dt); PID->error_pre = PID->error_now; PID->error_last = PID->error_pre; } return PID->output; } float PID_Calc_Loc_Error(PID_Controller *PID,float error,float dt) { PID->error_now = error; PID->dt = dt; PID->error_int += PID->error_now * PID->dt; if (PID->error_int > PID->int_limit) { PID->error_int = PID->int_limit; } else if (PID->error_int < -(PID->int_limit)) { PID->error_int = -(PID->int_limit); } if(PID->dt == 0.0f) { PID->error_pre = PID->error_now; PID->error_last = PID->error_pre; PID->output = 0; } else { PID->output = PID->kp * PID->error_now + PID->ki * PID->error_int + PID->kd * ((PID->error_now - PID->error_pre) / PID->dt); PID->error_pre = PID->error_now; PID->error_last = PID->error_pre; } return PID->output; } float get_i( PID_Controller* pid ,float error, float dt) { if((pid->ki != 0) && (dt != 0)) { if(isfinite(error)) { pid->error_int += ((float)error * pid->ki) * dt; } if (pid->error_int < -pid->int_limit) { pid->error_int = -pid->int_limit; } else if (pid->error_int > pid->int_limit) { pid->error_int = pid->int_limit; } if(!isfinite(pid->error_int)) { pid->error_int = 0; } return pid->error_int; } return 0; } float get_d( PID_Controller* pid , float error, float dt) { float derivative; if ((pid->kd != 0) && (dt != 0)) { if (isfinite(pid->last_derivative)) { // calculate instantaneous derivative derivative = (error - pid->error_last) / dt; } else { // we've just done a reset, suppress the first derivative // term as we don't want a sudden change in input to cause // a large D output change derivative = 0; pid->last_derivative = 0; } // discrete low pass filter, cuts out the // high frequency noise that can drive the controller crazy derivative = pid->last_derivative + pid->d_lpf_alpha * (derivative - pid->last_derivative); // update state pid->error_last = error; pid->last_derivative = derivative; // add in derivative component return pid->kd * derivative; } return 0; } float rate_to_motor_roll(PID_Controller *PID, float rate_target, float feedback, float dt, bool limit, bool thr_low) { float p,i,d; // used to capture pid values for logging float current_rate; // this iteration's rate float rate_error; // simply target_rate - current_rate // get current rate current_rate = feedback ; // calculate error and call pid controller rate_error = rate_target - current_rate; p = rate_error * PID->kp; // get i term i = PID->error_int; // update i term as long as we haven't breached the limits or the I term will certainly reduce if ((!limit && !thr_low) || ((i>0&&rate_error<0)||(i<0&&rate_error>0))) { i = get_i(PID ,rate_error, dt); } // get d term d = get_d(PID,rate_error, dt); return constrain_float((p+i+d), -1.0f, 1.0f); } float rate_to_motor_pitch(PID_Controller *PID, float rate_target, float feedback, float dt, bool limit, bool thr_low) { float p,i,d; // used to capture pid values for logging float current_rate; // this iteration's rate float rate_error; // simply target_rate - current_rate // get current rate current_rate = feedback ; // calculate error and call pid controller rate_error = rate_target - current_rate; p = rate_error * PID->kp; // get i term i = PID->error_int; // update i term as long as we haven't breached the limits or the I term will certainly reduce if ((!limit && !thr_low) || ((i>0&&rate_error<0)||(i<0&&rate_error>0))) { i = get_i(PID ,rate_error, dt); } // get d term d = get_d(PID,rate_error, dt); return constrain_float((p+i+d), -1.0f, 1.0f); } float rate_to_motor_yaw(PID_Controller *PID, float rate_target, float feedback, float dt, bool limit, bool thr_low) { float p,i,d; // used to capture pid values for logging float current_rate; // this iteration's rate float rate_error; // simply target_rate - current_rate // get current rate current_rate = feedback ; // calculate error and call pid controller rate_error = rate_target - current_rate; p = rate_error * PID->kp; // get i term i = PID->error_int; // update i term as long as we haven't breached the limits or the I term will certainly reduce if ((!limit && !thr_low) || ((i>0&&rate_error<0)||(i<0&&rate_error>0))) { i = get_i(PID ,rate_error, dt); } // get d term d = get_d(PID,rate_error, dt); return constrain_float((p+i+d), -1.0f, 1.0f); } float acc_to_motor_thr(PID_Controller *PID, float accel_error, float dt, bool limit_up, bool limit_down) { float p,i,d; // used to capture pid values for logging // separately calculate p, i, d values for logging p = accel_error * PID->kp; // get i term i = PID->error_int; // update i term as long as we haven't breached the limits or the I term will certainly reduce // To-Do: should this be replaced with limits check from attitude_controller? if ((!limit_down && !limit_up) || (i>0&&accel_error<0) || (i<0&&accel_error>0)) { i = get_i(PID ,accel_error, dt); } // get d term d = get_d(PID,accel_error, dt); PID->output = p + i + d; return PID->output; } void PID_SetIntegLimit(PID_Controller* PID, const float limit) { PID->int_limit = limit; } void PID_SetParam_P(PID_Controller* PID, float p) { PID->kp = p; } void PID_SetParam_I(PID_Controller* PID, float i) { PID->ki = i; } void PID_SetParam_D(PID_Controller* PID, float d) { PID->kd = d; } void PID_Reset(PID_Controller *PID) { PID->dt = 0.0f; PID->error_int = 0.0f; PID->error_now = 0.0f; PID->error_pre = 0.0f; PID->error_last = 0.0f; PID->last_derivative = NAN; PID->feedback = 0.0f; PID->output = 0; PID->setpoint = 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include "esp_system.h" #include "spiffs/spiffs_vfs.h" #include "esp_log.h" static const char *TAG = "reader_storage"; static const char* filename_stored = "stored.dat"; static const char* filename_position = "position.dat"; static int check_storage_ready() { if (spiffs_is_mounted == 0) { ESP_LOGE(TAG, "Reader storage is not mounted."); } return spiffs_is_mounted; } void reader_storage_get_filename(char* buf, int len) { if (check_storage_ready() == 0) { return; } strcpy(buf, SPIFFS_BASE_PATH); strcat(buf, "/"); strcat(buf, filename_stored); } long reader_storage_get_length() { if (check_storage_ready() == 0) { return -1; } char path[64]; reader_storage_get_filename(path, sizeof(path)); long length = -1; struct stat stats; if (stat(path, &stats) == 0) { length = stats.st_size; } ESP_LOGI(TAG, "Getting length: %ld", length); return length; } void reader_storage_store_file(char* source_path) { if (check_storage_ready() == 0) { return; } char dest_path[64]; reader_storage_get_filename(dest_path, sizeof(dest_path)); ESP_LOGI(TAG, "Storing file %s into %s", source_path, dest_path); FILE* src = fopen(source_path, "r"); if (src == NULL) { ESP_LOGE(TAG, "Failed opening source file."); return; } FILE* dst = fopen(dest_path, "w"); if (dst == NULL) { ESP_LOGE(TAG, "Failed opening destination file."); return; } char buf[32]; int len = 0; do { len = fread(buf, 1, sizeof(buf), src); if (len > 0) { len = fwrite(buf, 1, sizeof(buf), dst); } } while (len > 0); fclose(dst); fclose(src); ESP_LOGI(TAG, "File stored."); } long reader_storage_get_position() { if (check_storage_ready() == 0) { return -1; } long position = 0; char* path[64]; strcpy(path, SPIFFS_BASE_PATH); strcat(path, "/"); strcat(path, filename_position); FILE* f = fopen(path, "r"); if (f == NULL) { ESP_LOGE(TAG, "Failed opening position file for reading."); return; } if (fread(&position, sizeof(position), 1, f) != 1) { ESP_LOGE(TAG, "Failed reading position."); position = -1; } fclose(f); ESP_LOGI(TAG, "Getting position: %ld", position); return position; } void reader_storage_set_position(long position) { if (check_storage_ready() == 0) { return; } ESP_LOGI(TAG, "Setting position: %ld", position); char* path[64]; strcpy(path, SPIFFS_BASE_PATH); strcat(path, "/"); strcat(path, filename_position); FILE* f = fopen(path, "w"); if (f == NULL) { ESP_LOGE(TAG, "Failed opening position file for writing."); return; } if (fwrite(&position, sizeof(position), 1, f) != 1) { ESP_LOGE(TAG, "Failed writing position."); } fclose(f); }
C
#include "hw1.h" #include <stdlib.h> int morse(unsigned short mode){ char buffer, *newline="\n", *space=" ", *tab="\t"; int isDecrypt = 0x2000 & mode; int morseCount = 0; //Setup table setupMorseTable(key); if(isDecrypt){ }else{ buffer = getchar(); while(buffer != EOF){ if(buffer == *space){ printf(" "); }else if(buffer == *newline){ printf("\n"); }else if(buffer == *tab){ printf("\t"); }else{ if(!checkMorse(buffer)) return 0; //Not in morse_table char *newline="\n", *space=" ", *tab="\t"; char const *toEncrypt = checkMorse(buffer); while(*toEncrypt){ if(*toEncrypt == *space){ }else if(*toEncrypt == *newline){ }else if(*toEncrypt == *tab){ } //Full buffer, now print encrypt if(morseCount == 3){ printf("%c",printEncrypt()); morseCount = 0; } //Fill the buffer if(morseCount<3){ *(polybius_table + morseCount) = *toEncrypt; morseCount+=1; } toEncrypt++; } } buffer = getchar(); } } return 1; } const char *checkMorse(char buffer){ char *newline="\n", *space=" ", *tab="\t"; if(buffer == *space){ return space; }else if(buffer == *newline){ return newline; }else if(buffer == *tab){ return tab; } int position = buffer - 33; // '!' is index 0 const char *morsePoint = *(morse_table + position); if(*morsePoint){ return morsePoint; } return 0; } int encryptMorse(const char morse){ char *tablePoint = polybius_table; return 0; } void setupMorseTable(const char *key){ const char *alphaPointer = fm_alphabet, *keyPointer = key; char *tablePointer = fm_key; if(*key){ //First, add key to table while(*keyPointer){ *tablePointer = *keyPointer; keyPointer++; tablePointer++; } //Then, add reset of alphabet while(*alphaPointer){ //Skip if letter is in key keyPointer = key; //reset key pointer int found = 0; while(*keyPointer){ if(*alphaPointer == *keyPointer){ alphaPointer++; //skip letter found = 1; break; } keyPointer++; } if(found) continue; *tablePointer = *alphaPointer; alphaPointer++; tablePointer++; } }else{ for(int i=0; i<27; i++){ if(*alphaPointer){ *tablePointer = *alphaPointer; alphaPointer++; tablePointer++; }else{ *tablePointer = 0; tablePointer++; } } } // tablePointer = fm_key; // for(int i=0; i<27; i++){ // printf("%d %c\n", i, *tablePointer); // tablePointer++; // } } char printEncrypt(){ int position = 0, found = 0; char *encrypt = "xyz", *fmPoint = fm_key; printf("Encrypt1: %c", *(encrypt + 0)); printf("Encrypt2: %c", *(encrypt + 1)); printf("Encrypt3: %c", *(encrypt + 2)); // *(encrypt + 0) = *(polybius_table + 0); // *(encrypt + 1) = *(polybius_table + 1); // *(encrypt + 2) = *(polybius_table + 2); // while(!found){ // const char *letter = *(fractionated_table + position); // if((*letter + 0) == *(encrypt + 0)){ // if((*letter + 1) == *(encrypt + 1)){ // if((*letter + 2) == *(encrypt + 2)){ // found = 1; // } // } // } // if(!found) position++; // } // return *(fm_key + position); return 33; }
C
/* Kernel headers, needed for e.g. KERN_ALERT. */ #include <linux/kernel.h> /* Type definitions, needed for e.g. ssize_t. */ #include <linux/types.h> /* Module headers, needed for various Kernel module-specific functions and globals. */ #include <linux/module.h> /* Device headers, needed for managing a device. */ #include <linux/device.h> /* File structure headers, needed for defining and creating a character device. */ #include <linux/fs.h> /* Uaccess-headers, needed for copying data between user space and Kernel space. */ #include <asm/uaccess.h> /* Set the licence, author, version, and description of the module. */ MODULE_LICENSE("GPL"); MODULE_AUTHOR("Jarmo Puttonen"); MODULE_DESCRIPTION ("Character device that encrypts/decrypts given input by XORing with RC4-stream."); MODULE_VERSION("1.2"); /* Maximum size of message in a single write- or read-operation. */ #define MESSAGE_MAX_SIZE 1024 /* Device name which will be used in the file system (/dev/cry). */ #define DEVICE_NAME "cry" /* Class name defines which class the module is specific to. */ #define CLASS_NAME "cryptor" /* IOCTL-call values used for setting and getting the encryption key. */ #define IOCTL_SET_KEY 0 #define IOCTL_GET_KEY 1 static char *encryptionKey; /* Encryption key is char pointer (charp) that can be read and write by root (S_IRWXU). */ module_param(encryptionKey, charp, S_IRWXU); /* Encryption key parameter description for the module. */ MODULE_PARM_DESC(encryptionKey, "Encryption key that will be used in cryptography operations."); /* Device major number maps the device file to the corresponding driver. */ static int majorNum; /* Initialize memory for the message. */ static char msg[MESSAGE_MAX_SIZE] = { 0 }; /* Variable for storing length of the string. */ static short msgSize; /* The basic device class. */ static struct class *cryClass; /* The basic device structure. */ static struct device *cryDevice; /* Open is called when the user tries to open the character device file. */ static int cry_open(struct inode *, struct file *); /* Release is called when a process closes the character device file. */ static int cry_release(struct inode *, struct file *); /* Read is called when a process that has opened the character device file tries to read from it. */ static ssize_t cry_read(struct file *, char *, size_t, loff_t *); /* Write is called when a process that has opened the character device file tries to write to it. */ static ssize_t cry_write(struct file *, const char *, size_t, loff_t *); /* Ioctl is called when a process tries to do an ioctl call to the character device file. */ static long cry_ioctl(struct file *file, unsigned int cmd_in, unsigned long arg); /* Linux file structure operations which the character device will support. */ static struct file_operations fops = { .open = cry_open, .read = cry_read, .write = cry_write, .release = cry_release, .unlocked_ioctl = cry_ioctl, }; /* Function prototype for the rc4 based encryption. */ void rc4(unsigned char *key, unsigned char *msg); /* This function will be executed at module initialization time. */ static int __init cry_init(void) { printk(KERN_INFO "cryptor: Starting Crypto-module as LKM.\n"); /* Register a character device and try to get a major number dynamically if possible. */ majorNum = register_chrdev(0, DEVICE_NAME, &fops); if (majorNum < 0) { printk(KERN_ALERT "cryptor: Could not register a major number!\n"); return PTR_ERR(&majorNum); } printk(KERN_INFO "cryptor: Registered with major number %d.\n", majorNum); /* Create a struct class structure which will be used in creating the device. */ cryClass = class_create(THIS_MODULE, CLASS_NAME); if (IS_ERR(cryClass)) { /* Unregister the character device as we could not create the device class. */ unregister_chrdev(majorNum, DEVICE_NAME); printk(KERN_ALERT "cryptor: Could not register the device class!\n"); return PTR_ERR(cryClass); } printk(KERN_INFO "cryptor: Registered the device class.\n"); /* Create a device and register it with sysfs. */ cryDevice = device_create(cryClass, NULL, MKDEV(majorNum, 0), NULL, DEVICE_NAME); if (IS_ERR(cryDevice)) { /* Destroy the class and unregister the character device as we could not create the device driver. */ class_destroy(cryClass); unregister_chrdev(majorNum, DEVICE_NAME); printk(KERN_ALERT "cryptor: Could not create the device.\n"); return PTR_ERR(cryDevice); } printk(KERN_INFO "cryptor: Created the device to /dev/%s.\n", DEVICE_NAME); return 0; } /* This function which will be executed on the module cleanup time. */ static void __exit cry_exit(void) { /* Destroy the device, destroy the class and unregister the character device. */ device_destroy(cryClass, MKDEV(majorNum, 0)); class_destroy(cryClass); unregister_chrdev(majorNum, DEVICE_NAME); printk(KERN_INFO "cryptor: LKM unloaded successfully.\n"); } /* This is called when the user tries to open the character device file. */ static int cry_open(struct inode *inodep, struct file *filep) { /* If there is no encryption key, return an invalid argument error. */ if (encryptionKey == NULL) { printk(KERN_NOTICE "cryptor: User tried to use the device when there was no encryption key present."); return -EINVAL; } printk(KERN_INFO "cryptor: User opened the device.\n"); return 0; } /* This is called when a process that has opened the character device file tries to read from it. */ static ssize_t cry_read(struct file *filep, char *buffer, size_t len, loff_t *offset) { int errorCount = 0; /* Copy the saved message from the global variable to user space. */ /* If there were any errors, return an I/O Error. */ errorCount = copy_to_user(buffer, msg, msgSize); if (errorCount == 0) { printk(KERN_INFO "cryptor: Sent %d characters to user.\n", msgSize); msgSize = 0; return (0); } else { printk(KERN_ALERT "cryptor: Could not send %d characters to user!\n", msgSize); return -EIO; } } /* This is called when a process that has opened the character device file tries to write to it. */ static ssize_t cry_write(struct file *filep, const char *buffer, size_t len, loff_t *offset) { /* Write characters in input buffer to the message. */ sprintf(msg, "%s", buffer); msgSize = strlen(msg); printk(KERN_INFO "cryptor: Received %d characters to device!\n", msgSize); /* Lets encrypt/decrypt the message. */ printk(KERN_INFO "cryptor: Encrypting/decrypting the message."); rc4(encryptionKey, msg); /* Return the amount of characters that were encrypted/decrypted. */ return msgSize; } /* This is called when a process tries to do an ioctl call to the character device file. */ static long cry_ioctl(struct file *file, unsigned int ioctl_cmd, unsigned long arg) { int ret_val = 0; /* Find out if the user wants to set or get the encryption key. */ switch (ioctl_cmd) { case IOCTL_SET_KEY: /* Copy data from user space to the encryption key variable (Kernel space). */ ret_val = copy_from_user(encryptionKey, (char *)arg, sizeof(encryptionKey)); printk(KERN_INFO "cryptor: User changed encryption key via IOCTL.\n"); break; case IOCTL_GET_KEY: /* Copy data from the encryption key variable (Kernel space) to user space. */ ret_val = copy_to_user((char *)arg, encryptionKey, sizeof(encryptionKey)); printk(KERN_INFO "cryptor: Encryption key sent to user via IOCTL.\n"); break; default: /* If invalid ioctl call is given, log the operation and return. */ printk(KERN_WARNING "cryptor: Received invalid IOCTL call (%d).\n", ioctl_cmd); break; } return ret_val; } /* This is called when a process closes the character device file. */ static int cry_release(struct inode *inodep, struct file *filep) { printk(KERN_INFO "cryptor: Device closed succesfully.\n"); return 0; } /* Specify functions which will be called when the module is loaded and unloaded.. */ module_init(cry_init); module_exit(cry_exit); /* Following public domain RC4-implementation is from https://github.com/B-Con/crypto-algorithms */ void rc4_key_setup(unsigned char state[], const unsigned char key[], int len) { int i; int j; for (i = 0; i < 256; ++i) state[i] = i; for (i = 0, j = 0; i < 256; ++i) { unsigned char t = state[i]; j = (j + state[i] + key[i % len]) % 256; state[i] = state[j]; state[j] = t; } } void rc4_generate_stream(unsigned char state[], unsigned char out[], size_t len) { int i; int j; size_t idx; for (idx = 0, i = 0, j = 0; idx < len; ++idx) { unsigned char t = state[i]; i = (i + 1) % 256; j = (j + state[i]) % 256; state[i] = state[j]; state[j] = t; out[idx] = state[(state[i] + state[j]) % 256]; } } void rc4(unsigned char *key, unsigned char *msg) { unsigned char state[256]; unsigned char buf[MESSAGE_MAX_SIZE]; size_t i; rc4_key_setup(state, key, strlen(key)); rc4_generate_stream(state, buf, MESSAGE_MAX_SIZE); for (i = 0; i < strlen(msg); i++) { msg[i] ^= buf[i]; } }
C
/* * apartment.c * * Created on: 27 2016 * Author: Liron */ /* * * this should be everything * whatever I've tested and found to work has " //works" written above it, the splitting function could be improved * I've also implemented two helpful functions, their declaration can be seen here, and their implementation at the end * everything should be ordered like the header file, and I haven't checked the service file just yet */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <stdbool.h> #include "apartment.h" // helpful functions - implemented at the end of the file bool checkPath(Apartment apartment, int currentRow, int currentCol, int destinationRow, int destinationCol); //void print(Apartment apartment); // works Apartment apartmentCreate(SquareType** squares, int length, int width, int price) { if(squares == NULL || length <= 0 || width <= 0 || price < 0) return NULL; Apartment apartment = malloc(sizeof(*apartment)); if(apartment == NULL) return NULL; apartment->length = length; apartment->width = width; apartment->price = price; apartment->squares = malloc(length*sizeof(SquareType*)); if(apartment->squares == NULL) return NULL; for(int i=0; i<length; i++) { apartment->squares[i] = malloc(width*sizeof(SquareType)); if(apartment->squares[i]==NULL) { apartmentDestroy(apartment); return NULL; } for(int j=0; j<width; j++) { apartment->squares[i][j] = squares[i][j]; } } return apartment; } void destroySquares(SquareType*** sq,int length,int width) { for(int i=0;i<length;i++) { free((*sq)[i]); } free(*sq); return; } //does not work void apartmentDestroy(Apartment apartment) { if(apartment == NULL || apartment->length <= 0 || apartment->width <= 0 || apartment->squares == NULL) { //free(apartment); // this keeps fucking me up, this line is probably necessary but the code doesn't run with it return; } for(int i=0; i<apartment->length; i++) { free(apartment->squares[i]); // seems to fail here apartment->squares[i] = NULL; } free(apartment->squares); apartment->squares = NULL; free(apartment); // this keeps fucking us up, it should probably exist in the code, but hey } // works Apartment apartmentCopy(Apartment apartment) { if(apartment == NULL) return NULL; Apartment copy = apartmentCreate(apartment->squares, apartment->length, apartment->width, apartment->price); return copy; } // works ApartmentResult apartmentIsSameRoom(Apartment apartment, int row1, int col1, int row2, int col2, bool* outResult) { if(apartment == NULL) return APARTMENT_NULL_ARG; if(row1 >= apartment->length || col1 >= apartment->width || row2 >= apartment->length || col2 >= apartment->width || row1 < 0 || col1 < 0 || row2 < 0 || col2 < 0 || apartment->squares[row1][col1] == WALL || apartment->squares[row2][col2] == WALL) { *outResult = false; return APARTMENT_OUT_OF_BOUNDS; } if(apartment->squares[row1][col1] == WALL || apartment->squares[row2][col2] == WALL) { *outResult = false; return APARTMENT_NO_ROOM; } *outResult = checkPath(apartment, row1, col1, row2, col2); return APARTMENT_SUCCESS; } // works int apartmentTotalArea(Apartment apartment) { int empties = 0; for(int i=0; i<apartment->length; i++) for(int j=0; j<apartment->width; j++) if(apartment->squares[i][j] == EMPTY) empties++; return empties; } // works ApartmentResult apartmentRoomArea(Apartment apartment, int row, int col, int* outArea) { if(apartment == NULL || outArea == NULL) return APARTMENT_NULL_ARG; if(row < 0 || row >= apartment->length || col < 0 || col >= apartment->width) return APARTMENT_OUT_OF_BOUNDS; // if(apartment->squares[row][col] == WALL) return APARTMENT_NO_ROOM; *outArea = 0; bool path = false; for(int i=0; i<apartment->length; i++) { for(int j=0; j<apartment->width; j++) { path = checkPath(apartment, i, j, row, col); if(path) (*outArea)++; } } return APARTMENT_SUCCESS; } // works but very long ApartmentResult apartmentSplit(Apartment apartment, bool splitByRow, int index, Apartment* first, Apartment* second) { if(apartment == NULL) return APARTMENT_NULL_ARG; if(splitByRow) { if(index < 0 || index > apartment->length) return APARTMENT_OUT_OF_BOUNDS; for(int i=0; i<apartment->length; i++) if(apartment->squares[index][i] == EMPTY) return APARTMENT_BAD_SPLIT; int price1 = apartment->price*(index+1)/(apartment->length); int price2 = apartment->price*(apartment->length-index)/(apartment->length); SquareType** squares = malloc((apartment->length-index-1)*sizeof(SquareType*)); if(squares == NULL) return APARTMENT_OUT_OF_MEM; for(int i=0; i<apartment->length-index-1; i++) { squares[i] = malloc(apartment->width*sizeof(SquareType)); if(squares[i] == NULL) return APARTMENT_OUT_OF_MEM; for(int j=0; j<apartment->width; j++) { squares[i][j] = apartment->squares[i+index+1][j]; } } *first = apartmentCreate(apartment->squares, index, apartment->width, price1); *second = apartmentCreate(&apartment->squares[index+1], apartment->length-index-1, apartment->width, price2); for(int i=0; i<apartment->length; i++) free(squares[i]); free(squares); } else { if(index < 0 || index > apartment->width) return APARTMENT_OUT_OF_BOUNDS; for(int i=0; i<apartment->length; i++) if(apartment->squares[i][index] == EMPTY) return APARTMENT_BAD_SPLIT; int price1 = (apartment->price)*(index+1)/(apartment->width); int price2 = (apartment->price)*(apartment->width-index-1)/(apartment->width); SquareType** squares = malloc(apartment->length*sizeof(SquareType*)); if(squares == NULL) return APARTMENT_OUT_OF_MEM; for(int i=0; i<apartment->length; i++) { squares[i] = malloc((apartment->width-index-1)*sizeof(SquareType)); if(squares[i] == NULL) return APARTMENT_OUT_OF_MEM; for(int j=0; j<apartment->width-index-1; j++) { squares[i][j] = apartment->squares[i][j+index+1]; } } *first = apartmentCreate(apartment->squares, apartment->length, index, price1); *second = apartmentCreate(squares, apartment->length, apartment->width-index-1, price2); for(int i=0; i<apartment->length; i++) free(squares[i]); free(squares); } return APARTMENT_SUCCESS; } /* ApartmentResult splitAux(Apartment *apartment, Apartment** first, Apartment** second, int index, int lengthOrWidth, int splitByRow) { for(int i=0; i<lengthOrWidth; i++) if(apartment->squares[index][i] == EMPTY) return APARTMENT_BAD_SPLIT; int price1 = apartment->price*(index+1)/(apartment->length); int price2 = apartment->price*(apartment->length-index)/(apartment->length); SquareType** squares = malloc((apartment->length-index-1)*sizeof(SquareType*)); if(squares == NULL) return APARTMENT_OUT_OF_MEM; for(int i=0; i<apartment->length-index-1; i++) { squares[i] = malloc(apartment->width*sizeof(SquareType)); if(squares[i] == NULL) return APARTMENT_OUT_OF_MEM; for(int j=0; j<apartment->width; j++) { squares[i][j] = apartment->squares[i+index+1][j]; } } *first = apartmentCreate(apartment->squares, index, apartment->width, price1); *second = apartmentCreate(&apartment->squares[index+1], apartment->length-index-1, apartment->width, price2); for(int i=0; i<apartment->length; i++) free(squares[i]); free(squares); return APARTMENT_SUCCESS; } */ // works int apartmentNumOfRooms(Apartment apartment) { int roomCount = 0; for(int i=0; i<apartment->length; i++) { for(int j=0; j<apartment->width; j++) { bool pathExists = false; if(apartment->squares[i][j] == WALL) continue; for(int k = 0; k< i*apartment->width+j; k++) { apartmentIsSameRoom(apartment, i, j, k/apartment->width, k%apartment->width, &pathExists); if(pathExists) break; } if(!pathExists) roomCount++; } } return roomCount; } // works ApartmentResult apartmentSetSquare(Apartment apartment, int row, int col, SquareType value) { if(apartment == NULL || apartment->squares == NULL) return APARTMENT_NULL_ARG; if(row >= apartment->width || col >= apartment->length) return APARTMENT_OUT_OF_BOUNDS; if(apartment->squares[row][col] == value) return APARTMENT_OLD_VALUE; apartment->squares[row][col]=value; return APARTMENT_SUCCESS; } // works ApartmentResult apartmentGetSquare(Apartment apartment, int row, int col, SquareType* OutValue) { if(apartment == NULL || apartment->squares == NULL) return APARTMENT_NULL_ARG; if(row >= apartment->width || col >= apartment->length) return APARTMENT_OUT_OF_BOUNDS; *OutValue = apartment->squares[row][col]; return APARTMENT_SUCCESS; } // works ApartmentResult apartmentChangePrice(Apartment apartment, int percent) { if(apartment == NULL) return APARTMENT_NULL_ARG; if(percent < -100) return APARTMENT_PRICE_NOT_IN_RANGE; apartment->price *= (100+percent); apartment->price /= 100; bool round = apartment->price % 100 != 0 && percent < 0; // HOW U DO DIS???? if(round) apartment->price++; return APARTMENT_SUCCESS; } // works int apartmentGetPrice(Apartment apartment) { assert(apartment != NULL); return apartment->price; } // works int apartmentGetLength(Apartment apartment) { assert(apartment != NULL); return apartment->length; } // works int apartmentGetWidth(Apartment apartment) { assert(apartment != NULL); return apartment->width; } // works bool apartmentIsIdentical(Apartment apartment1, Apartment apartment2) { if(apartment1 == NULL && apartment2 == NULL) return true; if(apartment1 == NULL || apartment2 == NULL) return false; if(apartment1->price != apartment2->price || apartment1->length != apartment2->length || apartment1->width != apartment2->width) return false; for(int i=0; i<apartment1->length; i++) for(int j=0; j<apartment1->width; j++) if(apartment1->squares[i][j] != apartment2->squares[i][j]) return false; return true; } // helpful functions implementation // works bool checkPath(Apartment apartment, int currentRow, int currentCol, int destinationRow, int destinationCol) { if(currentRow == destinationRow && currentCol == destinationCol) return true; if(apartment->squares[currentRow][currentCol] == WALL) return false; bool r1 = false, r2 = false, r3 = false, r4 = false; apartment->squares[currentRow][currentCol] = WALL; if(currentRow+1 < apartment->length && apartment->squares[currentRow+1][currentCol] == EMPTY) r1 = checkPath(apartment, currentRow+1, currentCol, destinationRow, destinationCol); if(currentRow-1 >= 0 && apartment->squares[currentRow-1][currentCol] == EMPTY) r2 = checkPath(apartment, currentRow-1, currentCol, destinationRow, destinationCol); if(currentCol+1 < apartment->width && apartment->squares[currentRow][currentCol+1] == EMPTY) r3 = checkPath(apartment, currentRow+1, currentCol+1, destinationRow, destinationCol); if(currentCol-1 >= 0 && apartment->squares[currentRow][currentCol-1] == EMPTY) r4 = checkPath(apartment, currentRow, currentCol-1, destinationRow, destinationCol); apartment->squares[currentRow][currentCol] = EMPTY; return r1 || r2 || r3 || r4; } // works, might crash if the apartment isn't initialized well void apartmentPrint(Apartment apartment) { if(apartment == NULL || apartment->length <= 0 || apartment->width <= 0 || apartment->price < 0 || apartment->squares == NULL) { return; } printf("length: %d, width: %d, price: %d\n", apartment->length, apartment->width, apartment->price); for(int i=0; i<apartment->length; i++) { //printf("okay now in the loop \n"); // wtf it fails right in the if, why?????? if(apartment == NULL || apartment->squares == NULL || apartment->squares[i] == NULL) { printf("NULLLLLLLLLLLLLLLLLLLLLLL %d\n", i); return; } for(int j=0; j<apartment->width; j++) { if(apartment->squares[i][j]==WALL) printf("# "); else printf("O "); } printf("\n"); } printf("and that's it for that apartment\n\n"); }
C
#include <stdio.h> #include <stdlib.h> int G[25][25], visited_places[10], limit, cost = 0; int tsp(int p) { int count, nearest_place = 999; int minimum = 999, temp; for(count = 0; count < limit; count++) { if((G[p][count] != 0) && (visited_places[count] == 0)) { if(G[p][count] < minimum) { minimum = G[count][0] + G[p][count]; } temp = G[p][count]; nearest_place = count; } } if(minimum != 999) { cost = cost + temp; } return nearest_place; } void minimum_cost(int place) { int nearest_place; visited_places[place] = 1; printf("%d ", place + 1); nearest_place = tsp(place); if(nearest_place == 999) { nearest_place = 0; printf("%d", nearest_place + 1); cost = cost + G[place][nearest_place]; return; } minimum_cost(nearest_place); } int main() { int i, j; printf("Enter Total Number of Cities:\t"); scanf("%d", &limit); for(i=0;i<limit;i++) for(j=0;j<limit;j++) {//scanf("%d",&G[i][j]); G[i][j]=rand()%20;} for(i=0;i<limit;i++) G[i][i]=0; printf("\nEntered Cost Matrix\n"); for(i = 0; i < limit; i++) { printf("\n"); for(j = 0; j < limit; j++) { printf("%d ", G[i][j]); } } printf("\n\nPath:\t"); minimum_cost(0); printf("\n\nMinimum Cost: \t"); printf("%d\n", cost); return 0; } /*printf("\nEnter Cost Matrix\n"); for(i = 0; i < limit; i++) { printf("\nEnter %d Elements in Row[%d]\n", limit, i + 1); for(j = 0; j < limit; j++) { scanf("%d", &matrix[i][j]); } visited_cities[i] = 0; }*/
C
#include "lib/kernel/list.h" #include "threads/thread.h" #include <debug.h> #include <stdio.h> #include "userprog/pagedir.h" #include "threads/palloc.h" #include "threads/malloc.h" #include "threads/vaddr.h" #include "vm/swap.h" #include "vm/frame.h" static struct list_elem *clock_ptr; void vm_frame_init() { list_init(&frame_list); //clock_ptr = NULL; } void* vm_frame_allocate(enum palloc_flags flags, void *upage) {//프레임 추가 void *frame = palloc_get_page(PAL_USER | flags); //page userpool에서 page 가져옴 if (frame == NULL) { //page allocate를 받을수 없는경우 vm_evict_frame(); } if (frame != NULL) { //successfully allocated page vm_add_frame(upage, frame); } } void vm_add_frame(void *upage, void *frame) { //프레임테이블에 엔트리 추가 struct frame *f = (struct frame*) malloc(sizeof(struct frame)); f->t = thread_current(); f->upage = upage;//// f->uaddr = frame;////??????????????????????????????????????????맞는지모름 list_push_back(&frame_list, &f->elem); //프레임 추가!!! } void* vm_evict_frame() { //페이지자리 하나 만들기 struct frame *ef;//스왑할 페이지 ef = evict_by_clock(); //ef = evict_by_lur(); //ef = evict_by_secont_chance(); if (ef == NULL) //스왑할 페이지를 못찾음 PANIC("No frame to evict"); if(!save_evicted_frame(ef)) PANIC("can't save evicted frame"); //페이지 비우기 ef->t = thread_current(); ef->upage = NULL; ef->uaddr = NULL; return ef; } struct frame* evict_by_clock() {//clock algorithm struct frame *f; struct thread *t; struct list_elem *e; void* last_use = pagedir_lru_list_get_head(false); if(last_use != NULL){ for(e=list_begin(&frame_list); e!=list_end(&frame_list); e=list_next(e)){ f = list_entry(e, struct frame, elem); if(f->uaddr == last_use){ e = f; } } } struct frame *f_class0 = NULL; int cnt = 0; bool found = false; while (!found) { for (; e != list_end(&frame_list) && cnt < 2; e = list_next(e)) { f = list_entry(e, struct frame, elem); t = f->t; //clock algorithm if (!pagedir_is_accessed(t->pagedir, f->uaddr)) { f_class0 = f; list_remove(e); list_push_back(&frame_list, e); break; } else { pagedir_set_accessed(t->pagedir, f->uaddr, false); } } if (f_class0 != NULL) found = true; else if (cnt++ == 2) found = true; } pagedir_lru_list_remove(f_class0->uaddr); return f_class0; } struct frame* evict_by_lru() { struct frame *f; struct list_elem *e; void* evict_page = pagedir_lru_list_get_head(true); if(evict_page == NULL){ PANIC("No page in LRU list"); } for(e = list_begin(&frame_list); e!=list_end(&frame_list); e = list_next(e)){ f = list_entry(e, struct frame, elem); if(f->uaddr == evict_page){ return f; } } return NULL; } struct frame* evict_by_second_chance() { struct frame *f; struct thread *t; struct list_elem *e; struct frame *f_class0 = NULL; int cnt = 0; bool found = false; while (!found) { for (e = list_begin(&frame_list); e != list_end(&frame_list) && cnt < 2; e = list_next(e)) { f = list_entry(e, struct frame, elem); t = f->t; //clock algorithm if (!pagedir_is_accessed(t->pagedir, f->uaddr)) { f_class0 = f; list_remove(e); list_push_back(&frame_list, e); break; } else { pagedir_set_accessed(t->pagedir, f->uaddr, false); } } if (f_class0 != NULL) found = true; else if (cnt++ == 2) found = true; } return f_class0; } bool save_evicted_frame(struct frame *f) { struct thread *t; size_t swap_slot_idx; t = f->t; if(pagedir_is_dirty(t->pagedir, f->uaddr)){ swap_slot_idx = vm_swap_out(f->uaddr); if(swap_slot_idx == SWAP_ERROR) return false; } memset(f, 0, PGSIZE); pagedir_clear_page(t->pagedir, f->uaddr); return true; } void vm_remove_frame(void *frame) { struct frame *f; struct list_elem *e; e = list_head(&frame_list); while ((e = list_next(e)) != list_tail(&frame_list)) { f = list_entry(e, struct frame, elem); if (f == frame) { list_remove(e); free(f); break; } } } void vm_free_frame(void *frame) { //프레임 할당해제 해줄 때 프레임이랑 페이지 둘다 할당해야되는데 하나로 묶고 싶어서 만든 함수! vm_remove_frame(frame); palloc_free_page(frame); } void vm_set_frame(void *fr, void *pte, void *upage){ //프레임을 원하는 주소에 설정해주는 함수인데 , pagedir 에서 쓸려고만듬 struct frame *f, *find; struct list_elem *e; f=fr; e=list_head(&frame_list); while((e=list_next(e)) != list_tail (&frame_list)){ find=list_entry(e, struct frame, elem); if(find==f){ break; } find=NULL; } if(find != NULL){ find->uaddr = pte; find->upage = upage; } }
C
/* ** EPITECH PROJECT, 2019 ** do_ops ** File description: ** do_op point and line */ #include "../../include/my.h" int div_mod_zero(char *nbr2) { if (my_abs(nbr2)[0] == '0') { my_putstr("error"); exit(84); } return (0); } char *do_op_line(char *nbr1, char op, char *nbr2) { int len = bigger_number(nbr1, nbr2) + 1; char *res; if ((op == '+' && is_neg(nbr1) == is_neg(nbr2)) || \ (op == '-' && is_neg(nbr1) != is_neg(nbr2))) { res = my_infin_add(my_abs(nbr1), my_abs(nbr2), len, 0); if (is_neg(nbr1) == 1 && is_neg(nbr2) == 0 ) res = to_neg(res); } else if ((op == '-' && is_neg(nbr1) == is_neg(nbr2)) || \ (op == '+' && is_neg(nbr1) != is_neg(nbr2))) { res = my_infin_sub(my_abs(nbr1), my_abs(nbr2), len, 0); if (neg_sub(nbr1, nbr2)) res = to_neg(res); } else return (do_op_point(nbr1, op, nbr2)); free(nbr1); return (res); } char *do_op_point(char *nbr1, char op, char *nbr2) { int len = bigger_number(nbr1, nbr2) + 1; char *res; if (op == '*') { res = my_infin_mult(my_abs(nbr1), my_abs(nbr2), len); if (neg_point(nbr1, nbr2) && res[0] != '0') res = to_neg(res); } else if (op == '/') { div_mod_zero(nbr2); res = my_infin_div(my_abs(nbr1), my_abs(nbr2), len); if (neg_point(nbr1, nbr2) && res[0] != '0') res = to_neg(res); } else return (do_op_mod(nbr1, op, nbr2)); free(nbr1); return (res); } char *do_op_mod(char *nbr1, char op, char *nbr2) { int len = bigger_number(nbr1, nbr2) + 1; char *res; if (op == '%') { div_mod_zero(nbr2); res = my_infin_mod(my_abs(nbr1), my_abs(nbr2), len); if (is_neg(nbr1) && is_neg(nbr2)) res = to_neg(res); } free(nbr1); return (res); }
C
#include <stdlib.h> #include <string.h> #include "benchmark.h" /* The implementation */ #include "sglib.h" #include "rhash.h" /* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */ /* define the initial size of the hash table (0 is illegal) */ #define HASHSIZE 100000 /* define the object of the hash table */ #define OBJ_INT 1 #define OBJ_STR 2 typedef struct obj obj_t; struct obj { char type; unsigned ukey; /* unsigned key */ char skey [16]; /* string key */ unsigned val; /* unsigned value */ obj_t * self; /* self pointer */ obj_t * _reserved_; /* field required to make the object hash-able */ }; /* Define a compare function for both integers/string keys */ static int cmp_objs (obj_t * a, obj_t * b) { if (a -> type == OBJ_INT) return a -> ukey - b -> ukey; else return strcmp (a -> skey, b -> skey); } /* Define a hash function for both integer/string keys (hash functions are inlined in support.h) */ static uint32_t hash_obj (obj_t * obj) { if (obj -> type == OBJ_INT) return java_hash (obj -> ukey); else return python_hash (obj -> skey); } /* Generates typedef and inline functions for the base container (usually a linked list) */ SGLIB_DEFINE_LIST_PROTOTYPES (obj_t, cmp_objs, _reserved_); SGLIB_DEFINE_LIST_FUNCTIONS (obj_t, cmp_objs, _reserved_); /* Generates typedef and inline functions for hash table */ SGLIB_DEFINE_HASHED_CONTAINER_PROTOTYPES (obj_t, HASHSIZE, hash_obj); SGLIB_DEFINE_HASHED_CONTAINER_FUNCTIONS (obj_t, HASHSIZE, hash_obj); /* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */ static obj_t * objs_unsigned (const unsigned * keys, unsigned n) { obj_t * objs = calloc (n, sizeof (obj_t)); unsigned i; for (i = 0; i < n; i ++) { objs [i] . type = 1; objs [i] . ukey = keys [i]; objs [i] . val = i; } return objs; } static obj_t * objs_str (char * const * keys, unsigned n) { obj_t * objs = calloc (n, sizeof (obj_t)); unsigned i; for (i = 0; i < n; i ++) { objs [i] . type = 2; strcpy (objs [i] . skey, keys [i]); objs [i] . val = i; } return objs; } /* Iterate over all the objects to evaluate the hash table size */ static unsigned sglib_hashed_obj_t_size (obj_t * ht [HASHSIZE]) { unsigned count = 0; obj_t * obj; struct sglib_hashed_obj_t_iterator it; for (obj = sglib_hashed_obj_t_it_init (& it, ht); obj; obj = sglib_hashed_obj_t_it_next (& it)) count ++; return count; } /* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */ #include "sglib-udb.c" #include "sglib-grow.c" int main (int argc, char * argv []) { return udb_benchmark (argc, argv, udb_int, udb_str, grow_int, grow_str); }
C
/* ** EPITECH PROJECT, 2020 ** algo ** File description: ** push_swap */ #include "my.h" #include <unistd.h> #include <stdio.h> #include <stdlib.h> int is_list_sorted_min_to_max(list_t *list) { int len_list = length_list(list); int n = 0; for (int i = 0, j = 1; j < len_list; i++, j++) { if (get_at(list, i) > get_at(list, j)) { return (0); } } return (1); } int is_list_sorted_max_to_min(list_t *list) { int len_list = length_list(list); for (int i = 0, j = 1; j < len_list; i++, j++) { if (get_at(list, i) < get_at(list, j)) { return (0); } } return (1); } void sort_list_of_3(Sorting_t *k) { if (get_at(k->list_a, 0) > get_at(k->list_a, 2) && get_at(k->list_a, 2) > get_at(k->list_a, 1)) { ra(k); } if (get_at(k->list_a, 0) > get_at(k->list_a, 1)) { sa(k); } if (get_at(k->list_a, 0) > get_at(k->list_a, 2)) { rra(k); } if (get_at(k->list_a, 1) > get_at(k->list_a, 2)) { sa(k); ra(k); } } void sort_two_last_nbr_list_a(Sorting_t *k) { int nb0 = get_at(k->list_a, 0); int nb1 = get_at(k->list_a, 1); if (nb0 > nb1) { sa(k); } } void algo(Sorting_t *k) { int len_list = length_list(k->list_a); if (len_list == 2) { sort_two_last_nbr_list_a(k); return; } if (len_list == 3) { sort_list_of_3(k); return; } create_chunks(k); move_chunks(k); }
C
#include <errno.h> #include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // compute the entropy of a given p array of node attribute static double entropy(double *p, uint64_t n) { double sum = 0; for (uint64_t i=0; i<n; i++) { sum += p[i]; } double entropy = 0; for (uint64_t i = 0; i < n; i++) { if (p[i] == 0.0) continue; entropy -= (p[i]/sum * log2l(p[i]/sum)); } return entropy; } int main(void) { uint64_t n_instances = 0; uint64_t n_nodes = 0; uint64_t n_node_atributes = 0; fprintf(stdout, "numbers of instances = "); scanf("%lu", &n_instances); fprintf(stdout, "number of nodes = "); scanf("%lu", &n_nodes); fprintf(stdout, "number of attribute for every node = "); scanf("%lu", &n_node_atributes); double container[n_nodes][n_node_atributes]; fprintf(stdout, "\nadd every attribute in the node\n"); for (size_t i =0; i<n_nodes; i++) { for(size_t j=0; j<n_node_atributes; j++) { printf("Node %lu , attribute %lu = ", i,j); scanf("%lf", &container[i][j]); } } double entropy_nodes[n_nodes]; // compute for every node the entropy for(size_t i=0; i<n_nodes; i++) { entropy_nodes[i] = entropy(container[i], n_node_atributes); printf("Entropy of this node %lu is H[x] = %F\n", i, entropy_nodes[i]); } double sum = 0, ig = 0; //compute the information gain from these nodes for(size_t i=1; i<n_nodes; i++) { for (size_t j=0; j<n_node_atributes; j++) { sum += container[i][j]; } ig = ig - (sum/n_instances) * entropy_nodes[i]; sum = 0; } ig = entropy_nodes[0] + ig; printf("Information gain for this entry IG(x) = %F\n", ig); }
C
int main() { int a,b,c,d; scanf("%d %d %d",&a,&b,&c); if((a%100!=0&&a/4==0)||a%400==0) { switch(b) { case 1:printf("%d",c); break; case 2:printf("%d",d=31+c);break; case 3:printf("%d",d=60+c);break; case 4:printf("%d",d=91+c);break; case 5:printf("%d",d=121+c);break; case 6:printf("%d",d=152+c);break; case 7:printf("%d",d=182+c);break; case 8:printf("%d",d=213+c);break; case 9:printf("%d",d=244+c);break; case 10:printf("%d",d=274+c);break; case 11:printf("%d",d=305+c);break; case 12:printf("%d",d=335+c);break; } } else { switch(b) { case 1:printf("%d",c);break; case 2:printf("%d",d=31+c);break; case 3:printf("%d",d=59+c);break; case 4:printf("%d",d=90+c);break; case 5:printf("%d",d=120+c);break; case 6:printf("%d",d=151+c);break; case 7:printf("%d",d=181+c);break; case 8:printf("%d",d=212+c);break; case 9:printf("%d",d=243+c);break; case 10:printf("%d",d=273+c);break; case 11:printf("%d",d=304+c);break; case 12:printf("%d",d=334+c);break; } } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* patterns_2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tkiselev <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/09/07 20:59:20 by tkiselev #+# #+# */ /* Updated: 2018/09/07 20:59:22 by tkiselev ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" /* ** 3 ** 1 ** 2 */ char pattern_6(t_stack *stack, int piece_len) { int a; int b; int c; if (piece_len == 3 && stack->len == 3) { a = stack->list->value; b = stack->list->next->value; c = stack->list->next->next->value; if (b < c && c < a) return (1); } return (0); } /* ** 3 ** 1 ** 2 ** something here */ char pattern_7(t_stack *stack, int piece_len) { int a; int b; int c; if (piece_len == 3 && stack->len != 3) { a = stack->list->value; b = stack->list->next->value; c = stack->list->next->next->value; if (b < c && c < a) return (1); } return (0); } /* ** 3 ** 2 ** 1 */ char pattern_8(t_stack *stack, int piece_len) { int a; int b; int c; if (piece_len == 3 && stack->len == 3) { a = stack->list->value; b = stack->list->next->value; c = stack->list->next->next->value; if (c < b && b < a) return (1); } return (0); } /* ** 3 ** 2 ** 1 ** something here */ char pattern_9(t_stack *stack, int piece_len) { int a; int b; int c; if (piece_len == 3 && stack->len != 3) { a = stack->list->value; b = stack->list->next->value; c = stack->list->next->next->value; if (c < b && b < a) return (1); } return (0); }
C
#include <stdio.h> #include <string.h> #define MAX_N 8 static int map[MAX_N][MAX_N] = {}, ans[MAX_N] = {}, tmpans[MAX_N] = {}, used[MAX_N] = {1, 0}; static int n; static int max = 0; static void findroad(int now, int count) { if (now == 0 && used[0] == 2) { if (count > max) { max = count; memmove(ans, tmpans, sizeof(tmpans)); } } int i; for (i = 0; i < n; i++) { if (map[now][i] == 0) { continue; } if (used[i] == 1 && i != 0) { continue; } used[i]++; tmpans[count] = i; findroad(i, count + 1); used[i]--; tmpans[count] = 0; } return; } int main(void) { scanf("%d", &n); int i, j; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { scanf("%d", &map[i][j]); } } findroad(0, 0); for (i = 0; i < max - 1; i++) { printf("%d%c", ans[i], i == max - 1 ? '\n' : ' '); } return 0; }
C
/* * @Author: your name * @Date: 2020-02-19 11:13:32 * @LastEditTime: 2020-02-19 13:31:32 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: /c-lang/unit-8/14.c */ #include <stdio.h> void sort(char *num, int n) { char temp; for (int i = 0; i < n / 2; i++) { temp = *(num + i); *(num + i) = *(num + n - i - 1); *(num + n - i - 1) = temp; } } #define N 10 int main() { char num[N]; int temp; for (int i = 0; i < N; i++) { scanf("%d", &num[i]); } sort(num, N); for (int i = 0; i < N; i++) { printf("%d ", num[i]); } printf("\n"); return 0; }
C
2. a)color is an array of 6 elements where each stores the address of char type data b)address of 2nd element.i.e., "blue" c)address of "r" in red d)address of "b" in blue e)color[5] gives address of 5th element.i.e., "yellow", *(colour + 5) represents the address of 0th element of 5th array.i.e., "y" in yellow.
C
#include <stdio.h> #include <stdlib.h> struct node { int key; struct node* next; }; struct node* new(int n) { struct node* p; p=(struct node*) calloc (1,sizeof(*p)); p->key=n; p->next=NULL; return p; } int searchkey(struct node* l, int n) { struct node* p=l; while (p!=NULL) { if (p->key==n) return 1; p=p->next; } return 0; } struct node* searchpos(struct node* l, int n) { struct node* p=l; if ((p==NULL) || (p->key>n)) return NULL; struct node* q=p->next; while (q!=NULL) if (q->key<n) { p=p->next; q=q->next; } else return p; return p; } struct node* insert(struct node* l, struct node* p, struct node* q) { struct node* r=l; struct node* t; if (p==NULL) { q->next=r; r=q; return r; } while (r!=p) r=r->next; t=r->next; r->next=q; q->next=t; return l; } struct node* pushsort(struct node* l, struct node* p) { struct node* q; q=searchpos(l,p->key); l=insert(l,q,p); return l; } struct node* pushback(struct node* l, struct node* p) { struct node* q; q=l; if (q==NULL) l=p; else { while (q->next!=NULL) q=q->next; q->next=p; } return l; } struct node* ins(struct node* l, struct node* p) { struct node* t; t=new(p->key); l=pushback(l,t); p=p->next; return l; } struct node* mergelist(struct node* l, struct node* p) { struct node* q; struct node* r; struct node* s; struct node* t; q=NULL; r=l; s=p; while ((r!=NULL) && (s!=NULL)) if (r->key>s->key) { t=new(s->key); q=pushback(q,t); s=s->next; //q=ins(q,s); } else { t=new(r->key); q=pushback(q,t); r=r->next; //q=ins(q,r); } if (s!=NULL) r=s; while (r!=NULL) { t=new(r->key); q=pushback(q,t); r=r->next; //q=ins(q,r); } return q; } void printlist(struct node* l) { struct node* p=l; while (p!=NULL) { printf("%d ",p->key); p=p->next; } printf("\n"); } int main(void) { struct node* list1 = NULL; struct node* list2 = NULL; struct node* list = NULL; struct node* link = NULL; int n; while (scanf("%d",&n)==1) { link=new(n); list1=pushsort(list1,link); } while (scanf("%d",&n)==1) { link=new(n); list2=pushsort(list2,link); } list=mergelist(list1,list2); printlist(list); return 0; }
C
//################################################################################################## // // Pthread mutex handling. // //################################################################################################## #include <pthread.h> #include <stdio.h> #include "wlibc_panic.h" #include "wrm_mtx.h" enum { Pthread_as_wrm_magic = 0x117733aa }; typedef struct { int magic; Wrm_mtx_t* wmtx; } Mutex_t; int pthread_mutex_init(pthread_mutex_t* mutex, const pthread_mutexattr_t* mutexattr) { panic("%s: implement me!\n", __func__); return 0; } int pthread_mutex_destroy(pthread_mutex_t* mutex) { panic("%s: implement me!\n", __func__); return 0; } int pthread_mutex_trylock(pthread_mutex_t* mutex) { panic("%s: implement me!\n", __func__); return 0; } int pthread_mutex_lock(pthread_mutex_t* mutex) { //printf("%s: mtx=%p, implement me!\n", __func__, mutex); Mutex_t* m = (Mutex_t*) mutex; // initialize mutex if need if (m->magic != Pthread_as_wrm_magic) { static Wrm_mtx_t _mtx = Wrm_mtx_initializer; int rc = wrm_mtx_lock(&_mtx, -1); if (rc) return rc; if (m->magic != Pthread_as_wrm_magic) { m->wmtx = malloc(sizeof(Wrm_mtx_t)); if (m->wmtx) { wrm_mtx_init(m->wmtx); m->magic = Pthread_as_wrm_magic; } } rc = wrm_mtx_unlock(&_mtx); if (rc || !m->wmtx) return rc | 100; } // lock mutex int rc = wrm_mtx_lock(m->wmtx, -1); return rc; } int pthread_mutex_timedlock(pthread_mutex_t* restrict mutex, const struct timespec* restrict abstime) { panic("%s: implement me!\n", __func__); return 0; } int pthread_mutex_unlock(pthread_mutex_t* mutex) { //printf("%s: mtx=%p, implement me!\n", __func__, mutex); Mutex_t* m = (Mutex_t*) mutex; // unlock mutex if it's initialized if (m->magic == Pthread_as_wrm_magic) { int rc = wrm_mtx_unlock(m->wmtx); return rc; } return 0; }
C
#include <stdio.h> #include <stdlib.h> int isTriangle(int lado1, int lado2, int lado3){ if(lado1 + lado2 > lado3 && lado1 + lado3 > lado2 && lado2 + lado3 > lado1){ if(lado1 == lado2 && lado2 == lado3){ //equilatero return 3; }else if(lado1 == lado2 && lado2 != lado3){ //isoceles return 2; }else if(lado1 != lado2 && lado2 != lado3){ //escaleno return 1; } }else{ //não e triangulo return 0; } } int main(){ int lado1,lado2,lado3, triangulo; printf("Digite o primeiro lado 1: "); scanf("%d",&lado1); printf("Digite o segundo lado 2: "); scanf("%d",&lado2); printf("Digite o terceiro lado 3: "); scanf("%d",&lado3); triangulo = isTriangle(lado1,lado2,lado3); if(triangulo == 0){ printf("Nao e um triangulo"); }else if(triangulo == 1){ printf("E um triangulo escaleno"); }else if(triangulo == 2){ printf("E um triangulo isoceles"); }else if(triangulo == 3){ printf("E um triangulo equilatero"); } }
C
#include<stdio.h> void sumsqrcube() { int i=0,sum=0,cube=0,sqr=0; for(i =0 ;i<=10;i++) { sum += i; sqr += i*i; cube += i*i*i; } printf("sum : %d\n",sum); printf("sqr : %d\n",sqr); printf("cube : %d\n",cube); } int main() { sumsqrcube(); return 0; }
C
/* **my_strcat:concatenate t to the end of s; pointer version */ #include<stdio.h> #include<string.h> #define MAXNUM 200 void my_strcat(char *s, char *t); main(){ char s[MAXNUM],t[MAXNUM]; strcpy(s, "hello, "); strcpy(t, "weekend!"); my_strcat(s, t); printf("result : %s\n", s); } void my_strcat(char *s, char *t){ while(*s) s++; while(*s++ = *t++) ; }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> void *funcion(void *argumento); int numero_hilos = 0; int main(int argc, char const *argv[]) { int num_hilos, maxima_cuenta; /*printf("Indique el numero de hilos y el conteo max de cada uno:\n"); scanf("%d",&num_hilos); scanf("%d",&maxima_cuenta);*/ pthread_t hilo1,hilo2; int argumento; printf("Introduce la cuenta del primer hilo\n"); scanf("%d",&argumento); if(pthread_create (&hilo1, NULL, funcion,(void*)argumento) != 0 ) { printf("Error\n"); return -1; } printf("Introduce la cuenta del segundo hilo\n"); scanf("%d",&argumento); if(pthread_create (&hilo2, NULL, funcion,(void*)argumento) != 0 ) { printf("Error\n"); return -1; } pthread_join(hilo2,NULL); pthread_join(hilo1,NULL); funcion((void*)1); return 0; } void *funcion(void *argumento){ numero_hilos ++; printf("Hola desde el hilo %d\n", numero_hilos); for (int i = 0; i < (int)argumento; ++i) { printf("\tCuenta %d\n",i); } }
C
#include <stdio.h> int comp(void* a, void* b) { return *(int*)a - *(int*)b; } void *max (void* m, size_t size, size_t n, int (*comp)(void*, void*)) { char* input = m; int* res = input; for(int i = 0; i < n; ++i) { int check = 0; for(int j = 0; (j < size) && !check; ++j) if(comp(input+i*size+j, input+res+j)) { check = 1; res = i*size; } } } int main(void) { printf("Hello World!\n"); return 0; }
C
#include <stdio.h> #include <string.h> int main() { char str1[2001] = "This is simple string."; char str2[] = "is"; char str3[] = "a"; int str_num = 2; int location[2] = {2, 5}; int r; char tmp[2001]; strcpy(tmp, str1); printf("%s\n", str1); int wordsize = strlen(str2); if (strlen(str2) >= strlen(str3)){ int gap = strlen(str2) - strlen(str3); int strsize = strlen(str1) - gap*str_num; for (int i = 0; i < str_num; i++){ location[i] = location[i] - gap*i; } for (int i = 0; i < str_num; i++) { int k = location[i]; for (int j = k, r = 0; r < strlen(str3); j++, r++){ str1[j] = str3[r]; } for (int j = k+wordsize-gap, r = 0; j < strsize; j++, r++){ str1[j] = tmp[k+wordsize+r]; } strcpy(tmp, str1); } str1[strsize] = '\0'; } else{ int gap = strlen(str3) - strlen(str2); int strsize = strlen(str1) + gap*str_num; for (int i = 0; i < str_num; i++){ location[i] = location[i] + gap*i; } for (int i = 0; i < str_num; i++) { int k = location[i]; for (int j = k, r = 0; r < strlen(str3); j++, r++){ str1[j] = str3[r]; } for (int j = k+wordsize+gap, r = 0; j < strsize; j++, r++){ str1[j] = tmp[k+wordsize+r]; } strcpy(tmp, str1); } } printf("%s\n", str1); return 0; }
C
#include "http.h" #include <strings.h> static void parse_uri(char *root, char *uri, int length, char *filename); static const char *get_file_type(const char *type); static void serve_static(int fd, char *filename, int filesize, fv_http_out_t *out); static void do_error(int fd, char *cause, char *errnum, char *shortmsg, char *longmsg); mime_type_t ferver_mime[] = { {".html", "text/html"}, {".xml", "text/xml"}, {".xhtml", "application/xhtml+xml"}, {".txt", "text/plain"}, {".rtf", "application/rtf"}, {".pdf", "application/pdf"}, {".word", "application/msword"}, {".png", "image/png"}, {".gif", "image/gif"}, {".jpg", "image/jpeg"}, {".jpeg", "image/jpeg"}, {".au", "audio/basic"}, {".mpeg", "video/mpeg"}, {".mpg", "video/mpeg"}, {".avi", "video/x-msvideo"}, {".gz", "application/x-gzip"}, {".tar", "application/x-tar"}, {".css", "text/css"}, {NULL , "text/plain"} }; void parse_uri(char *root, char *uri, int uri_length, char *filename) { char *question_mark = index(uri, '?'); int file_length; if (question_mark) { file_length = (int)(question_mark - uri); } else { file_length = uri_length; } strcpy(filename, root); strncat(filename, uri, file_length); char *last_dot = rindex(filename, '.'); if (last_dot == NULL && filename[strlen(filename) - 1] != '/') { strcat(filename, "/"); } if (filename[strlen(filename) - 1] == '/') { strcat(filename, "index.html"); } } const char* get_file_type(const char *type) { if (type == NULL) return "text/plain"; int i; for (i = 0; ferver_mime[i].type != NULL; ++i) { if (strcmp(type, ferver_mime[i].type) == 0) return ferver_mime[i].value; } return ferver_mime[i].value; } void serve_static(int fd, char *filename, int filesize, fv_http_out_t *out) { log_info("## ready to serve_static"); debug("filename = %s", filename); char header[MAXLINE]; char buf[SHORTLINE]; int n; struct tm tm; const char *file_type; const char *dot_pos = rindex(filename, '.'); file_type = get_file_type(dot_pos); sprintf(header, "HTTP/1.1 %d %s\r\n", out->status, get_shortmsg_from_status_code(out->status)); if (out->keep_alive) { sprintf(header, "%sConnection: keep-alive\r\n", header); } if (out->modified) { sprintf(header, "%sContent-type: %s\r\n", header, file_type); sprintf(header, "%sContent-length: %d\r\n", header, filesize); localtime_r(&(out->mtime), &tm); strftime(buf, SHORTLINE, "%a, %d %b %Y %H:%M:%S GMT", &tm); sprintf(header, "%sLast-Modified: %s\r\n", header, buf); } sprintf(header, "%sServer: Ferver\r\n", header); sprintf(header, "%s\r\n", header); n = rio_writen(fd, header, strlen(header)); check(n == (ssize_t)strlen(header), "rio_writen error, errno = %d", errno); if (!out->modified) { // 内容没改动则只返回http头 return; } // use sendfile int srcfd = open(filename, O_RDONLY, 0); check(srcfd > 2, "open error"); char *srcaddr = mmap(NULL, filesize, PROT_READ, MAP_PRIVATE, srcfd, 0); check(srcaddr != 0, "mmap error"); close(srcfd); n = rio_writen(fd, srcaddr, filesize); check(n == filesize, "rio_writen error, errno = %d", errno); munmap(srcaddr, filesize); log_info("## serve_static suc"); } void do_error(int fd, char *cause, char *errnum, char *shortmsg, char *longmsg) { char header[MAXLINE], body[MAXLINE]; sprintf(body, "<html><title>Tiny Error</title>"); sprintf(body, "%s<body bgcolor=""ffffff"">\r\n", body); sprintf(body, "%s%s: %s\r\n", body, errnum, shortmsg); sprintf(body, "%s<p>%s: %s\r\n</p>", body, longmsg, cause); sprintf(body, "%s<hr><em>The Tiny web server</em>\r\n", body); sprintf(header, "HTTP/1.1 %s %s\r\n", errnum, shortmsg); sprintf(header, "%sServer: ferver\r\n", header); sprintf(header, "%sContent-type: text/html\r\n", header); sprintf(header, "%sConnection: close\r\n", header); sprintf(header, "%sContent-length: %d\r\n\r\n", header, (int)strlen(body)); log_info("err response header = \n %s", header); rio_writen(fd, header, strlen(header)); rio_writen(fd, body, strlen(body)); log_info("leave do_error"); } void do_request(void *ptr) { fv_http_request_t *r = (fv_http_request_t *)ptr; int fd = r->fd; int rc; char filename[SHORTLINE]; struct stat sbuf; int n, tmp; for (;;) { log_info("#--ready to serve client(fd %d)--", fd); n = read(fd, r->last, (uint32_t)r->buf + MAX_BUF - (uint32_t)r->last); // GET / HTTP/1.1 16bytes check((uint32_t)r->buf + MAX_BUF > (uint32_t)r->last, "(uint32_t)r->buf + MAX_BUF"); // log_info("buffer remaining: %d", (uint32_t)r->buf + MAX_BUF - (uint32_t)r->last); // log_info("n = %d, errno = %d", n, errno); if (n == 0) { // EOF //当server和浏览器保持着一个长连接的时候,浏览器突然被关闭了 //此时该fd在事件循环里会返回一个可读事件,然后就被分配给了某个 //线程,该线程read会返回0,代表对方已关闭这个fd,于是server //端也调用close log_info("read return 0"); goto close; } if (n < 0) { if (errno != EAGAIN) { log_err("read err"); goto err; } break; // errno == EAGAIN } r->last += n; check((uint32_t)r->last <= (uint32_t)r->buf + MAX_BUF, "r->last shoule <= MAX_BUF"); log_info("## ready to parse request line"); log_info("enter fv_http_parse_request_line, buf start addr=%d, last addr=%d", (int)r->pos, (int)r->last); tmp = (int)r->pos; rc = fv_http_parse_request_line(r); log_info("header length=%d", (int)r->pos - tmp); if (rc == FV_AGAIN) { continue; } else if (rc != FV_OK) { log_err("rc != FV_OK"); goto err; } log_info("request method: %.*s", (int)(r->method_end - r->request_start), (char *)r->request_start); log_info("request uri: %.*s", (int)(r->uri_end - r->uri_start), (char *)r->uri_start); log_info("## parse request line suc"); log_info("## ready to parse request body"); log_info("enter fv_http_parse_request_body, buf start addr=%d, last addr=%d", (int)r->pos, (int)r->last); tmp = (int)r->pos; rc = fv_http_parse_request_body(r); log_info("body length=%d", (int)r->pos - tmp); if (rc == FV_AGAIN) { continue; } else if (rc != FV_OK) { log_err("rc != FV_OK"); goto err; } log_info("## parse request body suc"); fv_http_out_t *out = (fv_http_out_t*)malloc(sizeof(fv_http_out_t)); rc = fv_init_out_t(out, fd); check(rc == FV_OK, "fv_init_out_t"); parse_uri((char *)r->root, r->uri_start, r->uri_end - r->uri_start, filename); if (stat(filename, &sbuf) < 0) { do_error(fd, filename, "404", "Not Found", "ferver can't find the file"); goto done; } if (!(S_ISREG(sbuf.st_mode)) || !(S_IRUSR & sbuf.st_mode)) { do_error(fd, filename, "403", "Forbidden", "ferver can't read the file"); goto done; } out->mtime = sbuf.st_mtime; fv_http_handle_header(r, out); check(list_empty(&(r->list)) == 1, "header list should be empty"); if (out->status == 0) { out->status = FV_HTTP_OK; } serve_static(fd, filename, sbuf.st_size, out); log_info("#--serve client(fd %d) suc--", fd); if (!out->keep_alive) { log_info("when serve fd %d, request header has no keep_alive, ready to close", fd); free(out); goto close; } else { free(out); } } return; // reuse tcp connections err: log_info("err when serve fd %d, ready to close", fd); close: log_info("close fd %d", fd); close(fd); done: log_info("#--serve client(fd %d) suc--", fd); }
C
#include <cs50.h> #include <stdio.h> int main(void) { int bottle = 12; int num_bottles; printf("minutes: \n"); int minutes = get_int(); if (minutes > 0) { num_bottles = bottle * minutes; printf("bottles: %d\n", num_bottles); } else { num_bottles = bottle * minutes; printf("retry: "); } }
C
/* Author: Tyler Punch * File: partB.c * Purpose: this file contains my something cool */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "gpio.h" #include "partA.h" // Blink LEDs at ascending rate void ascending(char *arr[]) { int delay = 3000000; for(int i = 0; i < 8; i ++) { usleep(delay/(i + 1)); set_gpio_low(arr[i]); usleep(delay/(i + 1)); set_gpio_high(arr[i]); } } // Blink LEDs at descending rate void descending(char *arr[]) { int delay = 3000000; for (int i = 8; i > 0; i--) { usleep(delay/i); set_gpio_low(arr[i]); usleep(delay/i); set_gpio_high(arr[i]); } }
C
static int isDelimiter(char p, char delim){ return p == delim; } static int split(char *dst[], char *src, char delim){ int count = 0; for(;;) { while (isDelimiter(*src, delim)){ src++; } if (*src == '\0') break; dst[count++] = src; while (*src && !isDelimiter(*src, delim)) { src++; } if (*src == '\0') break; *src++ = '\0'; } return count; }
C
#include<signal.h> #include<stdio.h> void main() { int ret,pid; printf("Enter pid of the process to kill:"); scanf("%d",&pid); ret=kill(pid,9); if(ret>=0) printf("process killed \n"); else printf("kill error \n"); }
C
#include "ant.h" #include <stdarg.h> #include <conio.h> #include <alloc.h> extern char log_file_name[80]; extern FILE *log_file; extern char sys_file_name[80]; extern FILE *sys_file; extern char his_file_name[80]; extern FILE *his_file; extern int **map; extern int MAP_ROWS,MAP_COLS; extern int test_run; /*///////////////////////////////////////////////// */ void oprintf( int screen_print, FILE *stream, char *format, ... ) { va_list argptr; va_start( argptr, format ); if(screen_print==-1)return; if( screen_print ) { vprintf( format,argptr ); } if( stream !=NULL ) { vfprintf( stream,format,argptr ); } va_end( argptr ); } /*/////////////////////////////////////////////////// */ void print_movename(int on_screen,int output_code) { switch (output_code & MOVE_MASK) { case NO_MOVE : oprintf(on_screen,his_file,"NOP"); break; case MOVE_FWD : oprintf(on_screen,his_file,"FWD"); break; case MOVE_RIGHT : oprintf(on_screen,his_file,"RGT"); break; case MOVE_LEFT : oprintf(on_screen,his_file,"LFT"); break; } } /**************************************************************************/ /** Print a gene: */ void print_gene(int on_screen,int format,State_machine huge *p_gene) { int i,j; int code, next; oprintf(on_screen,his_file,"Input = 0 1\n"); oprintf(on_screen,his_file," ====== ======\n"); for (i=0 ; i < N_STATES ; i++) { if(format==0) oprintf(on_screen,his_file,"State %02X : ", i); else oprintf(on_screen,his_file,"State %d : ", i); for ( j=0 ; j < 2 ; j++ ) { run_machine(p_gene, i, j, &code, &next); if(format==1) oprintf(on_screen,his_file," "); print_movename(on_screen,code); if(format==0) oprintf(on_screen,his_file,"/%02X ", (next)); else oprintf(on_screen,his_file,"/%d ", (next)); } oprintf(on_screen,his_file,"\n"); } } /**************************************************************************/ void print_gene_track( Gene_track huge *g,int on_screen ) { int i; oprintf(on_screen,his_file,"Score = %d\n", g->score); if(on_screen!=0) oprintf(on_screen,his_file,"n_children = %d\n", g->n_children); oprintf(on_screen,his_file,"Gene = "); for (i=0 ; i<GENE_SIZE ; i++) oprintf(on_screen,his_file,"%02X", (char)(g->p_gene[i]) & 0xff); oprintf(on_screen,his_file,"\n"); if(on_screen==0) oprintf(0,his_file,"\n"); } /**************************************************************************/ void print_pop_stats( Gene_track huge *gene_track_array, int n_pop) { int score_bin[90]; int i; /* Initialize */ for ( i=0 ; i<90 ; i++ ) score_bin[i] = 0; /* Count population with given score */ for ( i=0 ; i<n_pop ; i++ ) score_bin [ (gene_track_array[i].score) ] ++; /* Print out the results : */ oprintf(1,his_file,"\nPopulation Statistics :\n"); oprintf(1,his_file,"%8s %8s | %8s %8s | %8s %8s\n", "SCORE", "N_POP", "SCORE", "N_POP", "SCORE", "N_POP"); for ( i=0 ; i<90 ; i += 3 ) oprintf(1,his_file,"%8d %8d | %8d %8d | %8d %8d\n", i, score_bin[i], i+1, score_bin[i+1], i+2, score_bin[i+2]); } /**************************************************************************/ int find_ant_w_score( Gene_track huge *gene_track_array, int n_pop, int score, int start_with ) { int i; for ( i=start_with ; i < n_pop ; i++ ) if (gene_track_array[i].score == score) return(i); /* None found */ return(-1); } /**************************************************************************/ void draw_trail(void) { int i,j; textmode(64); /* Replaced "C4350" with "64", since it wasn't defined*/ textbackground(LIGHTGRAY); clrscr(); for (j=0; j<MAP_ROWS; j++) { for (i=0; i<MAP_COLS; i++) if (map[j][i]) { textcolor(BLUE); putch(254); } else { textcolor(BLACK); putch(250); } gotoxy(1,j+2); } } /**************************************************************************/ void draw_ant(Ant *p_ant) { int ch; gotoxy(p_ant->x + 1, p_ant->y + 1); textcolor(RED); /* It's a RED ANT! */ switch(p_ant->heading) { case (NORTH) : ch = 30 ; break; case (EAST) : ch = 16 ; break; case (SOUTH) : ch = 31 ; break; case (WEST) : ch = 17 ; break; }; putch(ch); gotoxy(35,3); oprintf(1,his_file,"Score = (dec)%02d", p_ant->score); gotoxy(35,4); oprintf(1,his_file,"State = (hex)%02x", p_ant->cur_state); gotoxy(35,5); oprintf(1,his_file,"Posn = (%02d,%02d)", p_ant->x, p_ant->y); } /**************************************************************************/ void erase_ant(Ant *p_ant) { int x = p_ant->x; int y = p_ant->y; gotoxy(x + 1, y + 1); if (map[y][x]) { textcolor(BLUE); putch(254); } else { textcolor(BLACK); putch(250); } } /*************************************************************************/ void examine(Gene_track huge *gene_track_array, int n_pop, int n_life_steps, int n_gen, int gen_number, int n_select, int selection_strategy, double pcross, double pmutate) { int n,j; int s,a; char save_file_name[100]; while (1) { printf("\nEXAMINE :\n"); printf("0 : Return to evolution\n"); printf("1 : View an ant in action\n"); printf("2 : View an ant's gene\n"); printf("3 : View an ant's tracking information\n"); printf("4 : View the score distribution of the entire population\n"); printf("5 : Find an ant with a particular score\n"); printf("6 : Save the current state of the experiment\n"); printf("7 : Print ants info to that moment into history file \n"); printf("8 : Exit\n"); ENTER_LOOP : printf("\nEnter your choice :"); scanf("%d", &n); if ((n<0)||(n>8)) { printf("Invalid\n"); /*n=NULL; */ goto ENTER_LOOP; } switch(n) { case(0) : return; case(1) : printf("Enter ant's # (0-%d)", n_pop - 1); scanf("%d", &n); draw_trail(); ant_life((State_machine *)(gene_track_array[n].p_gene), n_life_steps, 1); textmode(C80); textcolor(BLACK); break; case(2) : printf("Enter ant's # (0-%d)", n_pop - 1); scanf("%d", &n); oprintf(0,his_file,"------------------------------------------------------\n"); oprintf(0,his_file," Generation = [%d], Ant #[%d]\n",gen_number,n); print_gene(1,0,(State_machine *)(gene_track_array[n].p_gene)); oprintf(0,his_file,"------------------------------------------------------\n"); break; case(3) : printf("Enter ant's # (0-%d)", n_pop - 1); scanf("%d", &n); oprintf(0,his_file,"------------------------------------------------------\n"); oprintf(0,his_file," Generation = [%d], Ant #[%d]\n",gen_number,n); print_gene_track(&(gene_track_array[n]), 1); oprintf(0,his_file,"------------------------------------------------------\n"); break; case(4) : oprintf(0,his_file,"------------------------------------------------------\n"); oprintf(0,his_file," Generation = [%d], Ant #[%d]\n",gen_number,n); print_pop_stats( gene_track_array, n_pop); oprintf(0,his_file,"------------------------------------------------------\n"); break; case(5) : printf("Enter ant's # to begin searching from (0-%d) : ", n_pop - 1); scanf("%d", &n); oprintf(0,his_file,"------------------------------------------------------\n"); oprintf(0,his_file," Generation = [%d], Ant #[%d]\n",gen_number,n); oprintf(1,his_file,"Enter desired score : "); scanf("%d", &s); oprintf(0,his_file, "%d\n",s); a = find_ant_w_score( gene_track_array, n_pop, s, n); if (a >= 0) oprintf(1,his_file,"Ant #%d has score %d\n", a, s); else oprintf(1,his_file,"No more ants in list with score %d\n", s); break; case (6) : printf("Enter the name of the save file : "); scanf("%s", save_file_name); save_state(save_file_name, n_pop, n_gen, gen_number, n_life_steps, n_select, selection_strategy, pcross, pmutate, gene_track_array); break; case(7): oprintf(0,his_file," Generation = [%d]\n",gen_number,n); oprintf(0,his_file,"________________________________________________________________\n"); break; break; case(8): fprintf(stderr,"\n---------------------- Forced end of experiment ! --------------"); free_all(&gene_track_array,1); close_log(1); close_sys(1); close_his(1); exit(1); break; } } } /**************************************************************************/ int open_log(char *filename, int n_pop, int n_generations, int n_life_steps, int n_select, double pcross, double pmutate, int selection_strategy, unsigned seed_number) { extern FILE *log_file; time_t t_now; char *time_string; t_now = time(NULL); time_string = ctime(&t_now); strcpy(log_file_name, filename); log_file = fopen(filename, "w"); if (log_file == NULL) { fprintf(stderr," Couldn't open log file!"); log_file_name[0] = 0; return(1); } fprintf(log_file, "Record of GA experiment performed on %s\n\n", time_string); oprintf(0,log_file, "PARAMETERS :\n"); oprintf(0,log_file, "Random number seed = %u\n", seed_number); oprintf(0,log_file, "Population Size = %d\n", n_pop); oprintf(0,log_file, "Number of Generations = %d\n", n_generations); oprintf(0,log_file, "Lifespan = %d\n", n_life_steps); oprintf(0,log_file, "Size of gene = %d\n ", GENE_SIZE); oprintf(0,log_file, "Size of gene track = %d\n", GENE_TRACK_SIZE); oprintf(0,log_file, "Selection Fraction = %d%%\n", n_select); oprintf(0,log_file, "Selection Strategy = %s\n", selection_strategy ? "ROULETTE" : "TRUNCATE"); oprintf(0,log_file, "Crossover Rate = %.3lf\n", pcross); oprintf(0,log_file, "Mutation Rate = %.3lf\n\n", pmutate); fprintf(log_file, "%8s %8s %8s %8s\n", "GEN#", "MIN", "AVG", "MAX"); return(0); } /**************************************************************************/ void close_log(int stop) { extern FILE *log_file; time_t t_now; char *time_string; if (log_file == NULL) return; t_now = time(NULL); time_string = ctime(&t_now); if( stop ) fprintf(log_file, "\nForced end of experiment at %s\n", time_string); if( !stop ) fprintf(log_file, "\nEnd of experiment at %s\n", time_string); fclose(log_file); } /**************************************************************************/ void log_gen(int gen, int min, int max, double avg) { extern FILE *log_file; if (log_file == NULL) return; fprintf(log_file, "%8d %8d %.2f %8d\n", gen, min, avg, max); flush(log_file); } /***********************************************************************/ int open_sys(char *filename,int n_pop, int n_generations, int n_life_steps, int n_select, double pcross, double pmutate, int selection_strategy, unsigned seed_number) { extern FILE *sys_file; time_t t_now; char *time_string; t_now = time(NULL); time_string = ctime(&t_now); strcpy(sys_file_name, filename); sys_file = fopen(filename, "w"); if (sys_file == NULL) { fprintf(stderr," Couldn't open sys file!\n"); sys_file_name[0] = 0; return(1); } fprintf(sys_file, "Full record of GA experiment performed on %s\n\n", time_string); if(test_run==0) { oprintf(1,sys_file,"PARAMETERS :\n"); oprintf(1,sys_file,"Random number seed = %u\n", seed_number); oprintf(1,sys_file,"Population Size = %d\n", n_pop); oprintf(1,sys_file,"Number of Generations = %d\n", n_generations); oprintf(1,sys_file,"Lifespan = %d\n", n_life_steps); oprintf(1,sys_file,"Size of gene = %d\n", GENE_SIZE); oprintf(1,sys_file,"Size of gene track = %d\n", GENE_TRACK_SIZE); oprintf(1,sys_file,"Selection Fraction = %d%%\n", n_select); oprintf(1,sys_file,"Selection Strategy = %s\n", selection_strategy ? "ROULETTE" : "TRUNCATE"); oprintf(1,sys_file,"Crossover Rate = %.3lf\n", pcross); oprintf(1,sys_file,"Mutation Rate = %.3lf\n\n", pmutate); } return(0); } /**************************************************************************/ void close_sys(int stop) { extern FILE *sys_file; time_t t_now; char *time_string; if (sys_file == NULL) return; t_now = time(NULL); time_string = ctime(&t_now); if( stop ) fprintf(sys_file, "\nForced end of experiment at %s\n", time_string); if( !stop ) fprintf(sys_file, "\nEnd of experiment at %s\n", time_string); fclose(sys_file); } /***********************************************************************/ int open_his(char *filename,int n_pop, int n_generations, int n_life_steps, int n_select, double pcross, double pmutate, int selection_strategy, unsigned seed_number) { extern FILE *his_file; time_t t_now; char *time_string; t_now = time(NULL); time_string = ctime(&t_now); strcpy(his_file_name, filename); his_file = fopen(filename, "w"); if (his_file == NULL) { fprintf(stderr," Couldn't open history file!\n"); his_file_name[0] = 0; return(1); } print_trail(); return(0); } /**************************************************************************/ void close_his(int stop) { extern FILE *his_file; time_t t_now; char *time_string; if (his_file == NULL) return; t_now = time(NULL); time_string = ctime(&t_now); if( stop ) fprintf(his_file, "\nForced end of experiment at %s\n", time_string); if( !stop ) fprintf(his_file, "\nEnd of experiment at %s\n", time_string); fclose(his_file); } /*////////////////////////////////////////////////////////////////// */ void print_trail () { extern FILE *his_file; int i, j; oprintf(0,his_file,"------------------------ The Map --------------------------\n"); for ( j = 0; j < MAP_ROWS; ++j ) { oprintf ( 0,his_file, " " ); for ( i = 0; i < MAP_COLS; ++i ) { if( map[j][i] < 10) oprintf ( 0,his_file, " "); oprintf ( 0,his_file, "%d", map[j][i] ); } oprintf ( 0, his_file, "\n" ); } oprintf(0,his_file,"-----------------------------------------------------------\n"); }