language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/*
c---------------------------------------------------------------------c
c c
c COMPUTER PROGRAMS IN SEISMOLOGY c
c VOLUME I c
c c
c ROUTINE: GREAD c
c c
c COPYRIGHT (C) 1997 R. B. Herrmann c
c c
c Department of Earth and Atmospheric Sciences c
c Saint Louis University c
c 221 North Grand Boulevard c
c St. Louis, Missouri 63103 c
c U. S. A. c
c c
c---------------------------------------------------------------------c
*/
#include <stdio.h>
#include <string.h>
#include "callib.h"
#include "dosubs.h"
#include "calplot.h"
extern struct Gcplot Gcplt;
static void doconv(float xn, float yn, INT *ix, INT *iy);
void dv_gread(int lf,char *fname, INT NumX, INT NumY, INT LowX, INT LowY, INT HighX, INT HighY, INT Num, INT Sclx, INT Scly);
/*
Read the PageNum'th page from the file fname.
Clip the plot page about the limits (Xlow,Ylow) -> (Xhigh,Yhigh)
The origin is redefined to be the lower left corner of the
clip region. This corner is then shifted to
position (X0, Y0)
*/
void gread(char *fname, float X0, float Y0, float Xlow, float Ylow,
float Xhigh, float Yhigh, int PageNum, float tsclx, float tscly)
{
INT NumX, NumY, LowX, LowY, HighX, HighY, Num;
int lf;
INT Sclx;
INT Scly;
Num = (INT)PageNum;
Sclx = (INT)(1000.0*tsclx);
Scly = (INT)(1000.0*tscly);
doconv(X0-Xlow*tsclx, Y0-Ylow*tscly, &NumX, &NumY);
doconv(Xlow, Ylow, &LowX, &LowY);
doconv(Xhigh, Yhigh, &HighX, &HighY);
lf = strlen(fname);
dv_gread(lf,fname, (INT)NumX, (INT)NumY, (INT)LowX, (INT)LowY,
(INT)HighX, (INT)HighY, (INT)Num, (INT)Sclx, (INT)Scly);
}
static void doconv(float xn, float yn, INT *ix, INT *iy);
static void doconv(float xn, float yn, INT *ix, INT *iy){
float xx, yy;
xx = 1000. * (xn + Gcplt.xold);
yy = 1000. * (yn + Gcplt.yold);
if(xx > 1000000000.0)
*ix = 1000000000;
else if(xx < -1000000000.0)
*ix = -1000000000;
else
*ix = xx ;
if(yy > 1000000000.0)
*iy = 1000000000;
else if(yy < -1000000000.0)
*iy = -1000000000;
else
*iy = yy ;
}
|
C
|
#include <stdio.h>
double HelloWorld_dobro (int x)
{
printf("Metodo dobro!\n");
return x * 2;
}
int somar(int n, int m)
{
return n + m;
}
|
C
|
#include "ush.h"
static bool iisdigit(int c) {
int n = 0;
if (c >=48 && c <=57) {
n++;
return n;
}
else {
return n;
}
}
static bool iisalpha(int c) {
int n = 0;
if ((c >=65 && c <=90) || (c >=97 && c <=122)) {
n++;
return n;
}
else {
return n;
}
}
static bool iislower(int c) {
int n = 0;
if (c >=97 && c <=122) {
n++;
return n;
}
else {
return n;
}
}
static bool iisupper(int c) {
int n = 0;
if (c >=65 && c <=90) {
n++;
return n;
}
else {
return n;
}
}
unsigned long mx_hex_to_nbr(const char *hex) {
int len = 0;
unsigned long res = 0;
int i = 0;
while (hex[len])
len++;
while(hex[i]) {
if (iisdigit(hex[i]))
res += (hex[i] - 48) * mx_pow_rec(16,len - i - 1);
else if (iisalpha(hex[i])){
if (iislower(hex[i]))
res += (hex[i] - 87) * mx_pow_rec(16,len - i - 1);
else if (iisupper(hex[i]))
res += (hex[i] - 55) * mx_pow_rec(16,len - i - 1);
}
i++;
}
return res;
}
|
C
|
#include "../sign.h"
#include "../dh.h"
#include "print.h"
#include <stdlib.h>
#include <time.h>
#define mes_len 1
#define loop_min 0
#define loop_len 10
int main(void)
{
unsigned long long i;
/* Checking signatures */
int j;
unsigned char sk[64];
unsigned long long mlen = mes_len;
unsigned char m[mlen];
unsigned char pk[32];
unsigned char sm[64+mlen];
unsigned long long smlen;
int ch;
srand( time(NULL) );
printf("\nChecking %d signatures............. ", loop_len);
for(j=loop_min;j<=loop_min+loop_len-1;j++)
{
srand(j);
for(i=0;i<64;i++) { sk[i] = rand() % 256; }
for(i=0;i<mlen;i++) { m[i] = rand() % 256; }
keypair(pk, sk);
sign(sm, &smlen, m, mlen, pk, sk);
ch = verify(m, mlen, sm, smlen, pk);
if ( ch != 1 )
{
printf("\n%lld\n", mlen);
for(i=0;i<32;i++) { printf("%02X,", sk[i]); }
printf("\n");
for(i=0;i<mlen;i++) { printf("%02X,", m[i]); }
}
}
printf("Correct");
/* End checking signatures */
/* Checking DH */
ecp r;
fe25519 c;
group_scalar n;
group_scalar ell = {
.v = { 0x24,0x8F,0x3B,0x2B,0xA5,0xE1,0x4C,0xFA,
0xD4,0x40,0xA5,0xAA,0xE3,0x83,0x24,0xEB,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x7F }
};
/* Checking 0*base = (a^2 : b^2) */
printf("\nChecking 0*base = (a^2 : b^2)...... ");
for (i=0; i<32; i++) n.v[i] = 0;
ladder_base(&r,&n);
fe25519_mulconst(&r.X, &r.X, 0x05, 0x00); // b^2
fe25519_mulconst(&r.Z, &r.Z, 0x9F, 0x00); // a^2
fe25519_sub(&c, &r.X, &r.Z);
fe25519_freeze(&c);
if (fe25519_iszero(&c)) printf("Correct");
/* Checking 1*base = base */
printf("\nChecking 1*base = base............. ");
for (i=0; i<32; i++) n.v[i] = 0;
n.v[0] = 1;
ladder_base(&r,&n);
compress(&c,&r);
fe25519_freeze(&c);
c.v[0] = c.v[0] - 7;
if (fe25519_iszero(&c)) printf("Correct");
/* Checking ell*base = (a^2 : b^2) */
printf("\nChecking ell*base = (a^2 : b^2).... ");
ladder_base(&r,&ell);
fe25519_mulconst(&r.X, &r.X, 0x05, 0x00); // b^2
fe25519_mulconst(&r.Z, &r.Z, 0x9F, 0x00); // a^2
fe25519_sub(&c, &r.X, &r.Z);
fe25519_freeze(&c);
if (fe25519_iszero(&c)) printf("Correct");
/* Checking some key exchanges.. */
unsigned char dh_sk0[32], dh_sk1[32];
unsigned char dh_pk0[32], dh_pk1[32];
unsigned char dh_ss0[32], dh_ss1[32];
printf("\nChecking %d DH exchanges........... ", loop_len);
for(j=loop_min;j<=loop_min+loop_len-1;j++)
{
srand(j);
for(i=0;i<32;i++) { dh_sk0[i] = rand() % 256; }
for(i=0;i<32;i++) { dh_sk1[i] = rand() % 256; }
dh_keygen(dh_pk0, dh_sk0);
dh_keygen(dh_pk1, dh_sk1);
dh_exchange(dh_ss0, dh_pk1, dh_sk0);
dh_exchange(dh_ss1, dh_pk0, dh_sk1);
for(i=0;i<32;i++) { dh_ss0[i] = dh_ss0[i] - dh_ss1[i]; }
for(i=0;i<32;i++) { dh_ss0[0] = dh_ss0[0] | dh_ss0[i]; }
if( dh_ss0[0] ) printf("Incorrect!");
}
printf("Correct\n");
/* End checking DH */
/* DH */
#if 0
unsigned char dh_sk[32];
unsigned char dh_pk[32];
unsigned char dh_ss[32];
for(i=0;i<32;i++)
{
dh_sk[i] = 0;
dh_pk[i] = 0;
}
dh_sk[31] = 0x40;
dh_keygen(dh_pk, dh_sk);
printf("\n");
for(i=0;i<32;i++) { printf("%02X ", dh_pk[i]); }
printf("\n");
for(i=0;i<32;i++) { dh_sk[i] = 0; }
dh_sk[0] = 2;
dh_exchange(dh_ss, dh_pk, dh_sk);
printf("\n");
for(i=0;i<32;i++) { printf("%02X ", dh_ss[i]); }
printf("\n");
#endif
/* end DH */
/* bValues */
#if 0
ecp xq, xr, xt;
fe25519 xqX = {
.v =
{0xF6,0x7,0x48,0xC,0xD7,0xA0,0x1,0x18,
0x5F,0x41,0x1A,0x2A,0x50,0x48,0xA6,0x10,
0x4C,0xB5,0x75,0xD9,0xE3,0x1C,0xBE,0x7C,
0x7F,0xFB,0xE7,0xF4,0x9,0xC9,0x93,0x62 }
};
fe25519 xqZ = {
.v =
{0x80,0xA7,0x52,0xFD,0xF9,0x46,0x19,0xE,
0x53,0x15,0x8C,0x8A,0xB9,0x17,0x8F,0xF4,
0x8D,0x4E,0x31,0xD7,0xF0,0xA4,0xCC,0x9C,
0xD,0x79,0xB7,0xDE,0x7D,0xE5,0x5F,0x64 }
};
fe25519 xrX = {
.v =
{0xE6,0x3D,0xDE,0xC0,0xCA,0xF9,0x31,0xCB,
0xC0,0x42,0xCC,0x80,0xF5,0x9C,0x45,0xA0,
0x40,0x72,0xA5,0x27,0xDA,0x75,0x7B,0x4E,
0xB7,0xF5,0x89,0xF3,0xE6,0xAC,0xAF,0x60 }
};
fe25519 xrZ = {
.v =
{0x29,0x5B,0x0,0xFC,0xEB,0xD,0xF1,0x7E,
0x4C,0x3A,0xA5,0x7F,0x49,0x38,0xD6,0xB9,
0x7F,0xB5,0x11,0x86,0xE,0x98,0x52,0x79,
0x34,0xA,0x84,0xE8,0x58,0xE6,0x81,0x57 }
};
fe25519 xtX = {
.v =
{0x13,0x7D,0xA9,0xD3,0x13,0x5,0xE1,0xA9,
0x2B,0xB6,0x48,0x2F,0xC8,0x3F,0x1,0x2E,
0xF4,0x1B,0x7,0x6B,0x6D,0xF9,0x14,0xBD,
0xE7,0xCB,0x65,0x7C,0xC3,0x9B,0x28,0x66 }
};
fe25519 xtZ = {
.v =
{0x89,0xED,0xD6,0xBB,0x27,0x96,0xF0,0x3A,
0x31,0x54,0x90,0x2E,0xAB,0x9,0x42,0x36,
0x1E,0xCD,0xE0,0x4F,0xD1,0xA8,0x41,0xE,
0x3E,0x6A,0x31,0xFE,0x18,0xA3,0x14,0x40 }
};
fe25519 bXX,bXZ,bZZ;
int cha;
fe25519_copy(&xq.X, &xqX);
fe25519_copy(&xq.Z, &xqZ);
fe25519_copy(&xr.X, &xrX);
fe25519_copy(&xr.Z, &xrZ);
fe25519_copy(&xt.X, &xtX);
fe25519_copy(&xt.Z, &xtZ);
kl_to_mont(&xq);
kl_to_mont(&xr);
kl_to_mont(&xt);
printf("\n");
for(i=0;i<32;i++) { printf("%02X ", xq.X.v[i]); }
printf("\n");
for(i=0;i<32;i++) { printf("%02X ", xq.Z.v[i]); }
printf("\n");
printf("\n");
for(i=0;i<32;i++) { printf("%02X ", xr.X.v[i]); }
printf("\n");
for(i=0;i<32;i++) { printf("%02X ", xr.Z.v[i]); }
printf("\n");
printf("\n");
for(i=0;i<32;i++) { printf("%02X ", xt.X.v[i]); }
printf("\n");
for(i=0;i<32;i++) { printf("%02X ", xt.Z.v[i]); }
printf("\n");
bValues(&bZZ, &bXZ, &bXX, &xq, &xr);
cha = check(&bZZ, &bXZ, &bXX, &xt);
printf("%02X ", cha);
printf("\n");
#endif
/* end bValues */
/* scalarmult */
#if 0
unsigned char scal0[32],scal1[32];
group_scalar sc0,sc1,sc2;
for(i=0;i<32;i++) {
scal0[i] = 0xFF;
scal1[i] = 0xFF;
}
scal0[31] = 0xFF;
scal1[31] = 0xFF;
group_scalar_get32(&sc0,scal0);
group_scalar_get32(&sc1,scal1);
group_scalar_mul(&sc2,&sc1,&sc0);
printf("\n");
for(i=0;i<32;i++) { printf("%02X ", sc0.v[i]); }
printf("\n");
for(i=0;i<32;i++) { printf("%02X ", sc1.v[i]); }
printf("\n");
for(i=0;i<32;i++) { printf("%02X ", sc2.v[i]); }
printf("\n");
#endif
/* end scalarmult */
return 0;
}
|
C
|
//Cory Bekker
//Steve kyle
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <omp.h>
int main(int argc, char* argv[]){
int num_threads;
long long num_throws = 0;
long long throw = 0;
long long int numberInCircle = 0;
if(argc != 3){
printf("Usage: [num threads] [num throws]\n");
exit(1);
}
num_threads = strtol(argv[1], NULL, 10);
num_throws = strtol(argv[2], NULL, 10);
printf("number of threads: %d\n", num_threads);
printf("number of throws: %d\n", num_throws);
omp_set_num_threads(num_threads);//set the number of threads
double x,y,distance;
#pragma omp parallel for shared(numberInCircle)
for(throw = 0; throw < num_throws; throw++){
x = (rand()-RAND_MAX/2.0)/(RAND_MAX/2.0);
y = (rand()-RAND_MAX/2.0)/(RAND_MAX/2.0);
distance = x*x + y*y;
if(distance <= 1)
numberInCircle++;
}
printf("Pi Equals: %f\n", (4.0 * (double)numberInCircle)/(double)num_throws);
return 0;
}
|
C
|
/*
* @lc app=leetcode id=2492 lang=c
*
* [2492] Minimum Score of a Path Between Two Cities
*/
// @lc code=start
typedef struct
{
int count;
int *parent;
unsigned int *size;
} UNION;
UNION *union_find_init(int n)
{
UNION *u = malloc(sizeof(UNION));
u->count = n;
u->parent = malloc(n * sizeof(int));
u->size = malloc(n * sizeof(unsigned int));
for (int i = 0; i < n; i++)
{
u->parent[i] = i;
u->size[i] = 1;
}
return u;
}
void union_p_q(int p, int q, UNION *u)
{
int root_p = find(p, u);
int root_q = find(q, u);
if (root_p == root_q)
return;
if (u->size[root_p] > u->size[root_q])
{
u->parent[root_q] = root_p;
u->size[root_p] += u->size[root_q];
}
else
{
u->parent[root_p] = root_q;
u->size[root_q] += u->size[root_p];
}
u->count--;
}
int find(int x, UNION *u)
{
while (u->parent[x] != x)
{
u->parent[x] = u->parent[u->parent[x]];
x = u->parent[x];
}
return x;
}
int find_father(int x, UNION *u)
{
if (u->parent[x] != x)
u->parent[x] = find_father(u->parent[x], u);
return u->parent[x];
}
void union_free(UNION *u)
{
free(u->parent);
free(u->size);
free(u);
}
int min(int a, int b) { return a < b ? a : b; }
int minScore(int n, int **roads, int roadsSize, int *roadsColSize)
{
UNION *u = union_find_init(100001);
for (int i = 0; i < roadsSize; i++)
union_p_q(roads[i][0], roads[i][1], u);
int r = INT_MAX;
for (int i = 0; i < roadsSize; i++)
{
if (find_father(roads[i][0], u) == find_father(1, u))
r = min(r, roads[i][2]);
}
union_free(u);
return r;
}
// @lc code=end
// Note: Union-Find
|
C
|
/*********************************************************
* $Author: o-rooneo $
* $Date: 2015/02/10 07:36:49 $
* $Log: main.c,v $
* Revision 1.7 2015/02/10 07:36:49 o-rooneo
* Finished project with bugs. View readme for full listing
*
* Revision 1.6 2015/02/09 21:53:05 o-rooneo
* it compiles! Added queue functionality
*
* Revision 1.5 2015/02/09 01:31:51 o-rooneo
* Merged functions.c into the tail end main.c
*
* Revision 1.4 2015/02/05 16:06:39 o-rooneo
* cleaned up debug messages. added case '?'
*
* Revision 1.3 2015/02/03 00:51:42 o-rooneo
* Added keywords for RCS. Added flags and getopt
*
********************************************************/
#include <stdio.h> //perror, printf
#include <stdlib.h> //
#include <unistd.h> //
#include <sys/stat.h> //
#include <sys/queue.h> //TAIL_QUEUE
#include <limits.h> //PATH_MAX
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
TAILQ_HEAD(tailhead, entry) head;
struct tailhead *headPtr;
struct entry{ //struct to define the nodes used for the tail queue
TAILQ_ENTRY(entry) entries;
char path[PATH_MAX];
};
int sizePathFun(char *path);
int breadthFirstApply(char *path, int pathFun(char *path1));
char executable[15];
char error[PATH_MAX+30];
int flags[7]; //To keep includes lower using int instead of flag. Global to allow access from all funcs
int main(int argc, char **argv)
{
strncpy(executable, argv[0], 15);
char opt;
int i;
float flagSize = 0;
int size = 0;
char path[PATH_MAX];
for(i = 0; i<7; i++) flags[i]=0; //initialize flags to 0
while((opt = getopt(argc,argv, "ashHkLx")) != -1){ //assign flag values
switch(opt){
case 'a':
if(flags[1]){
printf("Cannot set -a with -s\n");
break;
}
flags[0]=1;
break;
case 's':
if(flags[0]){
printf("Cannot set -s with -a\n");
break;
}
flags[1]=1;
break;
case 'h':
if(flags[3]){
printf("Cannot set -h with -H\n");
break;
}
//flags[2]=1;
break;
case 'H':
if(flags[2]){
printf("Cannot set -h with -H\n");
break;
}
//flags[3]=1;
break;
case 'k':
flags[4]=1;
break;
case 'L':
flags[5]=1;
break;
case 'x':
flags[6]=1;
break;
case '?':
default:
sprintf(error, "%s %s", executable,opt);
perror(error);
break;
}
}
/* Code to support only a single file parameter
if(optind >= argc){
strcpy(path,".");
size = breadthFirstApply(path,sizePathFun);
printf("%i\t%s\n",size,path);
}else{
strcpy(path,argv[optind]);
}
*/
//Probably unnecessary but du supports multiple files so I added the functionality
if(optind < argc){
while(optind < argc){
strcpy(path,argv[optind]);
breadthFirstApply(path,sizePathFun);
optind++;
}
return 0;
}
strcpy(path,".");
breadthFirstApply(path,sizePathFun);
return 0;
}
int sizePathFun(char *path)
{
struct stat statBuffer;
if(stat(path, &statBuffer) == -1){
sprintf(error, "%s %s", executable,path);
perror(error);
return -1;
}
return statBuffer.st_blocks/2;
}
int breadthFirstApply(char *path, int pathFun(char *path1))
{
struct dirent *direntPtr;
struct stat statBuffer;
struct entry *holder, *tailPtr, *traversalPtr;
DIR *currentDir;
char fullPath[PATH_MAX];
char tempPath[PATH_MAX];
int size = 0;
int sum = 0;
int directorySize = 0;
int classSize = 0;
char sizeClass = 'B';
float tempSize = 0;
float flagValue = 0.0;
TAILQ_INIT(&head);
headPtr = &head;
holder = (struct entry *) malloc(sizeof(struct entry));
strcpy(holder->path, path);
TAILQ_INSERT_TAIL(headPtr,holder,entries);
while(!TAILQ_EMPTY(headPtr)){
strcpy(tempPath, headPtr->tqh_first->path);
tailPtr = headPtr->tqh_first; //Get the next item in the queue
TAILQ_REMOVE(headPtr,headPtr->tqh_first,entries);
free(tailPtr);
directorySize = 0;
if ((currentDir = opendir(tempPath)) == NULL) {
if(headPtr->tqh_first){
TAILQ_REMOVE(headPtr,headPtr->tqh_first,entries);
}
sprintf(error, "%s %s", executable,tempPath);
perror(error);
continue;
}
while(currentDir != NULL && (direntPtr = readdir(currentDir))){
snprintf(fullPath, PATH_MAX, "%s/%s", tempPath, direntPtr->d_name);
if(stat(fullPath, &statBuffer) == -1){
printf("File not found");
continue;
}
switch(statBuffer.st_mode & S_IFMT){
case S_IFREG:
size = pathFun(fullPath)/2;
if(size > -1){
if(flags[2]){
while((tempSize / 1024.0) > 1){
tempSize/=1024.0;
classSize++;
}
}
if(flags[3]){
while((tempSize / 1000.0) > 1){
tempSize/=1000.0;
classSize++;
}
}
if(!flags[2] || !flags[3]) directorySize += size;
if(flags[0]){
if(flags[2] || flags[3]){
switch(classSize){
case 1: sizeClass = 'K'; break;
case 2: sizeClass = 'M'; break;
}
if(classSize > 2) sizeClass = 'G';
printf("%i %c\t%s\n",tempSize,fullPath);
}else{
printf("%i\t%s\n",size,fullPath);
}
}
}
break;
case S_IFDIR:
if(strcmp(direntPtr->d_name, ".") && strcmp(direntPtr->d_name, "..")) {
holder = (struct entry *)malloc(sizeof(struct entry));
strcpy(holder->path, fullPath);
TAILQ_INSERT_TAIL(headPtr, holder, entries);
}
break;
case S_IFLNK:
if(!flags[5]){
if(lstat(fullPath, &statBuffer) == -1){
sprintf(error, "%s %s", executable,fullPath);
perror(error);
continue;
}
}
size = pathFun(fullPath);
//Following will be treated as special files. No size printed.
case S_IFBLK:
printf("Block Device: %s\n", fullPath);
break;
case S_IFCHR:
printf("Character Device: %s\n",path);
break;
case S_IFIFO:
printf("FIFO Pipe: %s\n",path);
break;
}
}
if(!flags[1] || !flags[2] || !flags[3]){
printf("%i\t %s \n", directorySize, tempPath);
}
if(flags[2] || flags[3]){
printf("%i %c\t%s\n",tempSize,fullPath);
}
if(!flags[2] || !flags[3]){
sum += directorySize;
}
closedir(currentDir);
}
return sum;
}
|
C
|
/*
* cloudfs: memory source
* By Benjamin Kittridge. Copyright (C) 2013, All rights reserved.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <semaphore.h>
#include "config.h"
#include "log.h"
#include "object.h"
#include "misc.h"
#include "cache/memory.h"
////////////////////////////////////////////////////////////////////////////////
// Class: memory
// Description: Memory cache medium
////////////////////////////////////////////////////////////////////////////////
// Section: Object cache table
const struct object_cache_intr memory_intr = {
.load = memory_load,
.get_max = memory_get_max,
.get_capacity = memory_get_capacity,
.create = memory_create,
.read = memory_read,
.write = memory_write,
.destroy = memory_destroy,
};
////////////////////////////////////////////////////////////////////////////////
// Section: Cache memory counter
static sem_t memory_stat_lock;
static uint64_t memory_used = 0;
////////////////////////////////////////////////////////////////////////////////
// Section: Initialization
void memory_load() {
sem_init(&memory_stat_lock, 0, 1);
}
////////////////////////////////////////////////////////////////////////////////
// Section: Memory maximums and capacity
uint64_t memory_get_max() {
return MEMORY_DEFAULT_MAX;
}
uint64_t memory_get_capacity() {
uint64_t __memory_used;
sem_wait(&memory_stat_lock);
__memory_used = memory_used;
sem_post(&memory_stat_lock);
return __memory_used;
}
////////////////////////////////////////////////////////////////////////////////
// Section: Cache operations
struct object_cache *memory_create() {
struct memory_cache *mem;
if (!(mem = calloc(sizeof(*mem), 1)))
stderror("calloc");
return (struct object_cache *) mem;
}
int memory_read(struct object_cache *cache, uint32_t offt, char *buf,
uint32_t *len) {
struct memory_cache *mem;
uint32_t rlen;
mem = (struct memory_cache *) cache;
if (offt >= mem->len)
rlen = 0;
else
rlen = min(mem->len - offt, *len);
if (rlen)
memcpy(buf, mem->data + offt, rlen);
*len = rlen;
return SUCCESS;
}
int memory_write(struct object_cache *cache, uint32_t offt, const char *buf,
uint32_t len) {
struct memory_cache *mem;
uint32_t rlen;
mem = (struct memory_cache *) cache;
rlen = len + offt;
if (rlen > mem->len) {
sem_wait(&memory_stat_lock);
memory_used += rlen - mem->len;
sem_post(&memory_stat_lock);
if (!(mem->data = realloc(mem->data, rlen)))
stderror("realloc");
mem->len = rlen;
}
memcpy(mem->data + offt, buf, len);
return SUCCESS;
}
int memory_destroy(struct object_cache *cache) {
struct memory_cache *mem;
mem = (struct memory_cache *) cache;
sem_wait(&memory_stat_lock);
assert(memory_used >= mem->len);
memory_used -= mem->len;
sem_post(&memory_stat_lock);
if (mem->data)
free(mem->data);
free(mem);
return SUCCESS;
}
|
C
|
/*
* Title: showargv.c (display argv-array)
* Created: 04 Dec 2019
* Modified:
* 05 Dec 2019, add show_argv2(), for cases where verb differs
*/
#define CUR_PTYPES
#include "ptypes.h"
MODULE_ID("$Id: showargv.c,v 12.2 2019/12/05 10:07:19 tom Exp $")
/*
* Function: Displays a command + argument-string, using argv array.
*
* Arguments: fp - file-pointer to which to write result
* argv - list of arguments, terminated by NULL
* compat - true to add a trailing blank like "shoarg()"
*/
static void
show_argv_x(FILE *fp,
const char *verb,
char **argv,
int compat)
{
int ch;
int first = TRUE;
const char *arg;
fputc('%', fp);
while ((arg = *argv++) != NULL) {
if (first)
arg = verb;
first = FALSE;
fputc(' ', fp);
while ((ch = UCH(*arg++)) != EOS) {
if (valid_shell_char(ch)) {
if (ch == ' ' || ch == '\\')
fputc('\\', fp);
fputc(ch, fp);
} else if (ch < ' ') {
fputc('^', fp);
fputc(ch | '@', fp);
} else if (ch == 127) {
fputc('^', fp);
fputc('?', fp);
} else {
fprintf(fp, "\\%03o", ch);
}
}
}
if (compat)
fputc(' ', fp); /* compat with shoarg */
fputc('\n', fp);
}
void
show_argv(FILE *fp,
char **argv)
{
show_argv_x(fp, argv[0], argv, TRUE);
}
void
show_argv2(FILE *fp,
const char *verb,
char **argv)
{
show_argv_x(fp, verb, argv, TRUE);
}
/******************************************************************************/
#ifdef TEST
_MAIN
{
(void) argc;
(void) argv;
exit(EXIT_FAILURE);
/*NOTREACHED */
}
#endif /* TEST */
|
C
|
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <time.h>
#include <string.h>
#define PORT 8080
int main(int argc, char* argv[]){
char sendBuff[1025];
char recvBuff[1025];
time_t ticks;
int sockfd, connfd, len;
struct sockaddr_in server_addr, client_addr;
int clilen = sizeof(client_addr);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1){
printf("Socket creation failed... \n");
}
else{
printf("Socket successfully created... \n");
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
if(bind(sockfd, &server_addr, sizeof(server_addr)) != 0){
printf("Socket bind failed,,, \n");
}
else{
printf("Socket successfully binded... \n");
}
if(listen(sockfd,5) != 0){
printf("Listen failed... \n");
}
else{
printf("Server is listening... \n");
}
int n = 0;
while(1){
connfd = accept(sockfd, &client_addr, &clilen);
while(1){
ticks = time(NULL);
snprintf(sendBuff, sizeof(sendBuff), "%.24s\r\n", ctime(&ticks));
printf("%s",sendBuff);
write(connfd, sendBuff, strlen(sendBuff));
bzero(recvBuff, sizeof(recvBuff));
n = read(connfd, recvBuff, sizeof(recvBuff)) - 1;
if (n < 0){
printf("Read fail. n = %d\n",n);
}
else{
recvBuff[n] = 0;
printf("n = %d\n",n);
printf("%s\n",recvBuff);
}
while(time(NULL) - ticks < 5);
}
}
return 0;
}
|
C
|
void arrcpy(char* dstarr,int *start,char* src) {
while(*src)
dstarr[(*start)++] = *(src++);
}
|
C
|
/*
** parallel.c for bswireframe in /B1-MUL/bswireframe/projections
**
** Made by Quentin Laille
** Login <QuentinLaille@epitech.net>
**
** Started on Fri Nov 18 11:43:20 2016 Quentin Laille
** Last update Fri Dec 9 22:39:17 2016 Laille
*/
#include "my_wireframe.h"
sfVector2i my_parallel_projection(sfVector3f input, float angle)
{
sfVector2i new;
float rad;
rad = (angle * M_PI / 180.0);
new.x = input.x - (input.y * cosf(rad));
new.y = (input.y * cosf(rad)) - input.z;
return (new);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <GL/glut.h>
int o;
void initRendering(void);
void drawScene(void);
void keyboardToggler(unsigned char, int, int);
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowPosition(300, 300);
glutInitWindowSize(400, 400);
glutCreateWindow("GG!");
o = 0;
//scanf("Enter choice: %d\n", &o);
initRendering();
glutKeyboardFunc(keyboardToggler);
//glutReshapeFunc(resizeWindow);
glutDisplayFunc(drawScene);
glutMainLoop();
//glutPostRedisplay();
return 0;
}
void initRendering(void)
{
glEnable(GL_DEPTH_TEST);
glPointSize(8);
glLineWidth(4);
//fprintf(stderr, "OpenGL version: %s\n", glGetString(GL_VERSION));
}
void drawScene(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
switch(o)
{
case 0:
glColor3f(1.0, 1.0, 1.0);
break;
case 1:
glBegin(GL_POINTS);
glVertex2f(0.0, 0.0);
glVertex2f(0.0, 0.5);
glVertex2f(0.5, 0.0);
glVertex2f(-0.5, 0.0);
glVertex2f(0.0, -0.5);
glVertex2f(0.5, 0.5);
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd();
break;
case 2:
glBegin(GL_LINES);
glVertex2f(0.0, 0.0);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -1.0);
glVertex2f(0.3, 0.0);
glEnd();
break;
case 3:
glBegin(GL_TRIANGLES);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(0.3, 1.0);
glVertex2f(0.7, 0.1);
glVertex2f(0.9, 1.0);
glEnd();
break;
default:
fprintf(stderr, "LOL!\n");
}
glFlush();
}
void keyboardToggler(unsigned char c, int x, int y)
{
switch(c)
{
case 27:
exit(1);
break;
default:
o = (int) (c - '0');
//fprintf(stderr, "\to = %d\n", o);
glutPostRedisplay();
break;
}
}
|
C
|
#include<stdio.h>
#include<conio.h>
struct student{
int rollno;
char name[10];
int regno;
}s1[3];
void main()
{
int i;
for(i=0;i<=1;i++)
{
printf("enter rollno of %d student",i+1);
scanf("%d",&s1[i].rollno);
printf("enter regno of %d student",i+1);
scanf("%d",&s1[i].regno);
printf("enter name of %d student",i+1);
fflush(stdin);
gets(s1[i].name);
}
for(i=0;i<=1;i++)
{
printf("rollno of %d student is\t",i+1);
printf("%d\n",s1[i].rollno);
printf("regno of %d student is\t",i+1);
printf("%d\n",s1[i].regno);
printf("name of %d student is\t",i+1);
puts(s1[i].name);
}
getch();
}
|
C
|
#include "set.h"
#include "memory.h"
#include <stdint.h>
#include <string.h>
#define THRESHOLD (285)
#define N_PROBES (3)
s_cache_info cache;
s_memory_info memory;
s_set **potentially_conflict_sets = NULL;
size_t n_potentially_conflict_sets = 0;
// s_set **eviction_sets = NULL;
// size_t n_eviction_sets = 0;
s_set *eviction_set = NULL;
int probe(const s_set *set, const void *candidate) {
s_element *l;
size_t data;
size_t a, d;
size_t ts;
size_t i;
size_t cnt;
if(!set)
return 0;
printf("Probing %p:", candidate);
cnt = 0;
for(i = 0; i < N_PROBES; i++) {
// read candidate
data = *(size_t *)candidate;
// foreach l in set do
for(l = set->elements; l != NULL; l = l->next)
// read l
data = *(size_t *)get_addr(l);
// measure time to read candidate
asm volatile ("cpuid; rdtsc" : "=a" (a), "=d" (d) : : "ebx", "ecx");
ts = (a | ((uint64_t)d << 32));
data = *(size_t *)candidate;
asm volatile ("cpuid; rdtsc" : "=a" (a), "=d" (d) : : "ebx", "ecx");
ts = (a | ((uint64_t)d << 32)) - ts;
// return time > threshold
printf("\t%lu", ts);
if(ts > THRESHOLD)
++cnt;
}
printf("\t(%lu/%lu)", cnt, (size_t)N_PROBES);
if(cnt > 0)
printf("\t(Cache miss)");
printf("\n");
return (cnt > 0);
}
int randomize_lines(s_set *set) {
s_element *e1, *e2;
void *addr_tmp;
size_t r1, r2;
size_t tmp;
size_t i;
if(!set)
return -1;
for(i = 0; i < set->n_elements; i++) {
r1 = rand() % set->n_elements;
r2 = rand() % set->n_elements;
if(r1 == r2)
continue;
else if(r1 > r2) {
tmp = r1;
r1 = r2;
r2 = tmp;
}
e1 = get_element_by_idx(set, r1);
e2 = get_element_by_idx(set, r2);
addr_tmp = get_addr(e1);
set_addr(e1, get_addr(e2));
set_addr(e2, addr_tmp);
}
return 0;
}
int init_relative_complement(s_set *set_A, const s_set *set_B) { // Result = A - B
s_element *element;
s_element *i;
if(!set_A || !set_B)
return -1;
for(i = set_B->elements; i != NULL; i = i->next)
delete_element_by_addr(set_A, get_addr(i));
return 0;
}
int init_potentially_conflict_sets(void) {
s_element *element;
size_t N_BITS_UPPER = 0; // bit index 17-?
size_t N_BITS_SET_INDEX = 11; // bit index 6-16
size_t N_BITS_LOWER = 6; // bit index 0-5
size_t offset;
size_t i, j, k;
for(i = memory.size >> (N_BITS_SET_INDEX + N_BITS_LOWER); i > 0; i = i >> 1)
++N_BITS_UPPER;
n_potentially_conflict_sets = 1 << N_BITS_SET_INDEX;
potentially_conflict_sets = (s_set **)malloc(sizeof(s_set *) * n_potentially_conflict_sets);
if(!potentially_conflict_sets)
return -1;
memset(potentially_conflict_sets, 0, sizeof(s_set *) * n_potentially_conflict_sets);
for(i = 0; i < n_potentially_conflict_sets; i++) {
potentially_conflict_sets[i] = create_set();
for(j = 0; j < (1 << N_BITS_UPPER); j++) {
for(k = 0; k < (1 << N_BITS_LOWER); k += memory.line_size) {
offset = (j << (N_BITS_SET_INDEX + N_BITS_LOWER)) + (i << N_BITS_LOWER) + k;
if(offset >= memory.size)
continue;
insert_element_by_addr(potentially_conflict_sets[i], (void *)((size_t)memory.ptr + offset));
}
}
}
return 0;
}
int free_potentially_conflict_sets(void) {
size_t i;
for(i = 0; i < n_potentially_conflict_sets; i++)
free_set(&potentially_conflict_sets[i]);
potentially_conflict_sets = NULL;
n_potentially_conflict_sets = 0;
return 0;
}
int init_eviction_set(const size_t set_index) {
s_set *lines, *conflict_set, *set_tmp, *set_tmp2;
s_element *candidate, *l, *element;
// randomize lines
lines = potentially_conflict_sets[set_index];
randomize_lines(lines);
// conflict_set <- {}
conflict_set = create_set();
// foreach candidate in lines do
for(candidate = lines->elements; candidate != NULL; candidate = candidate->next)
// if not probe(conflict_set, candidate) then
if(!probe(conflict_set, get_addr(candidate)))
// insert candidate into conflict_set
insert_element_by_addr(conflict_set, get_addr(candidate));
print_set(conflict_set, "* Conflict set");
// // foreach candidate in lines - conflict_set do
// set_tmp = copy_set(lines);
// init_relative_complement(set_tmp, conflict_set);
// for(candidate = set_tmp->elements; candidate != NULL; candidate = candidate->next) {
// // if probe(conflict_set, candidate) then
// if(probe(conflict_set, get_addr(candidate))) {
// // eviction_set <- {}
// eviction_set = create_set();
// // foreach l in conflict_set do
// for(l = conflict_set->elements; l != NULL; l = l->next) {
// // if not probe(conflict_set - {l}, candidate) then
// set_tmp2 = copy_set(conflict_set);
// delete_element_by_addr(set_tmp2, get_addr(l));
// if(!probe(set_tmp2, get_addr(candidate)))
// // insert l into eviction_set
// insert_element_by_addr(eviction_set, get_addr(l));
// free_set(&set_tmp2);
// }
// // output eviction_set
// if(eviction_set->n_elements) {
// print_set(eviction_set, "* Eviction set");
// getchar();
// }
// // conflict_set <- conflict_set - eviction_set
// init_relative_complement(conflict_set, eviction_set);
// free_set(&eviction_set);
// }
// }
// free_set(&set_tmp);
free_set(&conflict_set);
}
int init_eviction_sets(void) {
size_t i;
// n_eviction_sets = n_potentially_conflict_sets;
// eviction_sets = (s_set **)malloc(sizeof(s_set *) * n_eviction_sets);
// if(!eviction_sets)
// return -1;
// memset(eviction_sets, 0, sizeof(s_set *) * n_eviction_sets);
for(i = 0; i < n_potentially_conflict_sets; i++)
init_eviction_set(i);
return 0;
}
int free_eviction_sets(void) {
// size_t i;
// if(eviction_sets == NULL)
// return 0;
// for(i = 0; i < n_eviction_sets; i++)
// free_set(&eviction_sets[i]);
// eviction_sets = NULL;
// n_eviction_sets = 0;
return 0;
}
int main(const int argc, const char *argv[]) {
srand(time(NULL));
/* Steps for preparation */
init_cache_info(&cache);
print_cache_info(cache);
init_memory_info(&memory, cache);
print_memory_info(memory);
init_potentially_conflict_sets();
// init_eviction_sets();
init_eviction_set(0xFF);
/* Steps for attack */
// while(1) {
// PRIME();
// IDLE();
// probe();
// }
/* Steps for finalization */
free_memory_info(&memory);
free_potentially_conflict_sets();
// free_eviction_sets();
free_set(&eviction_set);
return 0;
}
|
C
|
#include <stdio.h>
#include <ctype.h>
void First(char[],char );
void addToResult(char[],char );
int numofprod;
char prodset[10][10];
int main(){
int i;
char choice;
char c;
char result[20];
printf("How many productions: ");
scanf(" %d",&numofprod);
printf("Enter all the productions:\n");
for(i=0;i<numofprod;i++)
{
scanf(" %s",prodset[i]);
}
do{
printf("Find the First of: ");
scanf(" %c",&c);
First(result,c);
printf("\n First(%c) = { ",c);
for(i=0;result[i] != '\0'; i++)
printf(" %c",result[i]);
printf("}\n");
printf("Press y to continue: ");
scanf(" %c",&choice);
}while(choice == 'y' || choice == 'Y');
}
void First(char* Result, char c)
{
int i,j,k;
char subresult[20];
int foundepsilon;
subresult[0] = '\0';
Result [0] = '\0';
if(!isupper(c))
{
addToResult(Result,c);
return;
}
for(i=0;i<numofprod;i++)
{
if(prodset[i][0] == c)
{
if(prodset[i][2] == '$')
addToResult(Result,'$');
else
{
j=2;
while(prodset[i][j] != '\0')
{
foundepsilon = 0;
First(subresult,prodset[i][j]);
for(k=0;subresult[k]!='\0';k++)
addToResult(Result,subresult[k]);
for(k=0; subresult[k]!='\0' ; k++)
{
if(subresult[k] == '$'){
foundepsilon = 1;
break;
}
}
if(!foundepsilon)
break;
j++;
}
}
}
}
}
void addToResult(char* Result, char val)
{
int k;
for(k=0;Result[k] != '\0' ; k++)
{
if(Result[k] == val)
return;
}
Result[k] = val;
Result[k+1] = '\0';
}
|
C
|
#include <stdio.h>
#include <time.h>
struct timespec diff(struct timespec start, struct timespec end)
{
struct timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0) {
temp.tv_sec = end.tv_sec-start.tv_sec-1;
temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec-start.tv_sec;
temp.tv_nsec = end.tv_nsec-start.tv_nsec;
}
return temp;
}
int main(void){
int a = 1;
int b = 1;
int c;
struct timespec start,end;
for(int n = 0; n < 10 ; n++){
clock_gettime(CLOCK_MONOTONIC,&start);
c = a * b;
clock_gettime(CLOCK_MONOTONIC,&end);
struct timespec d = diff(start,end);
long e = d.tv_sec * 1000000000 + d.tv_nsec;
printf("%d - th : %ld \n",n+1,e);
}
}
|
C
|
#include "binary_trees.h"
/**
* binary_tree_leaves - function that counts the leaves in a binary tree
* @tree: pointer to the root node of the tree
*
* Return: number of leaves or 0
*/
size_t binary_tree_leaves(const binary_tree_t *tree)
{
size_t left_size, right_size;
if (!tree)
return (0);
if (!tree->left && !tree->right)
return (1);
else
{
left_size = binary_tree_size(tree->left);
right_size = binary_tree_size(tree->right);
return (left_size + right_size);
}
}
|
C
|
#include<stdio.h>
#include<string.h>
int max(int a, int b)
{
return (a > b)? a : b;
}
int lcs_length(char x[],char y[],int m,int n)
{
char c[m][n];
int i,j;
for(i=0;i<=m;i++)
c[i][0]=0;
for(i=0;i<=m;i++)
c[0][i]=0;
for (i=0; i<=m; i++)
{
for (j=0; j<=n; j++)
{
if (x[i] == y[j])
c[i][j] = c[i-1][j-1] + 1;
else
c[i][j] = max(c[i-1][j], c[i][j-1]);
}
}
return c[m][n];
}
void main()
{
char x[50],y[50];
int i,m,n,length;
printf("Enter the string 1:");
gets(x);
printf("Enter the string 2:");
gets(y);
m=strlen(x);
n=strlen(y);
length=lcs_length(x,y,m,n);
printf("Length of the LCS is :%d",length);
}
|
C
|
#include<stdlib.h>
#include<stdio.h>
int main()
{
int i=1 , n , j=1 , k , p;
scanf("%d",&n);
if(n>2)
{
for(p=1;p<(n-1);p++)
{
k=i+j;
i=j;
j=k;
}
}
else
{
k=1;
}
printf("%d!=%d",n,k);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: denis <denis@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/05/06 19:00:30 by denis #+# #+# */
/* Updated: 2020/08/28 15:09:09 by denis ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *allocate_new(char *balance, int pos)
{
char *new_balance;
int i;
balance += pos;
i = 0;
if (!(new_balance = (char*)malloc(sizeof(char) * (ft_strlen(balance) + 1))))
return (0);
while (*balance)
new_balance[i++] = *balance++;
new_balance[i] = '\0';
return (new_balance);
}
char *allocate_empty_line(char *line)
{
line = (char*)malloc(sizeof(char) * 1);
*line = '\0';
return (line);
}
char *init_line(char *s2)
{
char *res;
int i;
i = 0;
if (!(res = (char*)malloc(sizeof(char) * (ft_strlen(s2) + 1))))
return (0);
while (*s2 && *s2 != '\n')
res[i++] = *s2++;
res[i] = '\0';
return (res);
}
int finish_gnl(char **line, int count)
{
if (!(*line))
*line = allocate_empty_line("\0");
if (count < 0)
return (-1);
return (0);
}
int get_next_line(int fd, char **line)
{
int count;
char buff[BUFFER_SIZE + 1];
static char *balance;
int flag;
flag = 0;
*line = check_balance(&balance, *line, &flag);
if (fd < 0 || !line || flag == -1 || BUFFER_SIZE < 1)
return (-1);
if (flag == 1)
return (1);
while ((count = read(fd, buff, BUFFER_SIZE)) >= 0)
{
write(1, " \b\b", 4);
if (count == 0 && (*line == NULL || **line == 0))
return (0);
buff[count] = '\0';
if (!(*line = ft_strjoin_gnl(*line, buff)))
return (-1);
if (find_pos(buff))
return (init_balance(buff, find_pos(buff), &balance));
}
balance = NULL;
return (finish_gnl(line, count));
}
|
C
|
#include <assert.h>
#include <stdio.h>
#include <string.h>
char *mystrcat(char*, const char*);
int main(void) {
char s[1000];
assert( (strcpy(s, "pine"), !strcmp("pineapple", mystrcat(s, "apple"))) );
assert( (strcpy(s, ""), !strcmp("apple", mystrcat(s, "apple"))) );
assert( (strcpy(s, "pine"), !strcmp("pine", mystrcat(s, ""))) );
assert( (strcpy(s, ""), !strcmp("", mystrcat(s, ""))) );
assert( (strcpy(s, "uwaaaaaaaaaaaaaaaaaa"), !strcmp("uwaaaaaaaaaaaaaaaaaahyaaaaaaaaaaaaaaaaaaaa", mystrcat(s, "hyaaaaaaaaaaaaaaaaaaaa"))) );
printf("%s\n", (strcpy(s, "pen"), mystrcat(s, "pineapple"), mystrcat(s, "apple"), mystrcat(s, "pen")));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#define PORT 8000
#define MAX_CONNECTIONS 3
#define BUFFER_SIZE 10
void sendfile(char filename[1024], int *fileDes, int conn_fd)
{
// printf("in sendfile\n");
int fd = *fileDes,valread;
long int filelength = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
long int length_to_read = filelength;
printf("file length is %ld\n", filelength);
valread = send(conn_fd,&filelength,sizeof(long int),0);
float progress = 0;
while (1)
{
char buffer[BUFFER_SIZE] = {0};
if (length_to_read > BUFFER_SIZE)
{
valread = read(fd, buffer, BUFFER_SIZE);
send(conn_fd, buffer, BUFFER_SIZE, 0);
printf("buffer size is %d and buffer is %s\n", valread,buffer);
length_to_read = length_to_read - BUFFER_SIZE;
}
else if (length_to_read <= BUFFER_SIZE)
{
valread = read(fd, buffer, length_to_read);
send(conn_fd, buffer, length_to_read, 0);
printf("buffer size is %d and buffer is %s\n", valread,buffer);
break;
}
progress = ((float)(filelength - length_to_read)/filelength)*100;
printf("Sending... "); printf("%0.2f percent\r",progress);
}
printf("File sent.\n\n");
close(fd);
return;
}
int main()
{
//creating server socket
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket < 0)
{
perror("Problem in creating the socket");
exit(EXIT_FAILURE);
}
// This is to lose the pesky "Address already in use" error message
int opt = 1;
if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) // SOL_SOCKET is the socket layer itself
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(PORT);
server_address.sin_addr.s_addr = INADDR_ANY;
if (bind(server_socket, (struct sockaddr *)&server_address, sizeof(server_address)) < 0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_socket, MAX_CONNECTIONS) < 0)
{
perror("Listen error");
exit(EXIT_FAILURE);
}
int conn_fd, addrlen = sizeof(server_address);
if ((conn_fd = accept(server_socket, (struct sockaddr *)&server_address, (socklen_t *)&addrlen)) < 0)
{
perror("Accept error");
exit(EXIT_FAILURE);
}
char conn[1024] = {0};
int valread = read(conn_fd, conn, 1024);
printf("%s\n", conn);
char *connection = "Connected with server.\n";
send(conn_fd, connection, strlen(connection), 0);
while (1)
{
char filename[1024] = {0};
valread = read(conn_fd, filename, sizeof(filename));
// printf("Checking if file '%s' is available....\n",filename);
int fd = open(filename, O_RDONLY);
if (fd < 0)
{
// perror("Error");
send(conn_fd, "no", sizeof("no"), 0);
// continue;
}
else
{
printf("Required file is available.\n");
send(conn_fd, "yes", sizeof("yes"), 0);
sendfile(filename,&fd,conn_fd);
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include<GL/gl.h>
#include<GL/glut.h>
#define sign(x) ((x>0)?1:((x<0)?-1:0)) //Returns 1 if x>0, -1 if x<0, 0 otherwise
int x1,x2, y2,x3,x4,y3,y4,t1;
int x11,y11,x21,y21,x31,x41,y31,y41;
int xm1,ym1,xm2,ym2,xm3,ym3,xm4,ym4;
void plotpt(int x, int y) { //Plot a single point/pixel on window
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
}
void bres_general(int p,int q,int r,int s)
{
int dx, dy,x, y, pk, s1, s2, flag=0, t;
dx = abs(q-p); //Find dx and dy
dy = abs(s-r);
s1 = sign(q-p);
s2 = sign(s-r);
if(dy > dx){ //Swap values of dx and dy if dy > dx
t = dx;
dx = dy;
dy = t;
flag = 1;
}
pk = 2 * dy - dx; //Calculate value of decision parameter
x = p;
y = r;
int i;
for( i = 1; i <= dx; i++)
{
plotpt(x,y);
while(pk >= 0)
{
if(flag==1) {
x = x + s1;
}
else
{
y = y + s2;
pk = pk - 2* dx;
}
}
if(flag==1) {
y = y + s2;
}
else {
x = x + s1;
}
pk = pk + 2 * dy;
}
glFlush();
}
void draw()
{
bres_general(x1,x2,t1,y2);
bres_general(x3,x4,y3,y4);
bres_general(x2,x4,y2,y4);
bres_general(x1,x3,t1,y3);
bres_general(x11,x21,y11,y21);
bres_general(x31,x41,y31,y41);
bres_general(x21,x41,y21,y41);
bres_general(x11,x31,y11,y31);
bres_general(xm1,xm2,ym1,ym2);
bres_general(xm2,xm3,ym2,ym3);
bres_general(xm3,xm4,ym3,ym4);
bres_general(xm4,xm1,ym4,ym1);
}
void init() {
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); //Initialise Display Mode, Window Position and Window size
glutInitWindowPosition(0,0);
glutInitWindowSize(640, 480);
glutCreateWindow("Geometric Pattern");
glClearColor(0.0,0.0,0.0,0);
glColor3f(1.0,1.0,1.0);
gluOrtho2D(0,640,0,480);
}
int main(int argc, char **argv)
{
printf("\n Enter values of x1,y1: ");
scanf("%d %d",&x1,&t1);
printf("\n Enter values of x2,y2: ");
scanf("%d %d",&x2,&y2);
printf("\nEnter values of points(x3,y3)");
scanf("%d%d",&x3,&y3);
printf("\nEnter values of points(x4,y4)");
scanf("%d%d",&x4,&y4);
xm1=(x1+x2)/2;
ym1=(t1+y2)/2;
xm2=(x1+x3)/2;
ym2=(t1+y3)/2;
xm3=(x3+x4)/2;
ym3=(y3+y4)/2;
xm4=(x2+x4)/2;
ym4=(y2+y4)/2;
x11=(xm1+xm2)/2;
y11=(ym1+ym2)/2;
x21=(xm1+xm4)/2;
y21=(ym1+ym4)/2;
x31=(xm2+xm3)/2;
y31=(ym2+ym3)/2;
x41=(xm3+xm4)/2;
y41=(ym3+ym4)/2;
glutInit(&argc, argv);
init();
glutDisplayFunc(draw);
glutMainLoop();
return 0;
}
/*test data
x1,y1=100,100
x2,y2=100,300
x3,y3=300,100
x4,y4=300,300*/
|
C
|
#include "unit-test.h"
#include <stdio.h>
/** Module for unit test. Call UNIT_TEST(expr) to verify that expr
* is true.
*/
static int num_tests = 0;
static int num_failures = 0;
/** Implementation function called by UNIT_TEST() macro; do not call
* directly
*/
void
unit_test(const char *fileName, int lineNumber, const char *functionName,
int exprValue, const char *expr)
{
if (!exprValue) {
fprintf(stderr, "%s:%d: %s(): %s failed\n", fileName, lineNumber,
functionName, expr);
num_failures++;
}
num_tests++;
}
/** Return # of unit tests performed so far */
int num_total_unit_test(void) { return num_tests; }
/** Return # of unit test failures encountered so far */
int num_fail_unit_test(void) { return num_failures; }
/** If there are unit test failures, print a report on out. */
void report_unit_test(FILE *out) {
if (num_failures > 0) {
fprintf(out, "%d/%d failures\n", num_failures, num_tests);
}
}
/** Reset unit-test counts */
void reset_unit_test(void) { num_tests = num_failures = 0; }
|
C
|
/*
shadow_omni.h - shadow for omnidirectional dlights and PCF filtering
Copyright (C) 2015 Uncle Mike
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#ifndef SHADOW_OMNI_H
#define SHADOW_OMNI_H
#extension GL_EXT_gpu_shader4 : require
#define NUM_SAMPLES 4.0
uniform samplerCubeShadow u_ShadowMap;
float depthCube( vec3 coord, mat4 lightProjection )
{
vec3 abs_coord = abs( coord );
float fs_z = -max( abs_coord.x, max( abs_coord.y, abs_coord.z ));
vec4 clip = lightProjection * vec4( 0.0, 0.0, fs_z, 1.05 ); // z-bias
float depth = ( clip.z / clip.w ) * 0.5 + 0.5;
return shadowCube( u_ShadowMap, vec4( -coord.z, -coord.x, coord.y, depth )).r;
}
float ShadowOmni( mat4 lightProjection, vec3 I, vec2 texel )
{
#if defined( SHADOW_PCF2X2 ) || defined( SHADOW_PCF3X3 )
vec3 forward, right, up;
forward = normalize( I );
MakeNormalVectors( forward, right, up );
#if defined( SHADOW_PCF2X2 )
float filterWidth = texel.x * length( I ) * 2.0; // PCF2X2
#elif defined( SHADOW_PCF3X3 )
float filterWidth = texel.x * length( I ) * 3.0; // PCF3X3
#else
float filterWidth = texel.x * length( I ); // Hardware PCF1X1
#endif
// compute step size for iterating through the kernel
float stepSize = 4.0 * filterWidth / NUM_SAMPLES;
float shadow = 0.0;
for( float i = -filterWidth; i < filterWidth; i += stepSize )
{
for( float j = -filterWidth; j < filterWidth; j += stepSize )
{
shadow += depthCube( I + right * i + up * j, lightProjection );
}
}
// return average of the samples
shadow *= ( 4.0 / ( NUM_SAMPLES * NUM_SAMPLES ));
return shadow;
#else
return depthCube( I, lightProjection ); // fast path
#endif
}
#endif//SHADOW_OMNI_H
|
C
|
// Program to test arrays using matrix multiplication
int main()
{
int a[100], b[100], res[100], r1, c1, r2, c2, i, j, k;
prints("Enter rows and columns for first matrix (r1*c1 <= 100) :\n");
r1 = scani(); c1 = scani();
prints("Enter rows and columns for second matrix (r1*c1 <= 100) :\n");
r2 = scani(); c2 = scani();
// If column of first matrix in not equal to row of second matrix,
// ask the user to enter the size of matrix again.
while (c1!=r2)
{
prints("Error! column of first matrix not equal to row of second\n");
prints("Enter rows and columns for first matrix :\n");
r1 = scani(); c1 = scani();
prints("Enter rows and columns for second matrix :\n");
r2 = scani(); c2 = scani();
}
// Storing elements of first matrix.
prints("Enter elements of matrix 1 in row major form :\n");
for(i = 0; i < r1; ++i)
for(j = 0; j < c1; ++j)
{
a[i*c1 + j] = scani();
}
// Storing elements of second matrix.
prints("Enter elements of matrix 2 in row major form :\n");
for(i = 0; i < r2; ++i)
for(j = 0; j < c2; ++j)
{
b[i*c2 + j] = scani();
}
// Multiplying matrix a and b and storing in array mult.
for(i = 0; i < r1; ++i){
for(j = 0; j < c2; ++j){
res[i*c2 + j] = 0;
for(k = 0; k < c1; ++k)
{
res[i*c2 + j] += a[i*c1 + k] * b[k*c2 + j];
}
}
}
// Displaying the multiplication of two matrix.
prints("Output Matrix :\n");
for(i = 0; i < r1; ++i)
for(j = 0; j < c2; ++j)
{
printi(res[i*c2 + j]);
if(j == c2-1)
prints("\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_fft_complex.h>
#include <gsl/gsl_errno.h>
#define T 1.0
const double sigma = T/20.;
double function(double t)
{
double arg = 2 * M_PI / T * t;
return ( sin(arg) + sin(2*arg) + sin(3*arg) );
}
// losuje liczbe z zakresu -0.5 do 0.5
double U_rand()
{
double r = (double)rand() / (RAND_MAX +1.);
return (r - 0.5);
}
//funkcja do podejrzenia wartosci tablicy
void show(double* array, unsigned int dim)
{
for(unsigned int a = 0; a < dim; a++)
printf("%g\n", array[a]);
printf("\n\n");
}
//***************************************************************************************
int main()
{
FILE* fp1 = fopen("k8.dat", "w+");
FILE* fp2 = fopen("k10.dat", "w+");
FILE* fp3 = fopen("k12.dat", "w+");
const double t_max = 3*T;
int k[] = {8, 10, 12};
for(unsigned int kk = 0; kk < 3; kk++)
{
unsigned int N = pow(2, k[kk]);
const double dt = t_max/N;
//---------------------------- alokacja pamieci
double* f = malloc(2*N*sizeof(double));
double* g1 = malloc(2*N*sizeof(double));
double* g2 = malloc(2*N*sizeof(double));
//---------------------------- wypelnienie tablic
for(unsigned int i = 0; i < N; i++)
{
f[2*i] = function(dt*i) + U_rand();
switch(kk)
{
case 0:
fprintf(fp1, "%g %g\n", dt*i, f[2*i]);
break;
case 1:
fprintf(fp2, "%g %g\n", dt*i, f[2*i]);
break;
case 2:
fprintf(fp3, "%g %g\n", dt*i, f[2*i]);
break;
}
g1[2*i] = g2[2*i] = exp(-pow(dt*i, 2) / ( 2*pow(sigma, 2) ) ) / (sigma*sqrt(2*M_PI));
f[2*i+1] = g1[2*i+1] = g2[2*i+1] = 0.;
}
gsl_fft_complex_radix2_forward(f, 1, N);
gsl_fft_complex_radix2_forward(g1, 1, N);
gsl_fft_complex_radix2_backward(g2, 1, N);
switch(kk)
{
case 0:
fprintf(fp1, "\n\n");
break;
case 1:
fprintf(fp2, "\n\n");
break;
case 2:
fprintf(fp3, "\n\n");
break;
}
//------------------------- nadpisanie f[] transformata splotu f*g
for(unsigned int i = 0; i < N; i++)
{
double a1, a2, b1, b2;
a1 = f[2*i];
b1 = f[2*i+1];
a2 = g1[2*i] + g2[2*i];
b2 = g1[2*i+1] + g2[2*i+1];
f[2*i] = a1*a2 - b1*b2; //Re
f[2*i+1] = a1*b2 + a2*b1; //Im
}
gsl_fft_complex_radix2_backward(f, 1, N);
//------------------------------ znalezienie max. modulu f[] (tylko Re)
double f_max = fabs(f[0]);
for(unsigned int i = 1; i < N; i++)
{
if(fabs(f[2*i]) - f_max > 0)
f_max = fabs(f[2*i]);
}
printf("dla k = %2d f_max = %g\n", k[kk], f_max);
//--------------------------- zapis danych po odszumieniu
for(unsigned int i = 0; i < N; i++)
{
switch(kk)
{
case 0:
fprintf(fp1, "%g %g\n", dt*i, f[2*i] * 2.5 / f_max);
break;
case 1:
fprintf(fp2, "%g %g\n", dt*i, f[2*i] * 2.5 / f_max);
break;
case 2:
fprintf(fp3, "%g %g\n", dt*i, f[2*i] * 2.5 / f_max);
break;
}
}
//---------------------------------- dealokacja pamieci
free(f);
free(g1);
free(g2);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
|
C
|
/*
* utilFunctions.c
*
* Created on: Aug 16, 2019
* Author: Lars
*/
/* Includes ------------------------------------------------------------------*/
#include "utilFunctions.h"
extern RTC_HandleTypeDef hrtc;
/* Public Function Implementation -----------------------------------------------*/
/**
* @brief Turn on the current sink provided by the PSOC to measure the TSEP temperature
* @param NONE
* @retval NONE
*/
void turnOnCurrentSink(void)
{
HAL_GPIO_WritePin(GPIOG, GPIO_PIN_0, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOG, GPIO_PIN_0, GPIO_PIN_RESET);
}
/**
* @brief Turn off the current sink provided by the PSOC to measure the TSEP temperature
* @param NONE
* @retval NONE
*/
void turnOffCurrentSink(void)
{
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_1, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_1, GPIO_PIN_RESET);
}
/**
* @brief Sets the system real time for the sensor timing to the given value
* @param system_time structure of the RTC peripheral that holds the desired time value
* @param system_date structure of the RTC peripheral that holds the desired date value
* @retval NONE
*/
void setSystemTime(RTC_TimeTypeDef system_time, RTC_DateTypeDef system_date)
{
HAL_RTC_SetTime(&hrtc, &system_time, RTC_FORMAT_BCD);
HAL_RTC_SetDate(&hrtc, &system_date, RTC_FORMAT_BCD);
}
/**
* @brief Inits the clock counter of the DWT core module
* @param NONE
* @retval NONE
*/
void initDWT(void)
{
DWT->LAR = 0xC5ACCE55;
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CYCCNT = 0;
DWT->CTRL |= 1;
}
/**
* @brief Delays the programm execution for the given microseconds
* @param us delay in microseconds
* @retval NONE
*/
void delayUSDWT(uint32_t us)
{
uint32_t cycles = 0;
uint32_t start = 0;
cycles = (SystemCoreClock / 1000000L) * us;
start = DWT->CYCCNT;
do {
} while (DWT->CYCCNT - start < cycles);
}
|
C
|
/* 134. Program to delete a node for a given element from linked list. */
#include <stdio.h>
#include<stdlib.h>
typedef struct node {
int data;
struct node *next;
}Node;
int main(void)
{
Node*temp;
Node*start=NULL;
Node* p=NULL;
int n;
scanf("%d",&n);
while(n--)
{
temp=(Node *)malloc(sizeof(struct node));
scanf("%d",&temp->data);
temp->next=NULL;
if(start==NULL)
{
start=temp;
p=temp;
}
else
{
p->next=temp;
p=temp;
}
}
printf("Element to delete : ");
int ele; scanf("%d",&ele); printf("%d\n",ele);
Node*prev=start;
Node*cur=start;
while(cur!=NULL)
{
if(start->data==ele)
{
start=start->next;
}
if(cur->data==ele)
{
prev->next=cur->next;
free(cur);
break;
}
prev=cur;
cur=cur->next;
if(cur==NULL)
{
printf("Element doesn't exist!");
exit(0);
}
}
while(start!=NULL)
{
if(start->next!=NULL)
printf("%d->",start->data);
else
printf("%d",start->data);
start=start->next;
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* conv_str.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mjose <mjose@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/06/13 19:25:46 by mjose #+# #+# */
/* Updated: 2018/07/09 23:38:01 by mjose ### ########.fr */
/* */
/* ************************************************************************** */
#include "../Includes/ft_ls.h"
char *convstr_path_if(char *dir, char *obj)
{
char *new_path;
if (!ft_strcmp(dir, "./") || !ft_strcmp(dir, "."))
{
if (obj[0] == '/')
new_path = ft_strdup(obj);
else
new_path = path_it(dir, obj);
}
else
new_path = path_it(dir, obj);
return (new_path);
}
static char *path_it_nulldir(char *obj)
{
char *path;
if (!ft_strncmp(obj, "..", 2))
path = ft_strdup(obj);
else if (!ft_strncmp(obj, "./", 2))
path = ft_strdup(obj);
else if (!ft_strncmp(obj, "/", 1))
path = ft_strdup(obj);
else
path = ft_strjoin("./", obj);
return (path);
}
char *path_it(char *dir, char *obj)
{
char *tmp;
char *path;
if (!dir)
path = path_it_nulldir(obj);
else
{
tmp = ft_strjoin(dir, "/");
path = ft_strjoin(tmp, obj);
free(tmp);
}
return (path);
}
char *rmv_path_frm_obj(char *path)
{
int total_l;
int i;
int ctrl;
char *obj;
total_l = ft_strlen(path);
i = 0;
ctrl = 0;
while (i != total_l + 1)
{
if (path[i] == '/')
ctrl = i;
i++;
}
obj = (char *)malloc(sizeof(char) * (total_l - ctrl));
if (obj)
{
i = 0;
ctrl++;
while (path[ctrl])
obj[i++] = path[ctrl++];
obj[i] = '\0';
return (obj);
}
return (NULL);
}
char *rmv_obj_frm_path(char *path)
{
int i;
int ctrl;
char *obj;
i = 0;
while (path[i])
{
if (path[i] == '/')
ctrl = i;
i++;
}
obj = (char *)malloc(sizeof(char) * (ctrl) + 2);
if (obj)
{
i = 0;
while (i != ctrl)
{
obj[i] = path[i];
i++;
}
obj[i] = path[i];
obj[i + 1] = '\0';
return (obj);
}
return (NULL);
}
|
C
|
// %%cpp macro_example_2.c
// %run cat macro_example_2.c | grep -v "// %" > macro_example_2_filtered.c
// %run gcc -std=c99 -ansi macro_example_2_filtered.c -o macro_example_2.exe
// %run ./macro_example_2.exe
// %run gcc -std=gnu99 macro_example_2.c -o macro_example_2.exe
// %run ./macro_example_2.exe
#include <stdio.h>
#include <string.h>
#include <assert.h>
/* #VAR_NAME разворачивается в строковый литерал "VAR_NAME" */
#define print_int(i) printf(#i " = %d\n", (i));
/* Полезный макрос для вывода в поток ошибок */
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#define logprintf_impl(fmt, line, ...) eprintf(__FILE__ ":" #line " " fmt, __VA_ARGS__)
#define logprintf_impl_2(line, fmt, ...) logprintf_impl(fmt "%s", line, __VA_ARGS__)
#define logprintf(...) logprintf_impl_2(__LINE__, __VA_ARGS__, "")
#define SWAP(a, b) { __typeof__(a) c = (a); (a) = (b); (b) = (c); }
#define SWAP2(a, b) { char c[sizeof(a)]; memcpy(c, &a, sizeof(a)); \
memcpy(&a, &b, sizeof(a)); memcpy(&b, c, sizeof(a)); if (0) { a = b; b = a; } }
/* Способ сделать макрос с переменным числом аргументов
* И это единственный способ "перегрузить функцию в С" */
#define sum_2(a, b, c) ((a) + (b))
#define sum_3(a, b, c) ((a) + (b) + (c))
#define sum_impl(a, b, c, sum_func, ...) sum_func(a, b, c)
#define sum(...) sum_impl(__VA_ARGS__, sum_3, sum_2)
int main() {
/* assert(3 > 4); */
print_int(9 * 9 + 1);
eprintf("It is in stderr: %d\n", 431);
int x = 1, y = 2;
eprintf("(x, y) = (%d, %d)\n", x, y);
SWAP(x, y);
eprintf("(x, y) = (%d, %d)\n", x, y);
SWAP2(x, y);
eprintf("(x, y) = (%d, %d)\n", x, y);
print_int(sum(1, 1));
print_int(sum(1, 1, 1));
eprintf("%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
logprintf("Before exit %s\n", "");
return 0;
}
|
C
|
#include "Producers.h"
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
struct Producers
{
pthread_t* m_threadIDs; /* ID returned by pthread_create() */
size_t m_nTotalProducers; /* TODO decide if needed */
sem_t m_nCurrentProducers;
};
Producers* ProducersCreate(size_t _numOfProducers, void* (*_producerRoutine)(void *))
{
Producers* producers = NULL;
size_t i;
if (0 == _numOfProducers)
{
return NULL;
}
producers = malloc(sizeof(Producers));
if (!producers)
{
return NULL;
}
producers->m_threadIDs = malloc(_numOfProducers * sizeof(pthread_t));
{
free(producers);
return NULL;
}
for (i = 0; i < _numOfProducers; ++i)
{
if (0 != pthread_create(&producers->m_threadIDs[i], NULL, _producerRoutine, NULL));
{
/* TODO Destroy everything*/
return NULL;
}
}
return producers;
}
void* ProducerRoutine(void* _arg)
{
sem_t empty, full;
pthread_mutex_t mutex;
size_t i;
for (i = 0; i < _cicles; ++i)
{
pthread_mutex_lock(&mutex);
sem_wait(&empty);
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
pthread_exit(NULL);
}
void ProducersJoin(Producers* _producers)
{
size_t i;
if (!_producers)
{
return;
}
for (i = 0; i < _producers->m_nTotalProducers; ++i)
{
pthread_join(_producers->m_threadIDs[i], NULL);
}
}
|
C
|
/**********************************
* @author Jerry Chen
* Date: 27 Jul 17
* Email: jerry153fish@gmail.com
**********************************/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include "j_threadpool.h"
#include "j_queue.h"
#include "job.h"
// simple declare universal struct
static int pool_alive = 1;
struct thpool_s {
j_queue q;
pthread_t *threads;
int thread_size;
};
void *thread_fn(void *arg) {
threadpool tp = (threadpool)arg;
j_queue q = tp->q;
while(pool_alive) {
job j = q_get(q);
run_job(j);
}
};
// threadpool create
threadpool threadpool_init(int thread_size) {
threadpool tp = (threadpool)malloc(sizeof(struct thpool_s));
tp->q = q_init();
tp->thread_size = thread_size;
tp->threads = malloc(sizeof(pthread_t)*thread_size);
pool_alive = 1;
for (int i = 0; i < thread_size; i++) {
if (pthread_create(&tp->threads[i], NULL, thread_fn, (void *)tp)) {
printf("ERROR creating thread %d", i);
exit(1);
}
}
return tp;
};
// add function to pool
void pool_add_fn(threadpool tp, pool_fn fn, void *arg) {
q_put(tp->q, fn, arg);
};
// destroy
void pool_destroy(threadpool tp) {
pool_alive = 0;
destroy_q(tp->q);
free(tp);
};
|
C
|
#include "Pause.h"
#include "Stage_1.h"
int Pause(SDL_Surface *ecran, SDL_Rect camera, SDL_Rect position_objet , int stage_dispo)
{
SDL_Rect camera_pause, position_objet_pause;
SDL_Surface *pause=NULL;
int quit =0,i=1 ;
FILE *fichier =NULL ;
SDL_Event event;
do
{
switch(i)
{
case 1 :
pause=SDL_LoadBMP("pause_1.bmp");
break;
case 2 :
pause=SDL_LoadBMP("pause_2.bmp");
break;
case 3 :
pause=SDL_LoadBMP("pause_3.bmp");
break;
case 4 :
pause=SDL_LoadBMP("pause_4.bmp");
break;
}
SDL_BlitSurface(pause,NULL,ecran,NULL);
SDL_Flip(ecran);
SDL_WaitEvent(&event);
switch (event.type)
{
case SDL_KEYUP :
switch (event.key.keysym.sym)
{
case SDLK_UP :
i--;
if (i<1)
{
i=4;
}
break;
case SDLK_DOWN :
i++;
if (i>4)
{
i=1;
}
break;
}
break ;
case SDL_KEYDOWN :
switch (event.key.keysym.sym)
{
case SDLK_SPACE :
quit=1 ;
break ;
case SDLK_RETURN :
if ( i== 1 ) quit =1 ;
else if (i==2)
{
fichier=fopen("save.txt","w") ;
fprintf(fichier,"%d",stage_dispo);
fclose(fichier) ;
}
break ;
}
break ;
}
SDL_FreeSurface(pause);
}while(quit!=1) ;
return 0 ;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include "../lib/prime.h"
int main(int argc, char* argv[]) {
int limit = 10000;
sieve_t sieve = prime_sieve(limit);
for(int c = 3; c < limit; c += 2) {
// ignore all primes, only want odd composites
if(is_prime(c)) continue;
bool found = false;
for(int j = 0; j < sieve.num; j++) {
int p = sieve.primes[j];
int s = floor(sqrt((c - p ) / 2));
if(p + 2 * s * s == c) {
found = true;
break;
}
}
if(!found) {
printf("%i", c);
break;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#define MAXLINES 5000 /* 待排序的最大行数 */
char *lineptr[MAXLINES] /* 指向文本行的指针 */
int readlines(char *lineptr, int nlines);
void writelines(char *lineptr[], int nlines);
void qsort(void *lineptr[], int left, int right, int (*comp) (void *, void *));
int numcmp(char *, char*);
/* 对输入的文本行进行排序 */
/* 改写后的qsort函数能够处理任何数据类型,而不仅仅限于字符串。它的参数包括一个指针数组,两个整数和一个有两个指针参数的函数
其中指针数组参数的类型为通用指针类型void *, 由于任何类型的指针都可以转换为 void *类型,并且在将它转换回原来的类型时不会丢失信息
*/
main(int argc, char *argv[])
{
int nlines;
int numeric = 0;
if (argc > 0 && strcmp(argv[1], "-n") ==0)
{
numeric = 0;
}
if ((nlines = readlines(lineptr, MAXLINES)) >= 0)
{
qsort((void **) lineptr, 0, nlines-1, (int (*) (void*, void*)) (numeric ? numcmp : strcmp));
writelines(lineptr, nlines);
return 0;
}
else
{
printf("input too big to sort\n");
return 1;
}
}
/* 用指针方式实现的strcmp 函数*/
int strcmp (char *s, char *t)
{
for ( ; *s = *t; s++, t++)
{
if (*s == '\0')
{
return 0;
}
}
return *s - *t;
}
|
C
|
/*Hardware: see connect.txt */
#include <avr/io.h>
#include "lcd.h"
#include "KPDScan.h"
void mydelay(unsigned char v)
{
unsigned char j;
unsigned int i;
for (j=0;j<v;j++) for (i=0;i<8000;i++) asm volatile ("nop"::);
}
#define demodelay 0xFF
int main(void)
{
uint8_t key_val;
/* initialize display, cursor off */
lcd_init(LCD_DISP_ON);
lcd_clrscr();
for (;;) {
/*
lcd_puts("Hello, World!\n --mega48");
mydelay(demodelay);
lcd_clrscr();
lcd_puts("go on now...\n");
mydelay(demodelay);
*/
key_val=KPDScan();
/* output the key value (dec) to LCD */
lcd_gotoxy(0,0);
lcd_putc('0'+key_val/100);
lcd_gotoxy(1,0);
lcd_putc('0'+(key_val%100)/10);
lcd_gotoxy(2,0);
lcd_putc('0'+(key_val%100)%10);
}
}
|
C
|
/*
** my_revstr.c for my_revstr in /home/clemsx/delivery/CPool_Day06
**
** Made by clement xia
** Login <clemsx@epitech.net>
**
** Started on Mon Oct 10 10:46:34 2016 clement xia
** Last update Tue Oct 11 08:14:01 2016 clement xia
*/
int my_putstr(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
{
my_putchar(str[i]);
i = i + 1;
}
}
char *my_revstr(char *str)
{
int i;
int j;
char k;
i = 0;
j = 0;
while (str[i] != '\0')
{
i++;
}
i--;
while ( j < i )
{
k = str[j];
str[j] = str[i];
str[i] = k;
j++;
i--;
}
return (str);
}
|
C
|
#include "holberton.h"
/**
* _strspn - gets the length of a prefix substring.
*
* @s: the string to compare.
* @accept: value accepted.
*
* Return: result.
*/
unsigned int _strspn(char *s, char *accept)
{
unsigned int result;
unsigned int i;
unsigned int j;
result = 0;
i = 0;
while (s[i])
{
j = 0;
while (accept[j])
{
if (s[i] == accept[j] && i == result)
{
result++;
}
j++;
}
i++;
}
return (result);
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int /*<<< orphan*/ git_oid ;
/* Variables and functions */
int /*<<< orphan*/ cl_assert (int) ;
scalar_t__ git_oid_cmp (int /*<<< orphan*/ *,int /*<<< orphan*/ *) ;
int /*<<< orphan*/ git_oid_fromraw (int /*<<< orphan*/ *,unsigned char*) ;
void test_object_raw_compare__succeed_on_oid_comparison_lesser(void)
{
git_oid a, b;
unsigned char a_in[] = {
0x16, 0xa6, 0x77, 0x70, 0xb7,
0xd8, 0xd7, 0x23, 0x17, 0xc4,
0xb7, 0x75, 0x21, 0x3c, 0x23,
0xa8, 0xbd, 0x74, 0xf5, 0xe0,
};
unsigned char b_in[] = {
0x16, 0xa6, 0x77, 0x70, 0xb7,
0xd8, 0xd7, 0x23, 0x17, 0xc4,
0xb7, 0x75, 0x21, 0x3c, 0x23,
0xa8, 0xbd, 0x74, 0xf5, 0xf0,
};
git_oid_fromraw(&a, a_in);
git_oid_fromraw(&b, b_in);
cl_assert(git_oid_cmp(&a, &b) < 0);
}
|
C
|
#ifndef _VECTOR_H
#define _VECTOR_H
/*2D position struct*/
typedef struct
{
float x;
float y;
}Vector2f;
Vector2f newVector2f(float x, float y);
Vector2f add(Vector2f a, Vector2f b);
#endif
|
C
|
#include<stdio.h>
int main(void)
{
int num,max,min,i;
printf("三つの整数を入力してください\n");
for(i=1;i<=3;i++){
printf("整数(No.%d):",i);
scanf("%d",&num);
if((i==1)||(num>max)){
max=num;
}
if((i==1)||(num<min)){
min=num;
}
}
printf("最大値:%d\n",max);
printf("最小値:%d\n",min);
return 0;
}
|
C
|
/**
* Computaçao Embarcada
* Mutirão C
* Aula 1
* Rafael Corsi e Fábio Ayres
* Entrega do Exercicio 4 do Aluno Felipe Frid Buniac
*/
#include <stdio.h>
#include <math.h>
void main(){
int numprodutos;
char nome[100];
int preco;
int quantidade;
int precototal;
char nomes[50][100];
int precos[50];
int quantidades[50];
int precostotais[50];
int total =0 ;
numprodutos = 0;
printf("Quantos Produtos tem sua lista?");
scanf("%d", &numprodutos);
for (int i=1; i<=numprodutos ;i++){
printf("Qual Nome do Produto?");
scanf("%s", nomes[i-1]);
printf("Qual a preco do Produto?");
scanf("%d", &precos[i-1]);
printf("Qual a Quantidade do Produto?");
scanf("%d", &quantidades[i-1]);
precostotais[i-1] = ((precos[i-1]) * (quantidades[i-1]));
total += precostotais[i-1];
}
for(int i =1; i<=numprodutos; i++){
printf("Nome:%s ", nomes[i-1]);
printf("Quantidade:%d ", quantidades[i-1]);
printf("Preco:%d ", precos[i-1]);
printf("Preco Total:%d \n " , precostotais[i-1]);
}
printf("Preco Total dos Produtos:%d \n" , total);
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char *a = "hello";
char *b = malloc(100);
printf("enter\n");
fgets(b,100,stdin);
printf("Output: %s\n", b);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include "sha1.h"
#include "otp.h"
static uint8_t sanitize_base32_input(const char ch)
{
/* Google Authenticator checks for these values and corrects them,
assuming this was a human error */
if (ch == '0') return (uint8_t) 'O';
else if (ch == '1') return (uint8_t) 'L';
else if (ch == '8') return (uint8_t) 'B';
return (uint8_t) ch;
}
static int base32_decode(const char *src, const int srclen, uint8_t *dst, const int dstlen)
{
const int len = srclen == -1 ? strlen((const char *) src) : srclen;
int retval = 0;
uint32_t accum = 0;
int shifter = 0;
int i;
for (i = 0; i < len; i++) {
const uint8_t ch = sanitize_base32_input(src[i]);
uint8_t val;
if ((ch >= 'A') && (ch <= 'Z')) {
val = ch - 'A';
} else if ((ch >= '2') && (ch <= '7')) {
val = (ch - '2') + 26;
} else if (ch == '=') {
val = 0;
/* these are illegal in base32, but GAuth keys might have them. */
} else if (ch == ' ') {
continue; /* skip these. */
} else if ((ch >= 'a') && (ch <= 'z')) {
val = ch - 'a'; /* treat like uppercase. */
} else {
return -1; /* invalid string. */
}
accum = (accum << 5) | ((uint32_t) val);
shifter += 5;
if (shifter >= 8) {
if (retval > dstlen) {
return -1; /* dst too small */
}
dst[retval] = (uint8_t) ((accum >> (shifter - 8)) & 0xFF);
retval++;
shifter -= 8;
}
}
#if 0 // Apparently for Google Authenticator, we just drop extra bits...?
if (shifter > 0) {
if (retval > dstlen) {
return -1; /* dst too small */
}
dst[retval] = (uint8_t) (accum & 0xFF);
retval++;
}
#endif
return retval;
}
int totp(const char *base32_secret, char *dst, int dstlen)
{
uint8_t decoded[64];
int decodedlen;
uint64_t secs;
uint8_t timebytes[8];
uint8_t digest[SHA1_DIGEST_LENGTH];
uint8_t *bytes;
uint32_t val;
decodedlen = base32_decode(base32_secret, -1, decoded, sizeof (decoded));
if (decodedlen == -1) {
return -1;
}
secs = ((uint64_t) time(NULL)) / 30;
for (int i = 0; i < 8; i++) {
timebytes[i] = (uint8_t) (secs >> ((7-i) * 8));
}
SHA1Hmac(decoded, decodedlen, timebytes, 8, digest);
bytes = digest + (digest[SHA1_DIGEST_LENGTH-1] & 0xF);
val = (((uint32_t) bytes[0]) << 24) | (((uint32_t) bytes[1]) << 16) |
(((uint32_t) bytes[2]) << 8) | (((uint32_t) bytes[3]));
val &= 0x7FFFFFFF; /* drop most significant bit. */
val %= 1000000; /* make it six digits long. */
snprintf(dst, dstlen, "%06u", (unsigned int) val);
return 0;
}
/* end of otp.c ... */
|
C
|
#include <cs50.h>
#include <stdio.h>
const int BLOCK = 512;
int main(int argc, char *argv[])
{
if(argc != 2)
{
fprintf(stderr, "Usage: ./recover card.raw\n");
return 1;
}
FILE *input = fopen(argv[1], "r");
if (input == NULL)
{
fprintf(stderr, "Could not open %s", argv[1]);
}
for(int i = 0, int j = 0; i < sizeof(input); i++)
{
fread(void *buffer, 1, 512, input);
if(buffer[i] == 0xff &&
buffer[i + 1] == 0xd8 &&
buffer[i + 2] == 0xff &&
(buffer[i + 3] & 0xf0) == 0xe0)
{
i += 4;
sprintf()
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "quicksort.h"
#include <stdbool.h>
#include <math.h>
#define RAM 4
#define NUM_NUMS 64
#define NUM_CAMINHOS 3
/*
---INTERCALACAO BALANCEADA MULTI-CAMINHOS---
DUPLA: CARLOS ALBERTO ROSA DOS SANTOS E GUILHERME GUIDOLIN
*/
//arquivos utilizados nas intercalacoes
struct fitas{
FILE *arq;
bool pode_avancar;//define fazer a leitura de um proximo elemento do arquivo
bool ativa;//define se um arquivo esta ativo ou inativo para comparacao com os demais
};
typedef struct fitas Fitas;
// Cria um arquivo temporario chamado nome com tam numeros aleatorios.
// Os numeros gerados são mostrados na tela.
void cria_arq_rand(char *nome, int tam){
FILE *arq;
int num;
arq = fopen(nome,"wb");
for (int i = 0; i < tam; i++) {
num = rand()%100;
fwrite(&num, sizeof(num), 1, arq);
}
// fflush(arq); // garante que tudo foi gravado antes de fechar
fclose(arq);
}
// Le um aquivo com numeros inteiros e mostra-os na tela.
void le_arq(char *nome, bool antes, int tamanho_conjunto){
FILE *arq;
int num, lidos = 0;
int i=0;
arq = fopen(nome,"rb");
while( 1 == fread(&num,sizeof(num),1,arq)){
printf(" %d ",num,i++);
if (i%tamanho_conjunto==0 && antes == true)
printf(" ");
lidos++;
}
if (!feof(arq)){
printf("Houston!\n\n");
}// teoricamente nunca devemos ver isso!
if(lidos == 0){
printf("arquivo %s vazio !",nome);
}
printf("\n");
fclose(arq);
}
void fecha_arqs(int num, Fitas *fitas){
for (int i =0; i < num; i++){
//fflush(arqs[i]); // garante que tudo foi gravado antes de fechar
fclose(fitas[i].arq);
}
}
void abre_arqs_temp(int inicio, int fim, char *nome_arq,Fitas *fitas,char *como){
char nome_arq_temp[20];
for (int i=inicio;i<fim;i++){
// cria nome do arq temporario e abre
sprintf(nome_arq_temp,"%s.%d",nome_arq,i);
fitas[i].arq = fopen(nome_arq_temp, como);
}
}
void verifica_fitas_inativas(Fitas *fitas, int *leitura_fitas, int tam, int tamanho_conjunto)
{
for(int i = 0; i < tam;i++){
if(leitura_fitas[i] > tamanho_conjunto || feof(fitas[i].arq)){
fitas[i].ativa = false;
fitas[i].pode_avancar = false;
}
}
}
void zera_valores(int *leitura_fitas, int tam)
{
for(int i = 0; i < tam;i++){
leitura_fitas[i] = 0;
}
}
int verifica_menor(int *vet, Fitas *fitas, int tam)
{
int i, menor, ind_menor = 0;
menor = 2147483600;//numero inteiro muito grande
for(i = 0; i < tam;i++){
if(vet[i] < menor && fitas[i].ativa){
menor = vet[i];
ind_menor = i;
}
}
for(i = 0; i < tam;i++){
if(i == ind_menor){
fitas[i].pode_avancar = true;
}else{
fitas[i].pode_avancar = false;
}
}
//printf("%d e %d = %d\n",vet[0],vet[1],menor);
return menor;
}
bool verifica_fim(Fitas *fitas, int tam)
{
int i, inativas = 0;
for(i = 0; i < tam;i++){
if(!fitas[i].ativa){
inativas++;
}
}
if(inativas == tam){
return true;
}
return false;
}
void zera_fitas(Fitas *fitas, int tam)
{
for(int i = 0; i < tam;i++){
fitas[i].pode_avancar = true;
fitas[i].ativa = true;
}
}
void distribui(int num_caminhos, char *nome_arq, Fitas *fitas){
FILE *arq = fopen(nome_arq,"rb");
int buffer[RAM], i=0, lidos;
abre_arqs_temp(0,num_caminhos,nome_arq,fitas,"wb+"); //abre args temporarios
while( RAM == (lidos = fread(&buffer, sizeof(int), RAM, arq))){ // le o arquivo de entrada para a RAM
quick_sort(buffer,RAM); // ordena
fwrite(buffer, sizeof(int)*RAM, 1, fitas[i].arq); // escreve para o arquivo temporario atual
i++;
i %= num_caminhos; // incrementa o arquivo temporario
}
// trata os ultimos numeros do arquivo
quick_sort(buffer,lidos); // ordena
fwrite(buffer, sizeof(int)*lidos, 1, fitas[i].arq); // escreve para o arquivo temporario atual
fecha_arqs(num_caminhos, fitas);
}
void redistribui(Fitas *fitas,int conjunto,char *nome_arq,int *vet,int tam)
{
int buffer[conjunto], i=0, lidos;
abre_arqs_temp(NUM_CAMINHOS,NUM_CAMINHOS+1,nome_arq,fitas,"wb");
for(i = 0; i < tam;i++){
fwrite(&vet[i],sizeof(int),1,fitas[NUM_CAMINHOS].arq);
}
fecha_arqs(NUM_CAMINHOS+1,fitas);
abre_arqs_temp(0,NUM_CAMINHOS,nome_arq,fitas,"wb");
abre_arqs_temp(NUM_CAMINHOS,NUM_CAMINHOS+1,nome_arq,fitas,"rb");
i = 0;
while( conjunto == (lidos = fread(&buffer, sizeof(int), conjunto, fitas[NUM_CAMINHOS].arq))){ // le o arquivo de entrada para a RAM
fwrite(buffer, sizeof(int)*conjunto, 1, fitas[i].arq); // escreve para o arquivo temporario atual
i++;
i %= NUM_CAMINHOS; // incrementa o arquivo temporario
}
fwrite(buffer, sizeof(int)*lidos, 1, fitas[i].arq); // escreve para o arquivo temporario atual
fecha_arqs(NUM_CAMINHOS+1,fitas);
}
int conta_fim = 0;//contador global para saber quando as intercalações acabaram.
void intercalacao_balanceada(Fitas *fitas, char *nome_arq, int tamanho_conjunto, int *vet,int num_conjuntos, int num_intercalacoes)
{
conta_fim++;
if(conta_fim > num_intercalacoes){
return;
}
char *nome_temp = malloc(sizeof(char)*strlen(nome_arq)+3);
if(conta_fim == num_intercalacoes){
printf("ARQUIVOS INTERCALADOS NA INTERCALACAO NUMERO %d(ULTIMA):\n\n",conta_fim);
}else{
printf("ARQUIVOS INTERCALADOS NA INTERCALACAO NUMERO %d:\n\n",conta_fim);
}
for(int i =0; i < NUM_CAMINHOS;i++){
sprintf(nome_temp, "%s.%d", nome_arq, i);
printf("------ %s:------\n", nome_temp);
printf("\n");
printf("\n");
le_arq(nome_temp,true,tamanho_conjunto);
printf("\n");
}
free(nome_temp);
int i = 0, j, buffer, menor, cont = 0, z;
int val_fitas[NUM_CAMINHOS];
int leitura_fitas[NUM_CAMINHOS];
float tam_aux;
zera_valores(leitura_fitas,NUM_CAMINHOS+1);
bool fim = false;
abre_arqs_temp(0,NUM_CAMINHOS,nome_arq,fitas,"rb+");
zera_fitas(fitas,NUM_CAMINHOS+1);
for(i =0; i < num_conjuntos;i++){
zera_valores(leitura_fitas,NUM_CAMINHOS+1);
zera_fitas(fitas,NUM_CAMINHOS+1);
fim = false;
for(z = 0; z < NUM_CAMINHOS;z++){
fseek(fitas[z].arq,tamanho_conjunto*i*sizeof(int),SEEK_SET);
fread(&buffer,sizeof(int),1,fitas[z].arq);
if(feof(fitas[z].arq)){
fitas[z].ativa = false;
fitas[z].pode_avancar = false;
}
fseek(fitas[z].arq,tamanho_conjunto*i*sizeof(int),SEEK_SET);
}
while(!fim){
for(j = 0; j < NUM_CAMINHOS;j++){
if(fitas[j].pode_avancar && fitas[j].ativa && !feof(fitas[j].arq)){
leitura_fitas[j]++;
if(leitura_fitas[j] <= tamanho_conjunto){
fread(&val_fitas[j],sizeof(int),1,fitas[j].arq);
}
}
}
verifica_fitas_inativas(fitas,leitura_fitas,NUM_CAMINHOS,tamanho_conjunto);
menor = verifica_menor(val_fitas,fitas,NUM_CAMINHOS);
fim = verifica_fim(fitas,NUM_CAMINHOS);
if(!fim){
vet[cont] = menor;
cont++;
}
}
}
fecha_arqs(NUM_CAMINHOS+1,fitas);
redistribui(fitas,NUM_CAMINHOS*tamanho_conjunto,nome_arq,vet,NUM_NUMS);
tam_aux = num_conjuntos / 2.0;
tam_aux = ceil(tam_aux);
int num_conjuntos_prox = tam_aux;
intercalacao_balanceada(fitas,nome_arq,NUM_CAMINHOS*tamanho_conjunto,vet,num_conjuntos_prox,num_intercalacoes);
}
void inicializa_fitas(Fitas *fitas, int tam)
{
for(int i = 0; i < tam;i++){
fitas[i].arq = NULL;
fitas[i].pode_avancar = true;
fitas[i].ativa = true;
}
}
void intercalacao_multi_caminhos(Fitas *fitas, char *nome_arq,int tamanho_conjunto, int num_intercalacoes)
{
int vet[NUM_NUMS];
float valor = (float)NUM_NUMS / (RAM*NUM_CAMINHOS);
valor = ceil(valor);
int num_conjuntos = valor;
printf("INTERCALACOES BALANCEADAS:\n\n");
intercalacao_balanceada(fitas,nome_arq,RAM,vet,num_conjuntos,num_intercalacoes);
fecha_arqs(NUM_CAMINHOS+1, fitas);
}
Fitas* cria_fitas()
{
Fitas *f = (Fitas*)malloc(sizeof(Fitas) * (NUM_CAMINHOS+1));
return f;
}
float calcula_num_intercalacoes()
{
float v1 = (float)NUM_NUMS / RAM;
float num_intercalacoes_aux = log10(v1) / log10(NUM_CAMINHOS);
num_intercalacoes_aux = ceil(num_intercalacoes_aux);
return num_intercalacoes_aux;
}
int main(){
srand(time(NULL));
char nome_arq[]="teste.arq";
char *nome_arq_temp = malloc(sizeof(char)*strlen(nome_arq)+3); // suporta ate .99 arquivos
cria_arq_rand(nome_arq, NUM_NUMS);
printf("-------- ANTES DE ORDENAR: arquivo original ---------\n\n");
le_arq(nome_arq,false,RAM);
printf("\n");
Fitas *fitas = cria_fitas();
inicializa_fitas(fitas,NUM_CAMINHOS+1);
distribui(NUM_CAMINHOS, nome_arq,fitas);
int num_intercalacoes = calcula_num_intercalacoes();
printf("-------- ANTES DE ORDENAR: depois de feita a distribuicao em blocos ordenados ---------\n\n");
for (int i=0; i<NUM_CAMINHOS; i++){
sprintf(nome_arq_temp, "%s.%d", nome_arq, i);
printf("------- %s-------:\n", nome_arq_temp);
le_arq(nome_arq_temp,true,RAM);
}
printf("\n");
intercalacao_multi_caminhos(fitas,nome_arq,RAM,num_intercalacoes);
printf("-------- DEPOIS DE ORDENAR(resultado colocado no teste.arq.0, apos %d intercalacoes) ---------\n\n",num_intercalacoes);
sprintf(nome_arq_temp, "%s.%d", nome_arq, 0);
printf("------- %s:-------\n", nome_arq_temp);
le_arq(nome_arq_temp,false,RAM);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* map.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pferdina <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/31 16:03:54 by pferdina #+# #+# */
/* Updated: 2019/11/09 18:52:10 by pferdina ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
int count_tetris(t_tetris *list)
{
int counter;
counter = 0;
while (list)
{
counter++;
list = list->next;
}
return (counter);
}
int get_map_size(t_tetris *list)
{
int counter;
int size;
size = 1;
counter = count_tetris(list);
while (size * size < (counter * 4))
size++;
return (size);
}
void delete_map(t_map *map)
{
int i;
i = 0;
while (map->map[i])
{
free(map->map[i]);
i++;
}
free(map);
return ;
}
t_map *fill_map(t_map *map)
{
int i;
int j;
i = 0;
j = 0;
while (i < map->size)
{
while (j < map->size)
{
map->map[i][j] = '.';
j++;
}
j = 0;
i++;
}
return (map);
}
void print_map(t_map *map)
{
int i;
int j;
i = 0;
j = 0;
while (i < map->size)
{
while (j < map->size)
{
ft_putchar(map->map[j][i]);
j++;
}
j = 0;
ft_putendl("");
i++;
}
}
t_map *generate_map(int size)
{
t_map *field;
int i;
if (!(field = (t_map*)malloc(sizeof(t_map))))
return (NULL);
field->size = size;
if (!(field->map = (char**)malloc(sizeof(char*) * (size + 1))))
{
free(field);
return (NULL);
}
i = 0;
field->map[size] = 0;
while (i < size)
{
if (!(field->map[i] = ft_strnew(size)))
{
delete_map(field);
return (NULL);
}
i++;
}
field = fill_map(field);
return (field);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
//һ֮⣬ֶ
//ҳֻһε
//{ 1, 3, 5, 7, 1, 3, 5, 9 };
//ҳ79
int main(){
int arr[] = { 1, 3, 5, 7, 1, 3, 5, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
int i;
int tmp = 0;
int pos;
int a = 0;
int b = 0;
for (i = 0; i < n; ++i){
tmp ^= arr[i];
}
for (i = 0; i < 32; ++i){
if (tmp & (1 << i)){
pos = i;
break;
}
}
for (i = 0; i < n; ++i){
if (arr[i] & (1 << pos)){
a ^= arr[i];
}
else {
b ^= arr[i];
}
}
printf("%d, %d\n", a, b);
system("pause");
return 0;
}
|
C
|
// export PATH=$PATH:$(pwd)
#include <signal.h>
#include <stdio.h>
#include <string.h>
volatile sig_atomic_t flag = 0;
void handler(int sig) { flag = 1; }
int main(int argc, char *argv[]) {
FILE *file[argc - 1];
char str[256], c;
int line_number = 1;
signal(SIGINT, handler);
if (argc < 2 || !strcmp(argv[1], "-")) {
while (!flag) {
c = getchar();
printf("%c", c);
}
}
if (!strcmp(argv[1], "-help")) {
file[1] = fopen("help.md", "r");
while ((fgets(str, 256, file[1])) != NULL) {
printf("%s", str);
}
printf("\n\n");
fclose(file[1]);
goto end;
}
if (!strcmp(argv[1], "-w")) {
for (int i = 1; i < argc - 1; i++) {
file[i] = fopen(argv[i + 1], "w");
while ((fgets(str, 256, file[i])) != NULL) {
printf("%s", str);
}
printf("\n\n");
fclose(file[i]);
}
goto end;
}
if (!strcmp(argv[1], "-a")) {
for (int i = 1; i < argc - 1; i++) {
file[i] = fopen(argv[i + 1], "a");
while ((fgets(str, 256, file[i])) != NULL) {
printf("%s", str);
}
printf("\n\n");
fclose(file[i]);
}
goto end;
}
if (!strcmp(argv[1], "-r+")) {
for (int i = 1; i < argc - 1; i++) {
file[i] = fopen(argv[i + 1], "r+");
if (file[i] == NULL) {
printf("no exist\n\n");
continue;
}
while ((fgets(str, 256, file[i])) != NULL) {
printf("%s", str);
}
printf("\n\n");
fclose(file[i]);
}
goto end;
}
if (!strcmp(argv[1], "-w+")) {
for (int i = 1; i < argc - 1; i++) {
file[i] = fopen(argv[i + 1], "w+");
while ((fgets(str, 256, file[i])) != NULL) {
printf("%s", str);
}
printf("\n\n");
fclose(file[i]);
}
goto end;
}
if (!strcmp(argv[1], "-a+")) {
for (int i = 1; i < argc - 1; i++) {
file[i] = fopen(argv[i + 1], "a+");
while ((fgets(str, 256, file[i])) != NULL) {
printf("%s", str);
}
printf("\n\n");
fclose(file[i]);
}
goto end;
}
if (!strcmp(argv[1], "-n")) {
for (int i = 1; i < argc - 1; i++) {
file[i] = fopen(argv[i + 1], "r");
if (file[i] == NULL) {
printf("no exist\n\n");
continue;
}
while ((fgets(str, 256, file[i])) != NULL) {
printf("%d %s", line_number, str);
line_number++;
}
printf("\n\n");
fclose(file[i]);
}
goto end;
}
if (!strcmp(argv[1], "-e")) {
for (int i = 1; i < argc - 1; i++) {
file[i] = fopen(argv[i + 1], "r");
if (file[i] == NULL) {
printf("no exist\n\n");
continue;
}
while ((fgets(str, 256, file[i])) != NULL) {
for(int j=0;j<sizeof(str);j++){
if(str[j]=='\n'){
str[j]='$';
break;
}
}
printf("%s\n", str);
}
printf("\n");
fclose(file[i]);
}
goto end;
}
for (int i = 0; i < argc - 1; i++) {
file[i] = fopen(argv[i + 1], "r");
if (file[i] == NULL) {
printf("no exist\n\n");
continue;
}
while ((fgets(str, 256, file[i])) != NULL) {
printf("%s", str);
}
printf("\n\n");
fclose(file[i]);
}
end:
return 0;
}
|
C
|
#include <stdio.h>
int encontraSuperior(int funcionario, int matriz[][30], int tamanho){
int i;
if (funcionario==0)
/*ja e o presidente*/
printf ("0\n");
else{
/*escreve funcionario*/
printf ("%d ", funcionario);
/*percorre coluna para achar superior*/
for (i=0; i<tamanho; i++){
if (matriz[i][funcionario]==1){
encontraSuperior(i,matriz,tamanho);
}
}
}
}
int main (){
int mat[30][30],tam,func,i,j;
/*lendo tamanho da matriz, funcionario a ser buscado e matriz da empresa*/
scanf ("%d %d", &tam, &func);
for (i=0; i<tam; i++) {
for (j=0; j<tam; j++){
scanf ("%d", &mat[i][j]);
}
}
/*escreve a hierarquia do funcionario*/
encontraSuperior(func,mat,tam);
return 0;
}
|
C
|
/**
* \file
*
* \brief Empty user application template
*
*/
/**
* \mainpage User Application template doxygen documentation
*
* \par Empty user application template
*
* Bare minimum empty user application template
*
* \par Content
*
* -# Include the ASF header files (through asf.h)
* -# "Insert system clock initialization code here" comment
* -# Minimal main function that starts with a call to board_init()
* -# "Insert application code here" comment
*
*/
#define F_CPU 16000000
/*
* Include header files for all drivers that have been imported from
* Atmel Software Framework (ASF).
*/
/*
* Support and FAQ: visit <a href="https://www.microchip.com/support/">Microchip Support</a>
*/
#include <asf.h>
#include<avr/io.h>
#include<avr/interrupt.h>
#include<util/delay.h>
#define confidence_max 50
#define confidence_thresh 35
#define IR (PIND&(1<<PIND2))>>PIND2
#define SWT0 (PIND&(1<<PIND3))>>PIND3
#define SWT1 (PIND&(1<<PIND4))>>PIND4
#define IN1 PIND5
#define IN2 PIND6
#define EN1 PIND7
bool ir_state,swt0_state,swt1_state;
unsigned char lift_state=0; //0 - lower floor , 1 - upper floor , 2 - transition state
/*
D2- ir sensor , D3- Bottom end switch , D4- Top end switch , D5- in1 , D6- in2 , D7- en1
*/
void init_pins(void)
{
DDRD=0b11100010;
EICRA|=(1<<ISC11)|(1<<ISC10)|(1<<ISC01); //INT1 - Trigger at rising edge , INT0 - Trigger at falling edge
PCMSK2|=(1<<PCINT20); //D4 as pin change interrupt
}
void ascend(void)
{
lift_state=2; //lift in movement
PORTD&=~(1<<IN1);
PORTD|= (1<<IN2)|(1<<EN1);
PCICR|=(1<<PCIE2);
while(swt1_state == 0)
_delay_ms(10);
PCICR&=~(1<<PCIE2);
PORTD&=~( (1<<IN1)|(1<<IN2)|(1<<EN1) );
swt0_state=0; //swt0 is not pressed
lift_state=1; //lift has reached 1st floor
}
void decend(void)
{
lift_state=2; //lift in movement
PORTD&=~(1<<IN2);
PORTD|= (1<<IN1)|(1<<EN1);
EIMSK|=(1<<INT1);
while(swt0_state == 0)
_delay_ms(10);
EIMSK&=~(1<<INT1);
PORTD&=~( (1<<IN1)|(1<<IN2)|(1<<EN1) );
swt1_state=0; //swt1 is not pressed
lift_state=0; //lift has reached ground floor
}
void ir_high_update()
{
unsigned int confidence_ir_high=0;
if(ir_state == 0)
{
for(int i=0;i<confidence_max;i++)
{
if(IR)
confidence_ir_high++;
_delay_ms(1);
}
if(confidence_ir_high>confidence_thresh)
ir_state=1;
}
}
int main (void)
{
/* Insert system clock initialization code here (sysclk_init()). */
board_init();
/* Insert application code here, after the board has been initialized. */
init_pins();
sei();
_delay_ms(100);
if(swt0_state)
lift_state=0;
else if(swt1_state)
lift_state=1;
ir_high_update();
EIMSK|=(1<<INT0);
while(1)
{
if(ir_state == 0)
{
EIMSK&=~(1<<INT0);
if(lift_state == 0){
ascend();
_delay_ms(7000);
EIMSK|=(1<<INT0);
ir_high_update();
}
else if(lift_state == 1){
decend();
_delay_ms(7000);
EIMSK|=(1<<INT0);
ir_high_update();
}
}
_delay_ms(10);
}
return 0;
}
ISR(INT0_vect)
{
unsigned int confidence_ir=0;
if(ir_state == 1)
{
for(int i=0;i<confidence_max;i++)
{
if(~IR)
confidence_ir++;
_delay_ms(1);
}
if(confidence_ir>confidence_thresh)
ir_state=0;
}
}
ISR(INT1_vect)
{
unsigned int confidence_swt0=0;
if(swt0_state == 0)
{
for(int i=0;i<confidence_max;i++)
{
if(SWT0)
confidence_swt0++;
_delay_ms(1);
}
if(confidence_swt0>confidence_thresh)
swt0_state=1;
}
}
ISR(PCINT2_vect)
{
unsigned int confidence_swt1=0;
if(swt1_state == 0)
{
for(int i=0;i<confidence_max;i++)
{
if(SWT1)
confidence_swt1++;
_delay_ms(1);
}
if(confidence_swt1>confidence_thresh)
swt1_state=1;
}
}
|
C
|
#include "SeqQueue.h"
typedef struct Person {
char name[64];
int age;
}Person;
int main() {
SeqQueue* seq = InIt_SeqQueue();
Person p1 = { "aaa",10 };
Person p2 = { "bbb",20 };
Person p3 = { "ccc",30 };
Person p4 = { "ddd",40 };
Person p5 = { "eee",50 };
//
Push_SeqQueue(seq, &p1);
Push_SeqQueue(seq, &p2);
Push_SeqQueue(seq, &p3);
Push_SeqQueue(seq, &p4);
Push_SeqQueue(seq, &p5);
while (Size_SeqQueue(seq) > 0) {
Person* person = (Person*)Front_SeqQueue(seq);
printf("name:%s age:%d\n", person->name, person->age);
Pop_SeqQueue(seq);
}
system("pause");
return 0;
}
|
C
|
#include <string.h>
#include "pilha.h"
#include "operadores.h"
void interfaceCalculadora(PILHA* p1, PILHA* p2, PILHA* po){
int i=0,num;
int n1;
int n2;
char operador;
printf("Número de operacoes: ");
scanf("%d",&num);
while(i<num){
scanf("%d %c %d",&n1,&operador,&n2);
push(p1,n1);
//free(buffer);
//scanf("%c",&operador);
push(po,retornaIntParaCadaOperador(operador));
//free(operador);
//scanf("%d",&n2);
push(p2,n2);
//free(buffer);
i++;
}
//TEST_MESSAGE(buffer);
//push(p1,atoi(buffer));
//push(p2,2);
//push(po,1);
}
|
C
|
#ifndef __draughts_moves_h
#define __draughts_moves_h
#include "board.h"
// Special type that describes the move that can be performed
typedef struct moves_state {
int * params;
char * action;
struct moves_state * next;
int depth;
} moves_state;
/* Checks if the game is over, returns:
-1: game is not over
0: a draw
else number of a winner
*/
int rules_check_game_over(board_play * play);
// check events
void moves_check_events(board_play * play);
// Get an array of available moves for a player
moves_state * moves_get(board_play * play);
// Make a move based on the input. Return next available moves
moves_state * moves_define_and_make(board_play * play, char * input,
moves_state * moves);
// Execute a move. Return next available moves
moves_state * moves_exec(board_play * play, moves_state * state);
// Destroy moves_state array
void moves_destroy_moves(moves_state * moves);
// Unmake last move
void moves_unmake(board_play * play);
#endif
|
C
|
#include "spinnaker.h"
#define SOFT_RESET 0xf2000018 // CPU soft reset reg
#define MISC_CTRL 0xf2000038 // Misc control reg
// Write (poke) a single word to a neighbouring chip. Has a simple
// timeout mechanism which returns 0 on failure.
uint link_write_word (uint addr, uint link, const uint *buf)
{
volatile uint *cc = (uint *) CC_BASE;
uint t = 1024; // !! timeout - tweak this?
while ((cc[CC_TCR] & 0x80000000) == 0)
{
if (--t == 0)
return 0;
}
cc[CC_TCR] = 0x07a00000 + (link << 18); // NN direct packet
cc[CC_TXDATA] = *buf;
cc[CC_TXKEY] = addr;
while ((cc[CC_RSR] & 0x80000000) == 0)
{
if (--t == 0)
return 0;
}
addr = cc[CC_RXKEY];
return 1;
}
// Write "len" words to a neighbouring chip from buffer "buf".
// If any word times out returns 0, otherwise 1 when whole
// block sent.
uint link_write (uint addr, uint len, uint link, const uint *buf)
{
uint i;
for (i = 0; i < len; i++)
{
uint rc = link_write_word (addr, link, buf);
if (rc == 0)
return 0;
addr += 4;
buf++;
}
return 1;
}
// Boot a neighbouring chip with data supplied in a buffer. The
// load address ("addr") should normally be 0xf5000000 (System RAM)
// When download is complete CPU #0 is allowed to run, all others
// remain reset. NB - return codes not checked!
// addr - the load address for the data
// len - number of words
// link - the link number to use
// buf - array of words to be loaded
const uint w[] = {0x5ecfffff, 0x00000001, 0x5ec00002};
void link_boot (uint addr, uint len, uint link, uint *buf)
{
(void) link_write (SOFT_RESET, 1, link, w+0); // Reset all CPUs
(void) link_write (MISC_CTRL, 1, link, w+1); // Remap ROM/RAM
(void) link_write (addr, len, link, buf); // Copy buffer
(void) link_write (SOFT_RESET, 1, link, w+2); // Allow CPU #0 to run
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <SDL/SDL_image.h>
#include <SDL/SDL.h>
#include <SDL/SDL_ttf.h>
#include <SDL/SDL_mixer.h>
#include <time.h>
#include "scrolling.h"
//initialiser l'image du background et sa position initial
void SCROLL_Init(scrollImage *s /*variable de structure*/, char *path /*nom du image */)
{
s->img = IMG_Load("map.png");
s->position.x = s->position.y = s->position.w = s->position.h = 0;
s->clip.x = s->clip.y = 0;
s->clip.w = 5000;
s->clip.h = 600;
}
//bliter l'image du background dans sa nouvelle position
void SCROLL_Render(scrollImage *s /* variable de structure */, SDL_Surface **screen /*surface */)
{
SDL_BlitSurface(s->img, &s->clip, *screen, &s->position);
}
void animed(SDL_Rect animepos[], int *frame)
{
if (*frame < 4)
*frame = 3;
(*frame)++;
if (*frame > 7)
*frame = 4;
}
void animeg(SDL_Rect animepos[], int *frame)
{
if (*frame >= 4)
*frame = -1;
(*frame)++;
if (*frame == 2)
*frame = 3;
if (*frame > 3)
*frame = 0;
}
void initializeHero(Hero *hero)
{
SDL_Surface *tmp;
tmp = IMG_Load("anim.png");
hero->image = tmp;
SDL_Rect pos;
pos.x = 0;
pos.y = 0 /*hero.h*/;
hero->positionabs = pos;
SDL_Rect pos1;
pos1.x = 0;
pos1.y = 0;
hero->positionrel = pos1;
}
|
C
|
#include "clib.h"
#include "yakk.h"
#include "lab8defs.h"
#include "simptris.h"
#define ASTACKSIZE 256 /* Size of each stack in words */
#define BSTACKSIZE 256
#define CSTACKSIZE 256
#define MSGQSIZE 20
#define SEED 1251
np NPArray[NPARRAYSIZE]; /* buffers for new piece content */
cmd CmdArray[CMDARRAYSIZE]; /* buffers for command content */
stat StatArray[STATARRAYSIZE]; /* buffers for stat content */
int AStk[ASTACKSIZE]; /* Space for each task's stack */
int BStk[BSTACKSIZE];
int CStk[CSTACKSIZE];
void *NPQ[MSGQSIZE]; /* space for message queues */
void *CmdQ[MSGQSIZE];
void *StatQ[MSGQSIZE];
YKQ* NPQPtr; /* actual names of queues */
YKQ* CmdQPtr;
YKQ* StatQPtr;
void ATask(void); /* Function prototypes for task code */
void BTask(void);
void CTask(void);
YKSEM* RCSem; /* Semaphore for received command */
/* Function prototypes for utility code */
int find3space(int col); /* Finds nearest space 3 wide */
int find2space(int col);
int find1space(int col);
void postCommand(int cmd, int id, int dir);
void gameOver(void); /* Lists end of game stats ?*/
/* Global variables */
int lines = 0; /* total number of lines cleared */
int pieces = 0; /* number of pieces received */
void main(void) {
YKInitialize();
YKNewTask(ATask, (void *)&AStk[ASTACKSIZE], 5);
YKNewTask(BTask, (void *)&BStk[ASTACKSIZE], 15);
YKNewTask(CTask, (void *)&CStk[ASTACKSIZE], 25);
RCSem = YKSemCreate(1);
NPQPtr = YKQCreate(NPQ, MSGQSIZE);
CmdQPtr = YKQCreate(CmdQ, MSGQSIZE);
StatQPtr = YKQCreate(StatQ, MSGQSIZE);
YKRun();
}
void ATask(void){ /* Communicates with simptris */
cmd* command;
SeedSimptris((long) SEED);
StartSimptris();
printString("\n\nNew game\n");
while(1) { /* Pends on command queue */
YKSemPend(RCSem);
command = (cmd *) YKQPend(CmdQPtr);
/* Verify what command and piece */
// printString("piece id: ");
// printInt(command->id);
// printString(" cmd: ");
// printInt(command->cmd);
// printNewLine();
/* Does something with command */
if (command->cmd == SLIDE) {
SlidePiece(command->id, command->dir);
} else {
RotatePiece(command->id, command->dir);
}
}
}
int spaces = 0;
int space_dir = LEFT;
void BTask(void){ /* New Piece */
np* piece;
int i, col, id, dest, dir;
static int next = 0;
static int next_corner = 0;
static int corner_dir = RIGHT;
static int corners = 0;
//static int flag = 1;
//if(flag) {
// postCommand(SLIDE,5,RIGHT);
// flag = 0;
//}
while(1){
/* Removes pieces from piece queue */
piece = (np *) YKQPend(NPQPtr);
/* Decides what command to do */
col = piece->col;
id = piece->id;
if(piece->type == STRAIGHT){
if(spaces > MAXSPACES)
space_dir = RIGHT;
else{
space_dir = LEFT;
}
if(col == 5){ /* move the space one left then rotated */
postCommand(SLIDE, id, LEFT);
col--;
postCommand(ROTATE,id,space_dir);
} else if(col == 0){ /* piece needs to be moved right then rotated */
postCommand(SLIDE,id,RIGHT);
col++;
postCommand(ROTATE,id,space_dir);
} else if(piece->rot == 1){ /* verticle piece needs to be rotated */
postCommand(ROTATE,id,RIGHT);
}
/* move the piece to it's position */
if(space_dir == RIGHT){
dest = 4; // Should be 4
while(col < dest){
col++;
postCommand(SLIDE,id,RIGHT);
}
}else{ /* move space to the left section */
dest = 1; // Should be 1
while(col > dest){
// printString("slide left");
col--;
postCommand(SLIDE,id,LEFT);
}
}
} else {
/*
* X|
* 0 - XX| rot=1
*
* XXO| rot=3
* 1 - XOO|
*/
/* Rotations in the middle */
if(col > 0 && col < 5){
switch(piece->rot){
case 0: // Go from 0 to 1 or 0 to 3
dir = next_corner==0?LEFT:RIGHT;
postCommand(ROTATE,id,dir);
break;
case 1:
if(next_corner){ // Rotate twice to get to 3
postCommand(ROTATE,id,RIGHT);
postCommand(ROTATE,id,RIGHT);
}
break;
case 2: // Go from 2 to 1 or 2 to 3
dir = next_corner==0?RIGHT:LEFT;
postCommand(ROTATE,id,dir);
break;
case 3:
if(!next_corner){ // Rotate twice to get to 1
postCommand(ROTATE,id,RIGHT);
postCommand(ROTATE,id,RIGHT);
}
break;
}
} else if (col ==0) {
/* 0 can rotate RIGHT
* 1 never happens
* 2 never happens
* 3 can rotate LEFT
*/
switch(piece->rot){
case 0: // Go from 0 to 3, or slide first then rotate
if(!next_corner){ // Slide right first
postCommand(SLIDE,id,RIGHT);
col++;
}
dir = next_corner==0?LEFT:RIGHT;
postCommand(ROTATE,id,dir);
break;
case 3: // Rotate twice if needed
if(!next_corner){
postCommand(ROTATE,id,LEFT);
postCommand(SLIDE,id,RIGHT);
col++;
postCommand(ROTATE,id,LEFT);
}
break;
}
} else if (col == 5) {
/* 1 can rotate LEFT
* 2 can rotate RIGHT
*/
switch(piece->rot){
case 1: // Rotate twice to get 3 if needed
if(next_corner) {
postCommand(ROTATE,id,LEFT);
postCommand(SLIDE,id,LEFT);
col--;
postCommand(ROTATE,id,LEFT);
}
break;
case 2: // Go from 2 to 1, or rotate first
if(next_corner){
postCommand(SLIDE,id,LEFT);
col--;
}
dir = next_corner==0?RIGHT:LEFT;
postCommand(ROTATE,id,dir);
break;
}
}
/* Sliding */
if (corner_dir == RIGHT){
dest = next_corner==0?5:3;
// if(col == 3 && next_corner == 1){
//}else {
//if(dest == 4 && col >= 4){
while(col > dest){
postCommand(SLIDE,id,LEFT);
col--;
}
//} else{
while(col < dest) {
postCommand(SLIDE,id,RIGHT);
col++;
}
//}
} else {
dest = next_corner==0?0:2;
while(col > dest) {
postCommand(SLIDE,id,LEFT);
col--;
}
}
next_corner = !next_corner;
}
}
}
void postCommand(int cmd, int id, int dir){
static int next = 0;
// printString("Posting command: ");
// printInt(cmd);
// printString(", ID: ");
// printInt(id);
// printString(", dir: ");
// printInt(dir);
// printNewLine();
CmdArray[next].cmd = cmd;
CmdArray[next].id = id;
CmdArray[next].dir = dir;
/* Put commands on command queue */
if(YKQPost(CmdQPtr, (void *) &(CmdArray[next])) == 0)
printString(" Command queue overflow ! \n");
else if ( ++ next >= CMDARRAYSIZE)
next = 0;
}
void CTask(void){ /* Statistics */
stat* stats;
while(1){
/* Gets stats from stats queue */
stats = (struct stat *) YKQPend(StatQPtr);
if (stats->type == CLEAR)
lines++;
}
}
void gameOver(){
}
|
C
|
# include "stdio.h"
# include "stdlib.h"
/*
文件位置标志
系统为了对读写进行控制, 为每个文件设置了一个文件位置读写标记, 用来指示 接下来要读写的下一个字符的位置.
每一次读写, 文件读写标志都会向前进位.
在FILE结构体的定义中, 可以发现有一个 unsigned char * curp; 这就使文件位置标记(编译器的不同定义也不同)
void rewind(FILE * stream)
使文件位置标志重新回到文件头
int fseek(FILE * stream, long off, int whence)
stream 文件类型指针
off 位移量, 其是指以起始点为基点, 向前移动的字节数. 其数据类型是long, 数字常量后面加L就可以规定为long
whence 从哪里, 即起始点, 用0 SEEK_SET表示文件开始的位置, 1 SEEK_CUR 表示文件当前的位置, 2 SEEK_END表示文件末尾的位置
long ftell(FILE * stream)
得到流式文件中文件位置标记的当前位置
*/
void output_file(FILE *fp, int n){
printf("\n将读取 %d 个字符\n", n);
char ch = 0;
do {
ch = getc(fp);
putchar(ch);
n --;
} while (n>0);
putchar(10);
}
int main(int args, char * argv[]){
int seek_return = 0;
char *filepath = "./C_log.svg";
FILE *fp;
if ((fp=fopen(filepath, "r"))==NULL){
puts("文件打开失败.\n");
exit(0);
}
output_file(fp, 64);
printf("->当前ftell(fp) %ld\n", ftell(fp)); // 使用ftell获取文件位置标记
rewind(fp); // 使用rewind将文件位置标记重新指向文件开头
printf("->调用rewind(fp), 当前ftell(fp) %ld\n", ftell(fp));
output_file(fp, 10);
// 在已经读取了10个字符的情况下, 标记继续向后移动20, 将会从30字符开始
seek_return = fseek(fp, 20l, SEEK_CUR);
printf("->调用fseek(fp, 20, SEEK_CUR) 返回 %d, 当前ftell(fp) %ld\n", seek_return, ftell(fp));
// 在当前30字符, 向亲移动5, 变为25字符
seek_return = fseek(fp, -5, SEEK_CUR);
printf("->调用fseek(fp, -5, SEEK_CUR) 返回 %d, 当前ftell(fp) %ld\n", seek_return, ftell(fp));
// 在当前25字符, 向前移动100, 返回-1, 执行失败, 依然在25字符
seek_return = fseek(fp, -100, SEEK_CUR);
printf("->调用fseek(fp, -100, SEEK_CUR) 返回 %d, 当前ftell(fp) %ld\n", seek_return, ftell(fp));
// 从字符开头, 向后移动64, 将会从64字符开始
fseek(fp, 64, SEEK_SET);
printf("\n->调用fseek(fp, 64, SEEK_SET), 当前ftell(fp) %ld\n", ftell(fp));
output_file(fp, 32);
// 从字符结束, 向前移动128. 注意, 这里如果继续向后移动, 也可以, 不会报错, 但是打印出来的就不知道使哪里的东西了
fseek(fp, -128, SEEK_END);
printf("\n->调用fseek(fp, -128, SEEK_END), 当前ftell(fp) %ld\n", ftell(fp));
output_file(fp, 128);
/*
fp = freopen(filepath, "rb", fp);
上面的使用r文本打开, 但是因为使svg文件, 也没什么换行符, 用r和rb都是一样的
*/
// fseek()实现跳数据块
char ch = 0;
size_t chunk = 0;
for (int i=0; i<64; i+=2){
fseek(fp, i*sizeof(char), SEEK_SET); // 按照每个 字符的大小 * 个数 移动文件位置指针
chunk = fread(&ch, sizeof(char), 1, fp); // 读取 size * count字节的数据
if (i==0) printf("通过fseek与fread读取数据块, 数据块大小: %lu 字节\n", chunk);
putchar(ch);
}
putchar(10);
fclose(fp);
return 0;
}
|
C
|
#include "holberton.h"
/**
* print_p - prints a percent sign
*
* Return: the percent sign
*/
int print_p(void)
{
print_c('%');
return (1);
}
|
C
|
#include "ruzalo.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include "../structs_shared/jugador.h"
Ruzalo *ruzalo_init()
{
Ruzalo *ruzalo = malloc(sizeof(Ruzalo));
ruzalo->initial_life = 20000;
ruzalo->salto_active = false;
return ruzalo;
}
int choose_hability_ruzalo()
{
// 1: salto
// 0: espinavenenosa
float random_num;
random_num = rand() % 10;
printf("%f\n", random_num);
return random_num > 4;
}
void ruzalo_clean(Ruzalo *ruzalo)
{
free(ruzalo);
};
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <ctype.h>
#include <stdbool.h>
#include <ctype.h>
#include <time.h>
#include "dados.h" //Biblioteca que implementa a estrutura de dados lista ligada dinâmica
#define NUM_TENTATITVAS_LOGIN 3
REGISTRO cadastro()
/// Esta funcao recebe os dados do paciente a partir da entrada padrao e retorna esses dados em uma estrutura REGISTRO, definida em dados.h
{
REGISTRO reg; // struct em que os dados serao armazenados
int i;
printf("Insira nome: ");
fflush(stdin);
fgets(reg.nome, 255, stdin);
for (i = 0; reg.nome[i] != '\0'; i++)//Este laco percorre a string reg.nome e converte as letras minusculas em maiusculas
{
if (reg.nome[i] >= 'a' && reg.nome[i] <= 'z')
{
reg.nome[i] = reg.nome[i] - 32;
}
if(reg.nome[i] == '\n') reg.nome[i] = '\0'; //Troca o caractere de formatacao de nova linha "\n" pelo caractere de fim de string "\0"
if(reg.nome[i+1] == '\0') reg.nome[i] = NULL;
}
printf("\nInsira CPF: ");
fflush(stdin);
scanf("%lld", ®.cpf);
printf("\nInsira telefone: ");
fflush(stdin);
scanf("%d", ®.telefone);
printf("\nInsira endereco: ");
fflush(stdin);
scanf("%s", ®.endereco);
printf("\nInsira numero: ");
fflush(stdin);
scanf("%d", ®.numero);
printf("\nInsira bairro: ");
fflush(stdin);
scanf("%s", ®.bairro);
printf("\nInsira cidade: ");
fflush(stdin);
scanf("%s", ®.cidade);
printf("\nInsira estado: ");
fflush(stdin);
scanf("%s", ®.estado);
printf("\nInsira cep: ");
fflush(stdin);
scanf("%s", ®.cep);
printf("\nInsira o dia de nascimento: ");
fflush(stdin);
scanf("%d", ®.diaN);
printf("\nInsira o mes de nascimento: ");
fflush(stdin);
scanf("%d", ®.mesN);
printf("\nInsira o ano de nascimento: ");
fflush(stdin);
scanf("%d", ®.anoN);
printf("\nInsira email: ");
fflush(stdin);
scanf("%s", ®.email);
printf("\nInsira data diagnostico: ");
fflush(stdin);
scanf("%s", ®.diagnostico);
printf("\nAlguma comorbidade? \t [S / N]");
fflush(stdin);
scanf("%c", ®.comorbidade);
if (toupper(reg.comorbidade) == 'S')
{
printf("\nDigite as comorbidades: ");
fflush(stdin);
scanf("%s", ®.doencas);
} else strcpy(reg.doencas, "");
struct tm *data;
time_t segundos;
time(&segundos); //Esta funcao da biblioteca time.h retorna a hora do sistema em segundos
data = localtime(&segundos); // Converte de segundos para data atual
if(((data->tm_mon+1) <= reg.mesN) && (data->tm_mday < reg.diaN)){ //Calculo da idade
reg.idade = (data->tm_year + 1900) - reg.anoN -1;
}else{
reg.idade = (data->tm_year + 1900) - reg.anoN;
}
printf("\nIdade: %d\n", reg.idade);
if (reg.idade >= 65 || toupper(reg.comorbidade) == 'S') // Avaliacao quanto a inclusao no grupo de risco
{
registrarGrupoRisco(reg); // Se estiver no grupo de risco, registra no arquivo de texto
printf("Grupo de RISCO!!!\n");
system("pause");
}
else
{
printf("Fora do grupo de Risco!\n");
system("pause");
}
return reg;
}
void registrarGrupoRisco(REGISTRO reg)// Esta funcao recebe uma struct REGISTRO, e insere os dados no arquivo de paciente em grupo de risco
{
FILE *Ponteiro;
Ponteiro = fopen("grupo_de_risco.txt", "a");
fprintf(Ponteiro, "Cep: %s | Idade: %d | Nome: %s\n ------------------------------------\n", reg.cep, reg.idade, reg.nome);
fclose(Ponteiro);
}
bool autenticar(char *loginCad, char *senhaCad, int tentativas)
// Esta funcao realiza a autenticacao de usuarios
//*loginCad: string com o login ja cadastrado
//*senhaCad: string com a senha ja cadastrada
// tentativas: numero maximo de tentativas que podem ser realizadas antes que o programa feche automaticamente
{
setlocale(LC_ALL, "Portuguese");
char login[15];
char senha[7];
int cont = 0; //Armazena a quantidade de tentativas ja realizadas
int verifica_senha = 0;
/*Demais variaveis auxiliares de iteracao*/
char c;
int i;
int a;
do
{
i = 0;
fflush(stdin);
system("cls");
printf("Digite o LOGIN\a: ");
fflush(stdin);
scanf("%s", login);
printf("Digite a SENHA: ");
while ((c = getch()) != 13)
{
senha[i] = c;
putchar('*');
i++;
}
senha[i] = '\0';
if (strcmp(login, loginCad) == 0 && strcmp(senha, senhaCad) == 0)
{
printf("\nDADOS CORRETOS\n");
system("color 0a");
verifica_senha = 1;
Beep(1500, 500);
return true;
}
else
{
printf("\n FALHA \n");
system("color 0c");
Beep(1200, 200);
}
cont++;
} while (verifica_senha == 0 && cont < tentativas);
if (verifica_senha == 0)
{
printf("Você excedeu o número de tentativas!");
return false;
}
}
void arquivarGeral(REGISTRO reg)
// Esta funcao armazena os dados do paciente em "arquivo_pacientes.txt"
{
FILE *Ponteiro;
Ponteiro = fopen("arquivo_pacientes.txt", "a");
fprintf(Ponteiro, "{\"nome\": \"%s\", \"cpf\": \"%011lld\", \"telefone\": \"%d\", \"endereco\": \"%s\", \"numero\": \"%d\", \"bairro\": \"%s\", \"cidade\": \"%s\", \"estado\": \"%s\", \"cep\": \"%d\", \"diaN\": \"%d\", \"mesN\": \"%d\", \"anoN\": \"%d\", \"email\":\"%s\", \"diagnostico\": \"%s\", \"comorbidade\": \"%c\", \"idade\": \"%d\", \"doencas\": \"%s\"},\n",
reg.nome,
reg.cpf,
reg.telefone,
reg.endereco,
reg.numero,
reg.bairro,
reg.cidade,
reg.estado,
reg.cep,
reg.diaN,
reg.mesN,
reg.anoN,
reg.email,
reg.diagnostico,
reg.comorbidade,
reg.idade,
reg.doencas);
fclose(Ponteiro);
}
cadastrarUser(char *login, char *senha)
//Esta funcao realiza o cadastro de usuarios e armazena nos ponteiros char *login e char *senha
{
int c = 0;
int i = 0;
printf("Digite o LOGIN\a: ");
fflush(stdin);
scanf("%s", login);
printf("Digite a SENHA: ");
while ((c = getch()) != 13)
{
senha[i] = c;
putchar('*');
i++;
}
senha[i] = '\0';
}
int menuPrincipal(void)
// Esta funcao exibe o menu principal
{
int opcao = 1;
char loginCad[15];
char senhaCad[7];
loginCad[0] = 0;
LISTA pacientes; //instancia a estrutura de dados que armazena os registros dos pacientes
inicializarLista(&pacientes);
if (!loginCad[0]) //Se ainda não houver login cadastrado
{
printf("Cadastro de primeiro login\n");
cadastrarUser(loginCad, senhaCad);
system("cls");
}
do
{
printf("\nInsira\n [1] Novo cadastro de paciente\n [2] Alterar credencial de login\n [3] Sair\n [4] Exibir cadastros de pacientes\n [0] Fechar: ");
fflush(stdin);
scanf("%d", &opcao);
switch (opcao)
{
case 1:
{
REGISTRO reg = cadastro();
arquivarGeral(reg);
inserirElemento(&pacientes, reg);
system("cls");
break;
}
case 2:
{
cadastrarUser(loginCad, senhaCad);
system("cls");
break;
}
case 3:
{
if (!autenticar(loginCad, senhaCad, NUM_TENTATITVAS_LOGIN))
{
opcao = 0;
break;
}
system("cls");
break;
}
case 4:
{
exibirLista(&pacientes);
system("pause");
system("cls");
break;
}
case 0:
break;
default:
{
system("cls");
printf("Opcao invalida");
}
}
} while (opcao);
}
int main(void)
{
menuPrincipal();
system("pause");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int ft_atoi(char *str);
int main()
{
char *a;
a = " ------+++--+-2147483648fdgs363";
printf("%d", ft_atoi(a));
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* finish.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abombard <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/06 14:50:59 by abombard #+# #+# */
/* Updated: 2017/05/06 14:52:55 by abombard ### ########.fr */
/* */
/* ************************************************************************** */
#include "ping.h"
void finish(int signum)
{
(void)signum;
(void)signal(SIGINT, SIG_IGN);
printf("\n--- %s ping statistics ---\n", g_context.hostname);
printf("%ld packets transmitted, ", g_context.ntransmitted);
printf("%ld packets received, ", g_context.nreceived);
if (g_context.nrepeats)
(void)printf("+%ld duplicates, ", g_context.nrepeats);
if (g_context.ntransmitted)
{
if (g_context.nreceived > g_context.ntransmitted)
(void)printf("-- somebody's printing up packets!");
else
(void)printf("%d%% packet loss", (int)(((g_context.ntransmitted -
g_context.nreceived) * 100) / g_context.ntransmitted));
}
printf("\n");
if (g_context.nreceived)
{
(void)printf("round-trip min/avg/max = %ld.%ld/%lu.%ld/%ld.%ld ms\n",
g_context.tmin / 10, g_context.tmin % 10,
(g_context.tsum / (g_context.nreceived + g_context.nrepeats)) / 10,
(g_context.tsum / (g_context.nreceived + g_context.nrepeats)) % 10,
g_context.tmax / 10, g_context.tmax % 10);
}
exit(g_context.nreceived ? EXIT_SUCCESS : EXIT_FAILURE);
}
|
C
|
//
// Created by djvas on 28/09/2017.
//
#include "pr01_ex2017.h"
int main_pr01_ex2017(int argc, const char *argv[]) {
//readCharPrintAscii();
//readIntsPrintDiv();
//readDateGender();
//printAsciiTableLetters();
//printDigitOrNot();
//parseCountInStream();
//countInsertedChar();
return 0;
}
void readCharPrintAscii() {
char c = '\0';
do {
printf("Insira uma palavra\n");
scanf(" %c", &c);
printf("%c %d\n", c, c);
} while (c != '.');
}
void readIntsPrintDiv() {
int a = 2, b = 5;
printf("%d / %d = %0.2f\n", a, b, (float) a / b);
}
void readDateGender() {
int date = 0;
int month = 0;
int year = 0;
char gender = '\0';
printf("Instroduza a data, mes, ano e genero");
scanf("%d %d %d %c", &date, &month, &year, &gender);
}
void printAsciiTableLetters() {
for (int i = 'A'; i <= 'z'; ++i) {
printf("%c -> %d\n", i, i);
if (i > 'Z' && i < 'a')
continue;
}
}
void printDigitOrNot() {
char c = '\0';
do {
printf("Insira uma palavra\n");
scanf(" %c", &c);
if (c >= '0' && c <= '9')
printf("Digit\n");
else
printf("Not Digit\n");
} while (c != '.');
}
void parseCountInStream() {
}
void countInsertedChar() {
int cont = 0;
char c = '\0', c2='\0';
printf("Insira uma caracter\n");
scanf("%c", &c);
getchar();
while ((c2 = getchar()) != '\n') {
//printf("%c", c);
if (c2==c) {
cont++;
}
}
printf("char '%c' aparece %d vezes\n", c, cont);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int *InsertionSort(int *arr,int n);
void array_content(int *arr,int n);
int main(){
int arr[] = {1,20,5,6,3,4};
int n = 6;
int *sortedarr = InsertionSort(arr,n);
array_content(sortedarr,n);
}
int *InsertionSort(int *arr,int n){
int i;
for(i = 1;i < n;i = i + 1){
int current_val = *(arr + i);
int comp_place = i - 1;
while(comp_place >= 0 & current_val < *(arr + comp_place)){
*(arr + comp_place + 1) = *(arr + comp_place);
comp_place = comp_place - 1;
}
*(arr + comp_place + 1) = current_val;
}
return arr;
}
void array_content(int *arr,int n){
for(int i = 0;i < n;i = i + 1)
printf("%d\n",*(arr + i));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "mapreduce.h"
#include "word_freq.c"
void map_worker(int outfd, int infd) {
char filename[MAX_FILENAME];
FILE *file;
char chunk[READSIZE];
while (read(infd, filename, MAX_FILENAME) > 0) {
printf("Filename: %s from: %d\n", filename, outfd);
file = fopen(filename, "r");
// Read in each chunk from the file and send to be mapped.
if (file != NULL) {
while (fgets(chunk, READSIZE, file)) {
chunk[READSIZE - 1] = '\0';
// printf("Chunk: %s\n", chunk);
map(chunk, outfd);
}
} else {
printf("%s\n\n", filename);
perror("Unable to open file: ");
exit(1);
}
if (fclose(file) != 0) {
perror("File not closed properly:");
exit(1);
}
}
close(outfd);
close(infd);
printf("Exiting\n");
exit(0);
}
|
C
|
#include "Riostream.h"
#include "TFile.h"
#include "TTree.h"
using namespace std;
void MakeTree(void)
{
// Example of a script which reads some data and fills a TTree
// with a branch for each variable describing the data
//declaration of a structure for the data
struct data_t{
Int_t Eid;
Double_t E;
Double_t p;
Double_t theta;
Double_t phi;
Int_t PDG;
};
data_t data;
// open the data file for reading
ifstream file;
file.open("file.txt");
//UInt_t nevents = 100;
//open ROOT file to save the TTree in
TFile *ftree = new TFile("file.root","recreate");
//creation of TTree
TTree *t = new TTree("t", "TTree avec une structure");
//creation of branches to hold the variables of the structure
t->Branch("Eid", &data.Eid, "Eid/I");
t->Branch("E", &data.E, "E/D");
t->Branch("p", &data.p, "p/D");
t->Branch("theta", &data.theta, "theta/D");
t->Branch("phi", &data.phi, "phi/D");
t->Branch("PDG",&data.PDG, "PDG/I");
//loop over the 'nevents' events
//while( (nevents--) > 0 ){
//read the multiplicity of the event
// file >> event.Mult;
//loop over the particles of the event
while(!file.eof()){
//read the properties of each particle
file >> data.Eid;
file >> data.E;
file >> data.p;
file >> data.theta;
file >> data.phi;
file >> data.PDG;
t->Fill();
}
//fill the tree
// t->Fill();
//if( !(nevents%1000) ) cout << "Events left = " << nevents << endl;
//}
file.close();
//write and close the ROOT file
t->Write();
delete ftree;
}
|
C
|
#include <stdio.h>
int min(int a, int b);
int main()
{
int read[100];
int read_from_prompt;
int i;
int ret;
scanf("%d", &read_from_prompt);
for(i=0; i<read_from_prompt;i++)
{
scanf("%d", &read[i]);
}
ret = read[0];
for(i=0; i<read_from_prompt; i++)
{
ret = min(ret, read[i]);
}
printf("%d\n", ret);
return 0;
}
int min(int a, int b)
{
if(a<b)
return a;
else
return b;
}
|
C
|
#include "../inc/vptree.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#include <omp.h>
#define THRESHOLD 100000
#define SWAP(a,b) temp=(a);(a)=(b);(b)=temp;
/*
is a subtree. Features of this are coordinates, median distance, index of dataset, the left subtree-child and the right subtree
child
*/
/*
This funcion swaps rows of an 2D integer matrix.
*/
void swap_rows(int *index, int x, int y){
int temp;
temp=index[x];
index[x]=index[y];
index[y]=temp;
}
/*
This function is a component of quick select algorithm as shown in https://en.wikipedia.org/wiki/Quickselect .
It places the numbers which are smaller than the number on pivotIndex in the left-hand positions. The largest numbers are on the right.
The numbers are not sorted.
*/
int partition_array(double *list, int left, int right, int pivotIndex,int *index,int d){
double pivotValue=list[pivotIndex];
double temp=list[pivotIndex];
list[pivotIndex]=list[right];
list[right]=temp;
int itemp=index[pivotIndex];
index[pivotIndex]=index[right];
index[right]=itemp;
int storeIndex=left;
for(int i=left;i<right;i++){
if(list[i]<pivotValue){
temp=list[storeIndex];
list[storeIndex]=list[i];
list[i]=temp;
itemp=index[storeIndex];
index[storeIndex]=index[i];
index[i]=itemp;
storeIndex++;
}
}
temp=list[right];
list[right]=list[storeIndex];
list[storeIndex]=temp;
itemp=index[right];
index[right]=index[storeIndex];
index[storeIndex]=itemp;
return storeIndex;
}
/*
This function is a component of quick select algorithm as shown in https://en.wikipedia.org/wiki/Quickselect.
Returns the k-th smallest element of list within left..right inclusive.
*/
double selectFunction(double *list,int left, int right,int k,int *index,int d){
if(left==right){
return list[left];
}
int pivotIndex=left + floor(rand() % (right - left + 1));
pivotIndex=partition_array(list,left,right,pivotIndex,index,d);
if(k==pivotIndex){
return list[k];
}else if(k<pivotIndex){
return selectFunction(list,left,pivotIndex-1,k,index,d);
}else{
return selectFunction(list,pivotIndex+1,right,k,index,d);
}
}
/*
It is a retrospective function used to create the tree from top to leaf.
From an array of size n, select the last element of the tree as root.
The median distance is equal to the median of the distance vector if the number of the table is odd.
Otherwise the n / 2 -1 element is selected.
This is happening because the internal points remains the same while the computational cost is reduced compared to the median.
*/
vptree *recursevp(double *X, int *index ,int n, int d){
if(n==0){
vptree *tree = malloc(sizeof *tree);
tree=NULL;
return tree;
}
if(n==1){
vptree *tree = malloc(sizeof *tree);
tree->vp=(double *)malloc(d*sizeof(double));
for(int i=0;i<d;i++){
tree->vp[i]=X[index[n-1]*d+i];
}
tree->md=0;
tree->inner=NULL;
tree->outer=NULL;
tree->idx=index[0];
return tree;
}
vptree *tree = malloc(sizeof *tree);
tree->vp=(double *)malloc(d*sizeof(double));
for(int i=0;i<d;i++){
tree->vp[i]=X[index[n-1]*d+i];
tree->idx=index[n-1];
}
double *distances=(double *)malloc((n-1)*sizeof(double));
if(n*d>THRESHOLD){
#pragma omp shared(distances,X,index) private(i,sum)
{
#pragma omp parallel for schedule(static)
for (int i=0;i<n-1;i++){
double sum=0;
for(int j=0;j<d;j++){
sum+=(X[index[i]*d+j]-X[index[n-1]*d+j])*(X[index[i]*d+j]-X[index[n-1]*d+j]);
}
distances[i]=sqrt(sum);
}
}
}else{
for (int i=0;i<n-1;i++){
double sum=0;
for(int j=0;j<d;j++){
sum+=(X[index[i]*d+j]-X[index[n-1]*d+j])*(X[index[i]*d+j]-X[index[n-1]*d+j]);
}
distances[i]=sqrt(sum);
}
}
double median=0;
median=selectFunction(distances,0,n-2, floor((n-2)/2),index,d);
/*
for(int i=0;i<n-1;i++){
printf("Distances[i]= %lf \n",distances[i]);
}
*/
tree->md=median;
free(distances);
// printf("%lf |\n",median);
if(n*d>THRESHOLD){
#pragma omp parallel sections
{
#pragma omp section
tree->inner=recursevp(X,index,(int)floor(n/2),d);
#pragma omp section
tree->outer=recursevp(X,&index[(int)floor(n/2)],(int)floor((n-1)/2),d);
}
}else{
tree->inner=recursevp(X,index,(int)floor(n/2),d);
tree->outer=recursevp(X,&index[(int)floor(n/2)],(int)floor((n-1)/2),d);
}
return tree;
free(tree->vp);
free(tree);
}
/*
This function generates a vantage point tree of a dataset with n points and d dimensions.
*/
vptree *buildvp(double *X,int n, int d){
int *index=(int *)malloc(n*sizeof(int));
for(int i=0;i<n;i++){
index[i]=i;
}
return recursevp(X,index,n,d);
free(index);
};
//! Return vantage-point subtree with points inside radius
/*!
\param node A vantage-point tree
\return The vantage-point subtree
*/
vptree *getInner(vptree *tree){
return tree->inner;
};
//! Return vantage-point subtree with points outside radius
/*!
\param tree A vantage-point tree
\return The vantage-point subtree
*/
vptree *getOuter(vptree *tree){
return tree->outer;
};
//! Return median of distances to vantage point
/*!
\param tree A vantage-point tree
\return The median distance
*/
double getMD(vptree *tree){
return tree->md;
}
//! Return the coordinates of the vantage point
/*!
\param tree A vantage-point tree
\return The coordinates [d-dimensional vector]
*/
double *getVP( vptree *tree){
return tree->vp;
}
//! Return the index of the vantage point
/*!
\param tree A vantage-point tree
\return The index to the input vector of data points
*/
int getIDX( vptree *tree){
return tree->idx;
}
//! Delete the vantage point tree
/*!
\param tree A vantage-point tree
*/
void deleteTree(vptree *tree)
{
if (tree == NULL) return;
deleteTree(tree->inner);
deleteTree(tree->outer);
free(tree);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "queueADT.h"
struct node {
Item data;
struct node *next;
};
struct queue_type {
struct node *first;
struct node *last;
};
static void terminate(const char *message)
{
printf("%s\n", message);
exit(EXIT_FAILURE);
}
Queue create(void)
{
Queue q = malloc(sizeof(struct queue_type));
if (q == NULL)
terminate("Error in create: queue could not be created.\n");
q->first = NULL;
q->last = NULL;
return q;
}
void destroy(Queue q)
{
make_empty(q);
free(q);
}
void make_empty(Queue q)
{
while (!is_empty(q))
queue_remove(q);
}
bool is_empty(Queue q)
{
return (q->first == NULL);
}
bool is_full(Queue q)
{
return false;
}
void queue_insert(Queue q, Item i)
{
struct node *new_node = malloc(sizeof(struct node));
if (new_node == NULL)
terminate("Error in insert: queue is full.\n");
new_node->data = i;
if (is_empty(q)) {
new_node->next = new_node;
q->first = q->last = new_node;
return;
}
struct node *last_node = q->last;
last_node->next = new_node;
q->last = new_node;
}
Item queue_remove(Queue q)
{
struct node *old_front;
struct node *only_node;
Item i;
if (is_empty(q))
terminate("Error in queue_remove(): queue empty.\n");
if (q->first == q->last) { /* one node in linked list */
only_node = q->first;
i = only_node->data;
free(only_node);
q->first = NULL; /* if this line is omitted, throws 'glibc detected: double free' */
return i;
}
old_front = q->first;
q->first = old_front->next;
i = old_front->data;
free(old_front);
return i;
}
Item peek_first(Queue q)
{
struct node *first_node = q->first;
return first_node->data;
}
Item peek_last(Queue q)
{
struct node *last_node = q->last;
return last_node->data;
}
|
C
|
#ifndef __UQUEUE_H__
#define __UQUEUE_H__
typedef enum _uqueue_err
{
UQUEUE_ERROR_SUCCESS = 0,
UQUEUE_ERROR_INVALID_ARGS = 0x01010001,
UQUEUE_ERROR_NO_RESOURCE = 0x01010002,
UQUEUE_ERROR_EMPTY = 0x01010002,
}UQUEUE_ERROR_E;
typedef struct _UQUEUE_NODE
{
void *obj;
unsigned int len;
struct _UQUEUE_NODE *next;
}UQUEUE_NODE;
typedef struct
{
UQUEUE_NODE *head;
UQUEUE_NODE *tail;
unsigned int size;
}UQUEUE;
#define UQUEUE_SIZE(q) (q->size)
#define UQUEUE_EMPTY(q) (UQUEUE_SIZE(q) == 0)
UQUEUE *uqueue_new();
void uqueue_destroy(UQUEUE *queue);
int uqueue_enqueue(UQUEUE *queue, void *obj, int len);
int uqueue_dequeue(UQUEUE *queue, void **obj, int *len);
#endif
|
C
|
#include "gptimer.h"
#define ADDR 0x80000600
typedef struct {
volatile unsigned int counter; /* 0x0 */
volatile unsigned int reload; /* 0x4 */
volatile unsigned int control; /* 0x8 */
volatile unsigned int latch; /* 0xC */
} timerreg;
typedef struct {
volatile unsigned int scalercnt; /* 0x00 */
volatile unsigned int scalerload; /* 0x04 */
volatile unsigned int configreg; /* 0x08 */
volatile unsigned int latch; /* 0x0C */
timerreg timer[7];
} gptimer;
// Timer ticks every 10 cycles
#define RESOLUTION 9
#define MAX_VALUE 0xFFFFFFFF
unsigned int ntimers() {
gptimer *lr = (gptimer *) ADDR;
return (lr->configreg & 0x7); //Find number of counters configured.
}
void timer_start() {
gptimer *lr = (gptimer *) ADDR;
lr->scalerload = RESOLUTION;
lr->timer[0].reload = MAX_VALUE;
lr->timer[0].control = lr->timer[0].control | 0x7;
}
void timer_stop() {
gptimer *lr = (gptimer *) ADDR;
lr->timer[0].control = 0;
}
unsigned long timer_lap() {
gptimer *lr = (gptimer *) ADDR;
static unsigned long count = 0;
unsigned long int lap;
lap = (unsigned long) (count - lr->timer[0].counter);
count = lr->timer[0].counter;
return lap;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_sum(char *CHARSET, int *count){
int len = strlen(CHARSET);
int sum = 0;
if(len == 0) printf("0\n");
else{
for(int i = 0; i < len; i++){
sum += count[CHARSET[i]];
}
printf("%d\n", sum);
}
for(int i = 0; i < 256;i++)
count[i] = 0;
return;
}
int main(int argc, char *argv[])
{
/*
input issue
*/
FILE *fp;
char* CHARSET;
if(argc < 2){
fprintf(stderr, "NEED MORE ARGUMENTS\n" );
return 0;
}
else if(argc == 2){
CHARSET = argv[1];
fp = stdin;
}
else if(argc == 3){
CHARSET = argv[1];
fp = fopen(argv[2],"rb");
if(fp == NULL){
fprintf(stderr, "error\n" );
return 0;
}
}
else{
fprintf(stderr, "TOO MUCH ARGUMENTS\n" );
return 0;
}
/*
loop->result
*/
int count[256] = {0};
while(1){
char cha = fgetc(fp);
if(cha == EOF){
break;
}
else if(cha == '\n'){
print_sum(CHARSET, count);
continue;
}
else
count[cha]++;
}
return 0;
}
|
C
|
#include <stdio.h>
#include "mpi.h"
#define N 1024*1024
int main (int argc, char *argv[])
{
int rank, size, color, sum=0, localsum=0, i, chunk;
int arr[N], recv_arr[N], partialsum[N];
MPI_Status status;
int newrank, newsize;
MPI_Comm newcomm;
MPI_Init (&argc, &argv);
MPI_Comm_rank (MPI_COMM_WORLD, &rank);
MPI_Comm_size (MPI_COMM_WORLD, &size);
chunk = N/size;
// data initialization
if (!rank)
for (i=0; i<N; i++)
arr[i] = i+1;
// data distribution
double start=MPI_Wtime();
MPI_Scatter (&arr,chunk,MPI_INT,&recv_arr,chunk,MPI_INT,0,MPI_COMM_WORLD);
double scatter_time = MPI_Wtime() - start;
if (rank == 0) printf("Scatter time is =%f\n", scatter_time);
start = MPI_Wtime();
if (rank == 0) {
for (int i=1; i < size; i++)
MPI_Send(&arr, chunk, MPI_INT, i, i, MPI_COMM_WORLD);
}
if(rank) {
MPI_Recv(&recv_arr, chunk, MPI_INT, 0, rank, MPI_COMM_WORLD, &status);
}
double send_recv_time = MPI_Wtime() - start;
if (rank == 0) {
printf("Send/Recv Time is = %f\n", send_recv_time);
printf("%f\n", send_recv_time-scatter_time);
}
MPI_Finalize();
return 0;
}
|
C
|
#include<stdio.h>
void chk(char ar[30],char val)
{
int i=0;
int cnt=0;
while(ar[i] != val)
{
if(ar[i]==val)
{
break;
}
i++;
}
printf("found:%d ",i);
}
int main()
{
char a[30];
char ch;
printf("enter any string:");
scanf("%[^\n]s",&a);
printf("enter a character:");
scanf("%s",&ch);
chk(a,ch);
return 0;
}
|
C
|
//
// Author: huanglijun
// Date : 2019/6/6
// Desc : Solution35
//
/*
* 35. Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
*/
int searchInsert(vector<int>& nums, int target) {
int num = 0;
for(vector<int>::iterator iter = nums.begin(); iter != nums.end(); iter++){
if(*iter < target){
num++;
} else {
break;
}
}
return num;
}
#ifndef TESTCODE_SOLUTION35_H
#define TESTCODE_SOLUTION35_H
#endif //TESTCODE_SOLUTION35_H
|
C
|
#include <stdio.h>
int linearSearch(int arr[], int n, int x)
{
int i, z;
for (i = 0; i < n; i++)
{
if (x == arr[i])
{
z = i;
break;
}
else
{
z = -1;
}
}
return z;
}
int binarySearch(int arr[], int n, int x)
{
int lower, upper, mid;
upper = n-1; lower = 0;
while (lower <= upper)
{
mid = (lower + upper)/2;
if (x > arr[mid])
{
lower = mid + 1;
}
else if (x < arr[mid] )
{
upper = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
void bubblesortDec(int arr[], int n)
{
for(int i=0; i<n; i++)
{
for(int j=i+1; j<n; j++)
{
if(arr[i] < arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
void main()
{
int List[10], n = 10;
int p;
printf("PLease choose from the following options:\n 1.for Linear Search\n 2.for Binary Search\n 3.for Bubblesort\n 4.to exit \n");
scanf("%d", &p);
while (1)
{
if (p == 1)
{
printf("Enter 10 numbers\n");
for (int i = 0; i < n; i++)
{
scanf("%d", &List[i]);
}
int key;
printf("Enter element to search: ");
scanf("%d", &key);
int c = linearSearch(List, n, key);
if (c != -1)
{
printf("The element was found at %d position", c);
}
else
{
printf("The element was not found.");
}
break;
}
else if (p == 2)
{
printf("Enter 10 numbers\n");
for (int i = 0; i < n; i++)
{
scanf("%d", &List[i]);
}
int key;
printf("Enter element to search: ");
scanf("%d", &key);
int c = binarySearch(List, n, key);
if (c != -1)
{
printf("The element was found at %d position", c);
}
else
{
printf("The element was not found.");
}
break;
}
else if (p == 3)
{
printf("Enter 10 numbers\n");
for (int i = 0; i < n; i++)
{
scanf("%d ", &List[i]);
}
bubblesortDec(List, n);
printf("The descending order of the array is: ");
for (int i = 0; i < n; i++)
{
printf("%d ", List[i]);
}
printf("\n");
printf("The ascending order of the array is:");
for (int i = n-1; i >= 0; i--)
{
printf("%d ", List[i]);
}
break;
}
else if (p == 4)
{
printf("Bye Bye SearchNSort!");
break;
}
else
{
continue;
}
}
return;
}
|
C
|
#include <errno.h>
#include "file.h"
#include "strtype.h"
/*
* open a file (observing error handling)
*/
FILE* open_file(char* filename)
{
FILE *file = fopen(filename, FILE_PERMISSION);
if(file == NULL)
{
fprintf(stderr, "Error during file open. FILE: %s\n", filename);
exit(1);
}
return file;
}
/*
* ignore rest of current line
*/
void next_line(FILE *file) {
int c;
do {
c = fgetc(file);
} while (c && c != '\n');
}
/*
* read a integer (k) from input file (observing limits and security)
*/
int get_segment_size(FILE *file)
{
// set a buffer with SEGMENT_SIZE_BUFFER (extra space for '\0')
char buffer[SEGMENT_SIZE_BUFFER + 1];
int number;
fgets(buffer, SEGMENT_SIZE_BUFFER + 1, file);
sscanf(buffer, "%s\n", buffer);
// limit condition: ignore rest of current line
if (strlen(buffer) == SEGMENT_SIZE_BUFFER) {
next_line(file);
}
number = atoi(buffer);
if (number < 0 || number > WORD_SIZE)
return 0;
return number;
}
/*
* read a word from input file (observing limits and security)
* return the size of read word
* Notes:
* handling alphabet error: discard all invalid characters
* handling line too long error: discard all characters until end of line
*/
int get_word(FILE *file, char *word)
{
// set a buffer with WORD_SIZE (extra space for '\0')
char buffer[WORD_SIZE + 1];
// empty the word
word[0] = 0;
fgets(buffer, WORD_SIZE + 1, file);
// read only valid characters [a..z] from the buffer
sscanf(buffer, "%[a-z]s\n", word);
// force end of the word (in limit conditions)
word[WORD_SIZE] = 0;
int word_size = strlen(word);
// limit condition: ignore rest of current line
if (word_size == WORD_SIZE)
next_line(file);
return word_size;
}
/*
* execute the method to calculate LCS for all input cases
*/
void sweep_input(FILE *file, method execute)
{
int lcs;
// the string must contain space for termination mark ('\0')
char word0[WORD_SIZE + 1], word1[WORD_SIZE + 1];
int size0, size1;
// read the first k (zero implies end of execution)
int segment_size = get_segment_size(file);
// while exist input case to execute (test case)
while(segment_size != 0)
{
// reads both words
size0 = get_word(file, word0);
size1 = get_word(file, word1);
// is really there words?
if (size0 && size1) {
// sort the arguments (words)
//if (strlen(word0) <= strlen(word1))
lcs = execute(segment_size, word0, size0, word1, size1);
//else
// lcs = execute(segment_size, word1, size1, word0, size0);
// outputs the calculated size of longest common subsequence
printf("%d\n", lcs);
}
else
{
// returns zero, that always is a valid size of LCS,
// even in this system error condition (empty line or word)
printf("0");
}
// read another instance of k (zero implies end of execution)
segment_size = get_segment_size(file);
}
}
/*
* close a file (observing error handling)
*/
void close_file(FILE *file)
{
fclose(file);
if(errno)
{
fprintf(stderr, "Error during file close.");
exit(2);
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "class_compiler.h"
#include "method_pool.h"
#define _XOPEN_SOURCE 600
#define _POSIX_C_SOURCE 1
#define POOL_SIZE 512
#define BYTECODE_LENGTH 2048
#define MAX_LOCALS 50
extern char *strtok_r(char *, const char *, char **);
// TODO: Récuperer l'index du bytecode lorsqu' on écrit un if
// puis l'orsqu'on atteint la fin du if, on édite ce morceau de byte cod
typedef struct Method_info {
u2 access_flags;
u2 name_index;
u2 descriptor_index;
u2 attributes_count;
// on met directement la structure Code_attribute car c'est le seul attributs
u2 attribute_name_index;
u4 attribute_length;
u2 max_stack;
u2 max_locals;
u4 code_length;
u1 *code;
u2 exception_table_length;
u2 code_attributes_count;
} Method_info;
typedef struct local {
char *name;
char *type;
} local;
struct method {
char *name;
char *type;
u2 ref_index;
local **locals;
u2 locals_count;
u1 *bcode;
int length;
};
struct method_pool {
u2 method_count;
method *clinit;
Method_info **pool;
int list_count;
method **list; // on stockera les method dans une list pour ensuite les rechercher
// lorsqu'on les appellera dans le code, dans ce nous renveirrons leur type de retour
};
// Créé un structure method qui acceuille du byte code
method *method_create(method_pool *ptr, char *type, char *name, char *params, u2 method_ref) {
method *new = malloc(sizeof (method));
if (new == NULL) {
perror("Erreur malloc");
return NULL;
}
new->bcode = malloc(sizeof(u1) * BYTECODE_LENGTH);
if (new->bcode == NULL) {
perror("Erreur malloc");
return NULL;
}
new->locals = malloc(sizeof(local *) * MAX_LOCALS);
if (new->locals == NULL) {
return NULL;
}
new->length = 0;
new->locals_count = 0;
new->name = name;
new->type = type;
new->ref_index = method_ref;
char *save; // point de sauvegarde pour strtok_r
char *str = strtok_r(params, ",", &save);
while (str != NULL) {
char *type = strtok(str, ";");
char *name = strtok(NULL, ";");
method_add_local(new, type, name);
str = strtok_r(NULL, ",", &save);
}
method_pool_add_method(ptr, new);
return new;
}
// On enregistre une variable locale dans la structure methode
int method_add_local(method *ptr, char *type, char *name) {
local *l = malloc(sizeof(local));
if (l == NULL) {
return -1;
}
char *type_dup = malloc(strlen(type) + 1);
if(type_dup)
{
strcpy(type_dup, type);
}
char *name_dup = malloc(strlen(name) + 1);
if(name_dup)
{
strcpy(name_dup, name);
}
l->type = type_dup;
l->name = name_dup;
ptr->locals[ptr->locals_count] = l;
ptr->locals_count++;
return ptr->locals_count - 1;
}
// Ajoute une insctruction byte code codé sur un octet a la méthode
void method_instruction(method *ptr, u1 instr) {
memcpy(&ptr->bcode[ptr->length], &instr, 1);
ptr->length += 1;
}
void method_instruction_modify(method *ptr, u2 index, u1 instr) {
ptr->bcode[index] = instr;
}
u1 *method_render(method *ptr) {
return ptr->bcode;
}
int method_length(method *ptr) {
return ptr->length;
}
char *method_type(method *ptr) {
return ptr->type;
}
u2 method_locals_count(method *ptr) {
return ptr->locals_count;
}
// Retourne l'indice de la variable locale recherchée, si rien trouvé on renvoie -1
int method_search_local(method *ptr, char *name, char *type) {
for (int i = 0; i < ptr->locals_count; ++i) {
if (strcmp(ptr->locals[i]->name, name) == 0) {
strcpy(type, ptr->locals[i]->type);
return i;
}
}
return -1;
}
method_pool *method_pool_init(void) {
method_pool *ptr = malloc(sizeof(method_pool));
if (ptr == NULL) {
perror("Erreur malloc");
return NULL;
}
ptr->method_count = 0;
ptr->pool = malloc(sizeof(Method_info *) * POOL_SIZE);
ptr->list_count = 0;
ptr->list = malloc(sizeof(method *) * POOL_SIZE);
// Initialisation méthode instanciation(init)
method *ini = method_create(ptr, "()V", "init", "", 1);
// 0: aload_0
method_instruction(ini, 0x2a);
// 1: invokespecial 0x0001
method_instruction(ini, 0xb7);
method_instruction(ini, 0x00);
method_instruction(ini, 0x01);
// 4: return
method_instruction(ini, 0xb1);
if (method_pool_entry(ptr, 0x0001, 5, 6, 1, method_render(ini), method_length(ini)) != 0) {
perror("Methode ini");
return NULL;
}
// Initialisation constructeur (clinit), on ne la met pas dans la pool
ptr->clinit = method_create(ptr, "()V", "clinit", "", 1337);
return ptr;
}
method *method_pool_get_clinit(method_pool *ptr) {
return ptr->clinit;
}
Method_info *new_method(u2 access, u2 name_index, u2 type_index, u2 locals_count, u1 *code, int length) {
Method_info *ptr = malloc(sizeof(Method_info));
if (ptr == NULL) {
return NULL;
}
ptr->access_flags = access;
ptr->name_index = name_index;
ptr->descriptor_index = type_index;
ptr->attributes_count = 1;
ptr->attribute_name_index = constant_pool_code();
ptr->attribute_length =
sizeof(u2) * 4 + sizeof(u4) + length;
ptr->max_stack = 50;
ptr->max_locals = locals_count + 10; // par sécurité
ptr->code_length = length;
ptr->code = code;
ptr->exception_table_length = 0;
ptr->code_attributes_count = 0;
return ptr;
}
int method_pool_entry(method_pool *ptr, u2 access, u2 name_index, u2 type_index, u2 locals_count, u1 *code, int length) {
if (ptr->method_count == POOL_SIZE) {
perror("Max field pool entries.");
return -1;
}
ptr->pool[ptr->method_count] = new_method(access, name_index, type_index, locals_count, code, length);
ptr->method_count++;
return 0;
}
u2 method_pool_count(method_pool *ptr) {
return ptr->method_count;
}
void method_pool_fwrite(method_pool *ptr, size_t index, FILE *f) {
if (index >= ptr->method_count) {
perror("Invalid index");
return;
}
Method_info *meth = ptr->pool[index];
u2 access_flags = htons(meth->access_flags);
fwrite(&access_flags, sizeof(u2), 1, f);
u2 name_index = htons(meth->name_index);
fwrite(&name_index, sizeof(u2), 1, f);
u2 descriptor_index = htons(meth->descriptor_index);
fwrite(&descriptor_index, sizeof(u2), 1, f);
u2 attributes_count = htons(meth->attributes_count);
fwrite(&attributes_count, sizeof(u2), 1, f);
u2 attribute_name_index = htons(meth->attribute_name_index);
fwrite(&attribute_name_index, sizeof(u2), 1, f);
u4 attribute_length = htonl(meth->attribute_length);
fwrite(&attribute_length, sizeof(u4), 1, f);
u2 max_stack = htons(meth->max_stack);
fwrite(&max_stack, sizeof(u2), 1, f);
u2 max_locals = htons(meth->max_locals);
fwrite(&max_locals, sizeof(u2), 1, f);
u4 code_length = htonl(meth->code_length);
fwrite(&code_length, sizeof(u4), 1, f);
fwrite(meth->code, meth->code_length, 1, f);
u2 exception_table_length = htons(meth->exception_table_length);
fwrite(&exception_table_length, sizeof(u2), 1, f);
u2 code_attributes_count = htons(meth->code_attributes_count);
fwrite(&code_attributes_count, sizeof(u2), 1, f);
}
void method_pool_add_method(method_pool *ptr, method *new) {
ptr->list[ptr->list_count] = new;
ptr->list_count++;
}
// cherche un nom de méthode, si elle existe on renvoie son type
char *method_pool_search(method_pool *ptr, char *name) {
for (int i = 0; i < ptr->list_count; i++) {
if (strcmp(name, ptr->list[i]->name) == 0) {
return ptr->list[i]->type;
}
}
return NULL;
}
// Retourne l'index de son équivalent dans la constante pool
u2 method_pool_get_index(method_pool *ptr, char *name) {
for (int i = 0; i < ptr->list_count; i++) {
if (strcmp(name, ptr->list[i]->name) == 0) {
return ptr->list[i]->ref_index;
}
}
return 0;
}
// Terminaison de la method clinit en ajoutant un return
void method_pool_end(method_pool *ptr) {
method_instruction(ptr->clinit, 0xb1);
if (method_pool_entry(ptr, 0x0009, 10, 6, 1, method_render(ptr->clinit), method_length(ptr->clinit)) != 0) {
perror("Methode ini");
}
}
|
C
|
#include<stdio.h>
#include<sys/socket.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<netinet/in.h>
#include<string.h>
#include <arpa/inet.h>
#include<signal.h>
#define PORT 55769
struct communication{
char message[1024];
int flag; // 0 Read, 1 ReadWrite and 2 Close
};
int main(int argc, char const *argv[])
{
struct sockaddr_in server;
int sock_desc;
sock_desc = socket(AF_INET, SOCK_STREAM, 0);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(PORT);
connect(sock_desc, (void *)(&server), sizeof(server));
struct communication msg;
while(1){
int k = read(sock_desc, &msg, sizeof(msg));
printf("%s",&msg.message);
if(msg.flag == 1){
char input[1024];
scanf("%s",input);
write(sock_desc,input,sizeof(input));
}else if(msg.flag == 2){
close(sock_desc);
break;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t mutex;
char * buf[10];
int pos;
void *thid(void*p)
{
pthread_mutex_lock(&mutex);
buf[pos]=(char *)p;
sleep(1);
pos++;
pthread_mutex_unlock(&mutex);
}
int main()
{
pthread_mutex_init(&mutex,NULL);
pthread_t thid1,thid2;
pthread_create(&thid1,NULL,thid,(void *)"asdf");
pthread_create(&thid2,NULL,thid,(void *)"zxcvb");
sleep(10);
pthread_join(thid1,NULL);
pthread_join(thid2,NULL);
pthread_mutex_destroy(&mutex);
int i=0;
for(i=0;i<pos;++i)
printf("%s ",buf[i]);
printf("....../n");
return 0;
}
|
C
|
#include <stdio.h>
#include "misc.h"
#define MAX_NUM 1001
int main()
{
int i, j, sum = 1, num;
E_PRINTF("%d ", 1);
for(i=3;i<=MAX_NUM;i+=2)
{
for(j=0;j<4;j++)
{
num = (i-2)*(i-1)+1+(i-1)*j;
sum += num;
E_PRINTF("%d ", num);
}
}
printf("\nSum: %d\n", sum);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>
/*
*
* The producer-consumer problem using pthreads. This one is NOT safe.
* A context-switch within the critical section causes serious problems.
* We place pthread_yield() calls within cons() to increase the chances that
* a problem occurs.
*/
#define BUF_SZ 10
#define VAL_MIN 1
#define VAL_MAX 100
typedef struct pc_typ {
unsigned int head, tail;
unsigned int buf[BUF_SZ];
} pc_typ;
void *prod(void *arg) {
pc_typ *d = (pc_typ *)arg;
while(1) {
unsigned int h, t;
h = d->head; t = d->tail;
if(((h + 1)%BUF_SZ) == t) {
/* buf[] is full */
continue;
}
int val = (rand() % (VAL_MAX - VAL_MIN + 1)) + VAL_MIN;
printf("prod: buf[%d] <-- %d\n", h, val); fflush(stdout);
(d->buf)[(d->head)++] = val;
if((d->head) >= BUF_SZ) {
(d->head) %= BUF_SZ;
}
}
}
void *cons(void *arg) {
pc_typ *d = (pc_typ *)arg;
while(1) {
unsigned int h, t;
h = d->head; t = d->tail;
if(h == t) {
/* buf[] is empty */
continue;
}
int val = (d->buf)[t];
printf("cons: buf[%d] == %d\n", t, val); fflush(stdout);
(d->tail)++;
pthread_yield();
pthread_yield();
pthread_yield();
if((d->tail) >= BUF_SZ) {
(d->tail) %= BUF_SZ;
}
}
}
int main() {
pthread_t tc, tp;
pc_typ d;
int retcode = 0;
bzero(&d, sizeof(pc_typ));
srand(getpid());
retcode = pthread_create(&tc, NULL, &cons, (void *)&d);
if(retcode) {
fprintf(stderr, "pthread_create(cons), %s\n", strerror(retcode));
return 0;
}
retcode = pthread_create(&tp, NULL, &prod, (void *)&d);
if(retcode) {
fprintf(stderr, "pthread_create(prod), %s\n", strerror(retcode));
return 0;
}
retcode = pthread_join(tc, NULL);
if(retcode) {
fprintf(stderr, "pthread_join(cons), %s\n", strerror(retcode));
return 0;
}
retcode = pthread_join(tp, NULL);
if(retcode) {
fprintf(stderr, "pthread_join(prod), %s\n", strerror(retcode));
return 0;
}
return 0;
}
|
C
|
/*
* Scheduler.c
*
* Created: 2013-11-20 18:20:28
* Author: student
*/
#define F_CPU 16000000UL
#define MAX_TASKS 10
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
typedef void(*TASK_PTR) (void);
struct tsk{
TASK_PTR t;
uint16_t ToGo;
uint16_t Interval;
uint8_t ready;
};
struct tsk tasks[MAX_TASKS];
int tasks_num = 0;
void init(){
for(int i = 0; i < MAX_TASKS; i++){
tasks[i].Interval = 0;
tasks[i].ready = 0;
tasks[i].t = 0;
tasks[i].ToGo = 0;
}
}
void addTask(TASK_PTR task, uint16_t period){
if(tasks_num < MAX_TASKS){
tasks[tasks_num].Interval = period;
tasks[tasks_num].ToGo = period;
tasks[tasks_num].t = task;
tasks_num++;
}
}
void addOneShot(TASK_PTR task, uint16_t period){
if(tasks_num < MAX_TASKS){
tasks[tasks_num].Interval = 0;
tasks[tasks_num].ToGo = period;
tasks[tasks_num].t = task;
tasks_num++;
}
}
//wykonywana w przerwaniu
void schedule(){
//int i = 0;
for(int i = 0; i < MAX_TASKS; i++){
//jesli task nie jest pusty zmiejszamy ToGo
if(tasks[i].t != 0){
tasks[i].ToGo--;
//jesli ToGo = 0 zwiekszamy ready (periodyczny)
if(tasks[i].ToGo == 0 && tasks[i].Interval != 0){
tasks[i].ready++;
tasks[i].ToGo = tasks[i].Interval;
}
//(nie jest periodyczny)
else if(tasks[i].ToGo == 0 && tasks[i].Interval == 0){
tasks[i].ready++;
}
}
}
}
void execute(){
for(int i=0; i < MAX_TASKS; i++){
if(tasks[i].ready > 0){
tasks[i].t();
tasks[i].ready--;
//usuwanie taska jesli zostal wykonany i nie jest periodyczny
if(tasks[i].ready == 0 && tasks[i].Interval == 0){
tasks[i].Interval = 0;
tasks[i].ToGo = 0;
tasks[i].t = 0;
}
}
}
}
ISR(TIMER0_COMP_vect){
schedule();
}
void task1(){
PORTA = 0xFF;
}
void task2(){
PORTA = 0x00;
}
int main(void)
{
// prescaler na 64
OCR0 = 250;
TCCR0 |= (0 << WGM00) | (0 << WGM01) | (0 << CS02) | (1 << CS01) | (1 << CS00) | (0 << COM01) | (0 << COM00);
TIMSK |= (1 << TOIE0) | (1 << OCIE0);
DDRA = 0xFF;
init();
addTask(task1, 2);
addTask(task2, 4);
sei();
while(1){
execute();
}
return 0;
}
|
C
|
/* Copyright (C) 2005-2005 Henry Cejtin, Matthew Fluet, Suresh
* Jagannathan, and Stephen Weeks.
*
* MLton is released under a BSD-style license.
* See the file MLton-LICENSE for details.
*/
void displayHeap (__attribute__ ((unused)) GC_state s,
GC_heap heap,
FILE *stream) {
fprintf(stream,
"\t\tnursery = "FMTPTR"\n"
"\t\toldGenSize = %zu\n"
"\t\tsize = %zu\n"
"\t\tavailableSize = %zu\n"
"\t\tstart = "FMTPTR"\n"
"\t\tfrontier = "FMTPTR"\n",
(uintptr_t)heap->nursery,
heap->oldGenSize,
heap->size,
heap->availableSize,
(uintptr_t)heap->start,
(uintptr_t)heap->frontier);
}
void initHeap (__attribute__ ((unused)) GC_state s,
GC_heap h) {
h->nursery = NULL;
h->oldGenSize = 0;
h->size = 0;
h->availableSize = h->size;
h->start = NULL;
h->frontier = NULL;
}
/* sizeofHeapDesired (s, l, cs)
*
* returns the desired heap size for a heap with l bytes live, given
* that the current heap size is cs.
*/
size_t sizeofHeapDesired (GC_state s, size_t live, size_t currentSize) {
size_t res;
float ratio;
ratio = (float)s->sysvals.ram / (float)live;
if (ratio >= s->controls->ratios.live + s->controls->ratios.grow) {
/* Cheney copying fits in RAM with desired ratios.live. */
res = live * s->controls->ratios.live;
/* If the heap is currently close in size to what we want, leave
* it alone. Favor growing over shrinking.
*/
unless (1.1 * currentSize <= res
or res <= .5 * currentSize)
res = currentSize;
} else if (s->controls->ratios.grow >= s->controls->ratios.copy
and ratio >= 2 * s->controls->ratios.copy) {
/* Split RAM in half. Round down by pageSize so that the total
* amount of space taken isn't greater than RAM once rounding
* happens. This is so resizeHeap2 doesn't get confused and free
* a semispace in a misguided attempt to avoid paging.
*/
res = alignDown (s->sysvals.ram / 2, s->sysvals.pageSize);
} else if (ratio >= s->controls->ratios.copy + s->controls->ratios.grow) {
/* Cheney copying fits in RAM. */
res = s->sysvals.ram - s->controls->ratios.grow * live;
/* If the heap isn't too much smaller than what we want, leave it
* alone. On the other hand, if it is bigger we want to leave res
* as is so that the heap is shrunk, to try to avoid paging.
*/
if (currentSize <= res
and res <= 1.1 * currentSize)
res = currentSize;
} else if (ratio >= s->controls->ratios.markCompact) {
/* Mark compact fits in RAM. It doesn't matter what the current
* size is. If the heap is currently smaller, we are using
* copying and should switch to mark-compact. If the heap is
* currently bigger, we want to shrink back to RAM to avoid
* paging.
*/
res = s->sysvals.ram;
} else { /* Required live ratio. */
res = live * s->controls->ratios.markCompact;
/* If the current heap is bigger than res, then shrinking always
* sounds like a good idea. However, depending on what pages the
* VM keeps around, growing could be very expensive, if it
* involves paging the entire heap. Hopefully the copy loop in
* growHeap will make the right thing happen.
*/
}
if (s->controls->fixedHeap > 0) {
if (res > s->controls->fixedHeap / 2)
res = s->controls->fixedHeap;
else
res = s->controls->fixedHeap / 2;
if (res < live)
die ("Out of memory with fixed heap size %s.",
uintmaxToCommaString(s->controls->fixedHeap));
} else if (s->controls->maxHeap > 0) {
if (res > s->controls->maxHeap)
res = s->controls->maxHeap;
if (res < live)
die ("Out of memory with max heap size %s.",
uintmaxToCommaString(s->controls->maxHeap));
}
if (DEBUG_RESIZING)
fprintf (stderr, "%s = sizeofHeapDesired (%s, %s)\n",
uintmaxToCommaString(res),
uintmaxToCommaString(live),
uintmaxToCommaString(currentSize));
assert (res >= live);
return res;
}
void releaseHeap (GC_state s, GC_heap h) {
if (NULL == h->start)
return;
if (DEBUG or s->controls->messages)
fprintf (stderr, "[GC: Releasing heap at "FMTPTR" of size %s bytes.]\n",
(uintptr_t)(h->start),
uintmaxToCommaString(h->size));
GC_release (h->start, h->size);
initHeap (s, h);
}
void shrinkHeap (GC_state s, GC_heap h, size_t keep) {
assert (keep <= h->size);
if (0 == keep) {
releaseHeap (s, h);
return;
}
keep = align (keep, s->sysvals.pageSize);
if (keep < h->size) {
if (DEBUG or s->controls->messages)
fprintf (stderr,
"[GC: Shrinking heap at "FMTPTR" of size %s bytes to size %s bytes.]\n",
(uintptr_t)(h->start),
uintmaxToCommaString(h->size),
uintmaxToCommaString(keep));
GC_decommit (h->start + keep, h->size - keep);
h->size = keep;
}
}
/* createHeap (s, h, desiredSize, minSize)
*
* allocates a heap of the size necessary to work with desiredSize
* live data, and ensures that at least minSize is available. It
* returns TRUE if it is able to allocate the space, and returns FALSE
* if it is unable. If a reasonable size to space is already there,
* then heapCreate leaves it.
*/
bool createHeap (GC_state s, GC_heap h,
size_t desiredSize,
size_t minSize) {
size_t backoff;
if (DEBUG_MEM)
fprintf (stderr, "createHeap desired size = %s min size = %s\n",
uintmaxToCommaString(desiredSize),
uintmaxToCommaString(minSize));
assert (isHeapInit (h));
if (desiredSize < minSize)
desiredSize = minSize;
desiredSize = align (desiredSize, s->sysvals.pageSize);
assert (0 == h->size and NULL == h->start);
backoff = (desiredSize - minSize) / 20;
if (0 == backoff)
backoff = 1; /* enough to terminate the loop below */
backoff = align (backoff, s->sysvals.pageSize);
/* mmap toggling back and forth between high and low addresses to
* decrease the chance of virtual memory fragmentation causing an mmap
* to fail. This is important for large heaps.
* Note that the loop always trys a NULL address last.
*/
for (h->size = desiredSize; h->size >= minSize; h->size -= backoff) {
const unsigned int countLog2 = 5;
const unsigned int count = 0x1 << countLog2;
const size_t step = (size_t)0x1 << ((POINTER_SIZE * CHAR_BIT) - countLog2);
static bool direction = TRUE;
unsigned int i;
assert (isAligned (h->size, s->sysvals.pageSize));
for (i = 1; i <= count; i++) {
size_t address;
address = (size_t)i * step;
if (direction)
address = (size_t)0x0 - address;
h->start = GC_mmapAnon ((pointer)address, h->size);
if ((void*)-1 == h->start)
h->start = (void*)NULL;
unless ((void*)NULL == h->start) {
direction = not direction;
if (h->size > s->cumulativeStatistics->maxHeapSizeSeen)
s->cumulativeStatistics->maxHeapSizeSeen = h->size;
if (DEBUG or s->controls->messages)
fprintf (stderr, "[GC: Created heap at "FMTPTR" of size %s bytes.]\n",
(uintptr_t)(h->start),
uintmaxToCommaString(h->size));
assert (h->size >= minSize);
return TRUE;
}
}
if (s->controls->messages)
fprintf(stderr,
"[GC: Creating heap of size %s bytes cannot be satisfied; "
"backing off by %s bytes (min size = %s).]\n",
sizeToBytesApproxString (h->size),
sizeToBytesApproxString (backoff),
sizeToBytesApproxString (minSize));
}
h->size = 0;
return FALSE;
}
/* createHeapSecondary (s, desiredSize)
*/
bool createHeapSecondary (GC_state s, size_t desiredSize) {
if ((s->controls->fixedHeap > 0
and s->heap->size + desiredSize > s->controls->fixedHeap)
or (s->controls->maxHeap > 0
and s->heap->size + desiredSize > s->controls->maxHeap))
return FALSE;
return createHeap (s, s->secondaryHeap, desiredSize, s->heap->oldGenSize);
}
/* remapHeap (s, h, desiredSize, minSize)
*/
bool remapHeap (GC_state s, GC_heap h,
size_t desiredSize,
size_t minSize) {
size_t backoff;
size_t size;
#if not HAS_REMAP
return FALSE;
#endif
assert (minSize <= desiredSize);
assert (desiredSize >= h->size);
desiredSize = align (desiredSize, s->sysvals.pageSize);
backoff = (desiredSize - minSize) / 20;
if (0 == backoff)
backoff = 1; /* enough to terminate the loop below */
backoff = align (backoff, s->sysvals.pageSize);
for (size = desiredSize; size >= minSize; size -= backoff) {
pointer new;
new = GC_mremap (h->start, h->size, size);
unless ((void*)-1 == new) {
h->start = new;
h->size = size;
if (h->size > s->cumulativeStatistics->maxHeapSizeSeen)
s->cumulativeStatistics->maxHeapSizeSeen = h->size;
assert (minSize <= h->size and h->size <= desiredSize);
return TRUE;
}
}
return FALSE;
}
enum {
COPY_CHUNK_SIZE = 0x2000000, /* 32M */
};
/* growHeap (s, desiredSize, minSize)
*/
void growHeap (GC_state s, size_t desiredSize, size_t minSize) {
GC_heap curHeapp;
struct GC_heap newHeap;
pointer orig;
size_t size;
curHeapp = s->heap;
assert (desiredSize >= s->heap->size);
if (DEBUG_RESIZING)
fprintf (stderr, "Growing heap at "FMTPTR" of size %s to %s bytes.\n",
(uintptr_t)s->heap->start,
uintmaxToCommaString(s->heap->size),
uintmaxToCommaString(desiredSize));
orig = curHeapp->start;
size = curHeapp->oldGenSize;
assert (size <= s->heap->size);
if (remapHeap (s, curHeapp, desiredSize, minSize))
goto done;
shrinkHeap (s, curHeapp, size);
initHeap (s, &newHeap);
/* Allocate a space of the desired size. */
if (createHeap (s, &newHeap, desiredSize, minSize)) {
pointer from;
pointer to;
size_t remaining;
from = curHeapp->start + size;
to = newHeap.start + size;
remaining = size;
copy:
assert (remaining == (size_t)(from - curHeapp->start)
and from >= curHeapp->start
and to >= newHeap.start);
if (remaining < COPY_CHUNK_SIZE) {
GC_memcpy (orig, newHeap.start, remaining);
} else {
remaining -= COPY_CHUNK_SIZE;
from -= COPY_CHUNK_SIZE;
to -= COPY_CHUNK_SIZE;
GC_memcpy (from, to, COPY_CHUNK_SIZE);
shrinkHeap (s, curHeapp, remaining);
goto copy;
}
releaseHeap (s, curHeapp);
newHeap.oldGenSize = size;
*curHeapp = newHeap;
} else {
/* Write the heap to disk and try again. */
void *data;
data = GC_diskBack_write (orig, size);
releaseHeap (s, curHeapp);
if (createHeap (s, curHeapp, desiredSize, minSize)) {
GC_diskBack_read (data, curHeapp->start, size);
GC_diskBack_close (data);
} else {
GC_diskBack_close (data);
if (s->controls->messages)
GC_displayMem ();
die ("Out of memory. Unable to allocate %s bytes.\n",
uintmaxToCommaString(minSize));
}
}
done:
unless (orig == s->heap->start) {
translateHeap (s, orig, s->heap->start, s->heap->oldGenSize);
setCardMapAbsolute (s);
}
}
/* resizeHeap (s, minSize)
*/
void resizeHeap (GC_state s, size_t minSize) {
size_t desiredSize;
if (DEBUG_RESIZING)
fprintf (stderr, "resizeHeap minSize = %s size = %s\n",
uintmaxToCommaString(minSize),
uintmaxToCommaString(s->heap->size));
desiredSize = sizeofHeapDesired (s, minSize, s->heap->size);
assert (minSize <= desiredSize);
if (desiredSize <= s->heap->size)
shrinkHeap (s, s->heap, desiredSize);
else {
releaseHeap (s, s->secondaryHeap);
growHeap (s, desiredSize, minSize);
}
resizeCardMapAndCrossMap (s);
assert (s->heap->size >= minSize);
}
/* resizeHeapSecondary (s)
*/
void resizeHeapSecondary (GC_state s) {
size_t primarySize;
size_t secondarySize;
primarySize = s->heap->size;
secondarySize = s->secondaryHeap->size;
if (DEBUG_RESIZING)
fprintf (stderr, "secondaryHeapResize\n");
if (0 == secondarySize)
return;
if (2 * primarySize > s->sysvals.ram)
/* Holding on to heap2 might cause paging. So don't. */
releaseHeap (s, s->secondaryHeap);
else if (secondarySize < primarySize) {
unless (remapHeap (s, s->secondaryHeap, primarySize, primarySize))
releaseHeap (s, s->secondaryHeap);
} else if (secondarySize > primarySize)
shrinkHeap (s, s->secondaryHeap, primarySize);
assert (0 == s->secondaryHeap->size
or s->heap->size == s->secondaryHeap->size);
}
|
C
|
#include <assert.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
char *cmnd;
void usage(void) {
fprintf(stderr, "Usage: %s -p maxproc -w maxwork\n", cmnd);
exit(1);
}
int main(int argc, char **argv) {
int i;
int max_proc = 10;
int max_work = 0;
struct {
int type;
int pid;
int outstanding;
} *event;
int ec = 0;
int pid;
int outstanding = 0;
int c;
int max_outstanding = 0;
int sum_outstanding = 0;
int failed_forks = 0;
while ((c = getopt(argc, argv, "p:w:")) != EOF) {
switch (c) {
char *p;
case 'p':
max_proc = strtol(optarg, &p, 0);
if (p == optarg || *p) usage();
break;
case 'w':
max_work = strtol(optarg, &p, 0);
if (p == optarg || *p) usage();
break;
case '?':
usage();
default:
assert(0);
}
}
event = malloc(max_proc * 2 * sizeof(*event));
if (!event) {
fprintf(stderr,
"%s: cannot malloc event log: %s\n",
argv[0], strerror(errno));
exit(1);
}
for (i = 0; i < max_proc; i++) {
switch (pid = fork()) {
case -1:
assert(ec < 2*max_proc);
event[ec].type = 0;
event[ec].pid = pid;
event[ec].outstanding = outstanding;
ec++;
break;
case 0:
for (i = 0; i < max_work; i++) ;
exit(0);
break;
default:
outstanding++;
assert(ec < 2*max_proc);
event[ec].type = 0;
event[ec].pid = pid;
event[ec].outstanding = outstanding;
ec++;
while ((pid = wait3(NULL, WNOHANG, NULL)) > 0) {
outstanding--;
assert(ec < 2*max_proc);
event[ec].type = 1;
event[ec].pid = pid;
event[ec].outstanding = outstanding;
ec++;
}
}
}
while ((pid = wait3(NULL, 0, NULL)) > 0) {
outstanding--;
assert(ec < 2*max_proc);
event[ec].type = 1;
event[ec].pid = pid;
event[ec].outstanding = outstanding;
ec++;
}
for (i = 0; i < ec; i++) {
printf("%d: %s %d (%d outstanding)\n",
i,
event[i].type ? "exit" : "fork",
event[i].pid,
event[i].outstanding);
if (event[i].outstanding > max_outstanding) {
max_outstanding = event[i].outstanding;
}
sum_outstanding += event[i].outstanding;
if (event[i].type == 0 && event[i].pid == -1) {
failed_forks ++;
}
}
printf ("\n");
printf ("max outstanding: %d, avg outstanding: %g\n",
max_outstanding, (double)sum_outstanding / ec);
printf ("failed forks: %d\n", failed_forks);
exit(0);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "source.h"
int main()
{
/* Count alpha */
char *str = "How many alpha in this string?";
printf("count_isalpha: %d\n", count_isalpha(str));
return 0;
}
|
C
|
/*
* This is newton2.pas, translated into SubsetC.
*
* It functions identically, except for the text printouts,
* since we don't support string literals.
*/
float epsilon;
int number;
int foo;
int abc;
int test1(int j, int) // missing second identifier
{
return 1;
}
void test2() // cannot return in a void
{
return 1;
}
void proc()
{
foo = 1;
}
int foobar(int a)
{
return a;
}
int adder(int a, int b)
{
return a+b;
}
float root(float x)
{
abc = 10;
float r;
int rr;
r = 1 // missing semi-colon
while (abs(x / sqr(r) - 1) >=) // missing end of conditional
{
rr = (x / r + r) / 2; // incompatible types
}
return; // missing token to return
}
void print(int n, float root)
{
// We don't support strings, so just print one after the other
writeln(n);
writeln(root);
}
int main()
{
int i;
float f;
epsilon = 0.000006;
number = -1;
while (number != 0)
{
writeln();
read(number);
if (number == 0)
{
print(number, 0.0);
}
if (number > 0)
{
print(number, root(number));
}
}
int rval;
rval = foobar(); // Error (not enough params)
rval = foobar(abc); // OK
rval = adder(abc); // Error (not enough params)
rval = adder(abc, i); // OK
rval = adder(f, abc); // Error (invalid param types)
rval = proc(); // Error (cannot assign to procedure)
writeln(rval);
}
|
C
|
#ifndef TIMER_H_
#define TIMER_H_
#include <sys/time.h>
#include "types.h"
#define timestamp(tv) ((uint64_t) tv.tv_sec * 1000000ULL + (uint64_t) tv.tv_usec)
#define TIMER_INIT (struct timer) { .start = timer_now() }
struct timer {
uint64_t start;
};
static inline uint64_t timer_now() {
struct timeval tv;
gettimeofday(&tv, NULL);
return timestamp(tv);
}
static inline void timer_new(struct timer *t) {
t->start = timer_now();
}
static inline uint64_t timer_elapsed(struct timer *t) {
return timer_now() - t->start;
}
static inline bool timer_is_elapsed(struct timer *t, uint64_t p) {
if (timer_elapsed(t) > p) {
t->start += p;
return TRUE;
}
return FALSE;
}
static inline uint64_t timer_restart(struct timer *t) {
uint64_t n = timer_now();
uint64_t e = n - t->start;
t->start = n;
return e;
}
#endif /* TIMER_H_ */
|
C
|
/*
** aff_tree.c for aff_tree.c in /home/ozouf_h//42sh/src/parsing
**
** Made by harold ozouf
** Login <ozouf_h@epitech.net>
**
** Started on Thu Apr 19 13:14:24 2012 harold ozouf
** Last update Mon Apr 23 21:11:40 2012 harold ozouf
*/
#include <stdlib.h>
#include <stdio.h>
#include "token.h"
#include "tree.h"
static void aff_space(int nbr)
{
int i;
i = -1;
while (++i < nbr)
printf(" ");
}
static void toto(t_node *rt, int space)
{
t_child *ch;
ch = rt->child;
if (rt)
while (ch)
{
if (ch->nd)
{
aff_space(space);
if (ch->nd->id == PIPE)
printf("|____pipe\n");
if (ch->nd->id == CMD)
printf("|____cmd %s\n", ch->nd->content);
if (ch->nd->id == OR)
printf("|____OR\n");
if (ch->nd->id == AND)
printf("|____AND\n");
if (ch->nd->id == ARG)
printf("|____arg %s\n", ch->nd->content);
if (ch->nd->id == S_RED_LEFT || ch->nd->id == S_RED_RIGHT || ch->nd->id == D_RED_LEFT || ch->nd->id == D_RED_RIGHT)
printf("|____red %d \n", ch->nd->id);
toto(ch->nd, space + 5);
}
ch = ch->next;
}
}
void aff_tree(t_node *root)
{
t_child *tmp_c;
printf("pv:\n");
tmp_c = root->child;
while (tmp_c)
{
if (tmp_c->nd->id == PIPE)
printf("|____pipe\n");
if (tmp_c->nd->id == CMD)
printf("|____cmd %s\n", tmp_c->nd->content);
if (tmp_c->nd->id == OR)
printf("|____OR\n");
if (tmp_c->nd->id == AND)
printf("|____AND\n");
if (tmp_c->nd->id == ARG)
printf("|____arg %s\n", tmp_c->nd->content);
if (tmp_c->nd->id == S_RED_LEFT || tmp_c->nd->id == S_RED_RIGHT || tmp_c->nd->id == D_RED_LEFT || tmp_c->nd->id == D_RED_RIGHT)
printf("|____red %d \n", tmp_c->nd->id);
toto(tmp_c->nd, 5);
tmp_c = tmp_c->next;
}
printf("_______________________________________________________\n\n\n");
}
|
C
|
void main()
{
int a[5][5],i,y;
void move(int a[5][5],int n,int m);
int judge(int n,int m);
for(i=0;i<5;i++)
scanf("%d %d %d %d %d",&a[i][0],&a[i][1],&a[i][2],&a[i][3],&a[i][4]);
int n,m;
scanf("%d %d",&n,&m);
y=judge(n,m);
if(y==0)
printf("error");
else if(y==1)
{
move(a,n,m);
for(i=0;i<5;i++)
printf("%d %d %d %d %d\n",a[i][0],a[i][1],a[i][2],a[i][3],a[i][4]);
}
}
int judge(int n,int m)
{
if(n>=0&&n<5&&m>=0&&m<5)
return(1);
else return(0);
}
void move(int a[5][5],int n,int m)
{ int t,j,*p;
p=&a[0][0];
for(j=0;j<5;j++)
{
t=*(p+5*n+j);
*(p+5*n+j)=*(p+5*m+j);
*(p+5*m+j)=t;
}
}
|
C
|
#include<stdio.h>
#include<string.h>
int main(){
char s1[100],s2[100];
printf("Enter first String : ");
scanf("%s",s1);
printf("Enter second String : ");
scanf("%s",s2);
strcat(s1,s2);
printf("New String is : %s",s1);
return 0;
}
|
C
|
/*main.c Khartikova*/
#include "shell.h"
int main()
{
TMemory *mem = NULL;
for (;;)
{
int t;
/*save environment*/
t = open("dev/tty", O_RDWR, 0);
dup2(t, 0);
dup2(t, 1);
/*greeting*/
printf("khash:%s[", getenv("USER"));
if (strcmp(getenv("PWD"), getenv("HOME")) == 0)
printf("~]");
else
printf("%s]", cut(getenv("PWD")));
if (getuid())
printf("$ ");
else
printf("# ");
signal(SIGINT, SIG_DFL);
/*string processing*/
mem = (TMemory *)malloc(sizeof(TMemory));
mem->end = mem->beg;
if (readme(mem) != -1)
{
/*signal(SIGINT, SIG_IGN);*/
analyze_this(mem);
/*restore environment*/
close(t);
if (mem->end != mem->beg)
free(mem->beg);
mem->end = mem->beg;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
float altura;
float peso;
float imc;
printf("Informe os dados do paciente.\n");
printf("Peso em kg: ");
scanf("%f", &peso);
printf("Altura em metros: ");
scanf("%f", &altura);
imc = (peso / pow(altura, 2));
if (imc < 18.5)
printf("Abaixo do Peso.\n");
else if (imc >= 18.6 && imc <= 24.9)
printf("Saudável.\n");
else if (imc >= 25.0 && imc <= 29.9)
printf("Peso em excesso.\n");
else if (imc >= 30.0 && imc <= 34.9)
printf("Obesidade Grau 1.\n");
else if (imc >= 35.0 && imc <= 39.9)
printf("Obesidade Grau 2 (severa).\n");
else if (imc >= 40.0)
printf("Obesidade Grau 3 (mórbida).\n");
return (0);
}
|
C
|
// Distance Measure
#ifndef Distance
#define Distance
//////////////
#include "Main.h"
#include "LEDs.h"
#define DISTANCE_CLOCK PC5
#define DISTANCE_DATA PC4
#define DISTANCE_PORT PINC
#define ClockDistHigh bit_set(PORTC,PC5)
#define ClockDistLow bit_clear(PORTC,PC5)
//prototypes
void InitializeDistance(void);
int GetDistance(void);
int IsCloseEnough(int TooFar, int TooClose, int daTestValue);
//functions
void InitializeDistance(void)
{
bit_set(DDRC,5);//set pin for output to Distance
bit_clear(DDRC,DISTANCE_DATA);//set pin for input from Distance
bit_set(PORTC,DISTANCE_DATA);//turn on pull-up resistor
ClockDistHigh; //bit_set(DISTANCE_PORT,DISTANCE_IN);//D IN is normally high
}
int GetDistance(void)
{
int daDistanceIs=0;
int us_time=50;//optimal
ClockDistHigh;
delayms(4);
ClockDistLow;
for(int i=0;i<=30;++i)
{
delayms(1);
//_delay_us(900);
if(bit_get(DISTANCE_PORT,DISTANCE_DATA))
{
//measurment is complete
break;
}
}
ClockDistHigh;
_delay_us(us_time);
for(int i=8; i>0; i--)
{
ClockDistLow;
_delay_us(us_time);
if (bit_get(PINC,4))
{
bit_clear(daDistanceIs,(i-1));
}
else
{
bit_set(daDistanceIs,(i-1));
}
ClockDistHigh;
_delay_us(us_time);
}
ClockDistHigh;
return daDistanceIs;
}
int IsCloseEnough(int TooFar, int TooClose, int daTestValue)
{
// ******************************
// DISTANCE GROUPER
// int TooFar is farther as the number gets smaller. Lower limit of 1
// int TooClose is closer as the number gets bigger. Upper limit of 254
// ******************************
const int STATE_NOT_CLOSE_ENOUGH=0;
const int STATE_TOO_CLOSE=1;
// const int STATE_YES=2;//the actual value, up to 255;
const int CLEAR_THE_VARIABLE=0;
//int daTestValue=CLEAR_THE_VARIABLE;
int IsCloseEnoughResult=CLEAR_THE_VARIABLE;
// ******************************
//daTestValue=GetDistance();
if(daTestValue > TooFar)
{
if(daTestValue >= TooClose) //*** Too Close *** Too Close *** Too Close ***
{
IsCloseEnoughResult=STATE_TOO_CLOSE;
}
else //*** We Are In The Zone of Goodness *** We Are In The Zone of Goodness ***
{
IsCloseEnoughResult=daTestValue;
}
}
else //*** Noop, Not Close Enough *** Noop, Not Close Enough ***
{
IsCloseEnoughResult=STATE_NOT_CLOSE_ENOUGH;
}
return IsCloseEnoughResult;
// ******************************
}
///////////////////
///////////////////
///////////////////
#endif
|
C
|
#include <stdio.h>
int add(int x, int y) {
return x + y;
}
int subtract(int x, int y) {
return x - y;
}
int multiply(int x, int y) {
return x * y;
}
int divide(int x, int y) {
return x / y;
}
int domath(int (*mathop)(int, int), int x, int y) {
int res = (*mathop)(x, y);
return res;
}
int getinput()
{
int method;
printf("1.Add, 2.Sub, 3.Mul, 4.Div\n");
scanf("%d", &method);
return method;
}
void print(char a[], int i){
printf("%s gives %d\n", a, i);
}
int callmathmethod(int method) {
int result = 666;
switch (method) {
case 1:
result = domath(add, 10, 2);
break;
case 2:
result = domath(subtract, 10, 2);
break;
case 3:
result = domath(multiply, 10, 2);
break;
case 4:
result = domath(divide, 10, 2);
break;
default:
printf("wrong input\n");
}
return result;
}
int main() {
int method = getinput();
int a, b, c, d;
char *e[] = {"Tom", "Add", "Subtract", "Multiply", "Divide"};
int result = callmathmethod(method);
print(e[method], result);
}
|
C
|
/*******************************************************************************
* This file is part of the "Data structures and algorithms" course. FMI 2018/19
*******************************************************************************/
/**
* @file example.c
* @author Ivan Filipov
* @date 12.2019
* @brief Some tests and usage examples for our
* searching algorithms implementations.
*
* @see https://en.wikipedia.org/wiki/Search_algorithm
* @note Theory in searching_algorithms.h, implementation details in searching_algorithms.c
*/
#include <stdio.h> // printf()
#include <stdlib.h> // qsort()
#include <math.h> // sqrt()
#include "search_algorithms.h"
#define ARR_SIZE 12 //!< how many elements are there
/// simply output an array's content
void print_arr(int arr[], size_t size) {
for (size_t i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n\n");
}
// ugly syntax function for qsort
int cmp(const void* x, const void* y) {
return *(int*)x - *(int*)y;
}
int main() {
int arr[ARR_SIZE] = { -124, 5, 11, 2, 6, 7, -42, 13, 88, 21, 9, 8 };
printf("Starting array : \n");
print_arr(arr, ARR_SIZE);
printf("after sorting with qsort : \n");
qsort(arr, ARR_SIZE, sizeof(int), cmp);
print_arr(arr, ARR_SIZE);
int searched_elem = 11;
printf("result of Linear searching for elem %d : %d \n",
searched_elem, linear_search(arr, ARR_SIZE, searched_elem));
printf("result of Binary searching for elem %d : %d \n",
searched_elem, binary_search(arr, ARR_SIZE, searched_elem));
printf("result of Jump searching for elem %d with step %d : %d \n",
searched_elem, (int)sqrt(ARR_SIZE), jump_search(arr, ARR_SIZE, searched_elem));
searched_elem = -11;
printf("result of Linear searching for elem %d : %d \n",
searched_elem, linear_search(arr, ARR_SIZE, searched_elem));
printf("result of Binary searching for elem %d : %d \n",
searched_elem, binary_search(arr, ARR_SIZE, searched_elem));
printf("result of Jump searching for elem %d with step %d : %d \n",
searched_elem, (int)sqrt(ARR_SIZE), jump_search(arr, ARR_SIZE, searched_elem));
return 0;
}
|
C
|
#include "loader.h"
/*************************************************************************
* loads the contents of a text file into an array and returns the
* number of lines that were loaded. The assumption is that each line
* of the file is at most LINE_LEN characters long
************************************************************************/
unsigned load(char * fname, char lines[][LINE_LEN+1])
{
/* memory that we read each line into */
char line[LINE_LEN + EXTRA_SPACES];
/* how many lines have we read ? */
unsigned curline=0;
/* the file we are reading from */
FILE * fpread = fopen(fname, "r");
/* if there was a problem reading from the file return an error
* indicator
*/
if(!fpread)
{
perror("opening file");
return FAIL;
}
/* otherwise, read lines from the file until we get to the end of the
* file
*/
while(fgets(line, LINE_LEN+EXTRA_SPACES, fpread))
{
/* test that the line was not too long */
if(line[strlen(line)-1]!='\n')
{
fprintf(stderr, "Error: line too long in input file.\n\n");
fclose(fpread);
return FAIL;
}
/* remove the new line as we now know the line was within the
* allowed line length
*/
line[strlen(line)-1]=0;
/* copy the line into our array */
strcpy(lines[curline++], line);
/* test that we have not overreached the maximum number of
* lines to read
*/
if(curline >= MAX_LINES)
{
fprintf(stderr, "Maximum lines reached.\n\n");
fclose(fpread);
return FAIL;
}
}
/* close the file */
fclose(fpread);
/* return the number of lines read into the array */
return curline;
}
/**************************************************************************
* prints out the lines in the array passed in inside a box for formatting
*************************************************************************/
void printarray(char lines[][LINE_LEN+1], unsigned height)
{
unsigned width;
unsigned count;
/* we need the longest element to know how big the bounding box
* needs to be
*/
width=find_longest(lines, height);
putchar('\n');
/* print the top of the box */
putline(width + 2);
/* print each line of the file */
for(count=0; count < height; ++count)
{
printf("|%*s|\n",width, lines[count]);
}
/* print the bottom of the box */
putline(width+2);
printf("\n\n\n");
}
/**************************************************************************
* finds the length of the longest string in an array of strings.
*************************************************************************/
unsigned find_longest(char lines[][LINE_LEN+1], unsigned height)
{
/* the length of the longest line found so far */
unsigned longest=0;
/* simple counter */
unsigned count;
for(count = 0; count < height; ++count)
{
/* if the length of the current line is longer than we have
* seen, store it
*/
unsigned length = strlen(lines[count]);
if(length > longest)
longest = length;
}
return longest;
}
void putline(unsigned length)
{
unsigned count;
for(count = 0; count < (length); ++count)
{
putchar('-');
}
putchar('\n');
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.