language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <string.h>
#include <security/pam_appl.h>
#include <security/pam_misc.h>
static const char *item_msg[14] = {"","SERVICE","USER","TTY","RHOST","CONV","AUTHTOK","OLDAUTHTOK","RUSER","USER_PROMPT","FAIL_DELAY","XDISPLAY","XAUTHDATA","AUTHTOK_TYPE"};
static struct pam_conv conv = {
misc_conv,
NULL
};
void show_item(int item,pam_handle_t *handle){
int pam_err;
const void *object;
pam_err = pam_get_item(handle,item,&object);
if(pam_err!=PAM_SUCCESS){
printf("Failed to retreve %s : %s\n", item_msg[item], pam_strerror(handle,pam_err));
}
else{
if(object!=NULL){
printf("%s is : %s\n", item_msg[item], (char*)object);
}
else{
printf("%s is NULL\n",item_msg[item]);
}
}
}
int main(int argc,char *argv[]){
int pam_err,i;
int pam_flag = 0;
pam_handle_t *handle = NULL;
const char *user = "nobody";
const void *item = NULL;
for (i=1;i<argc;i++)
{
if(strncmp(argv[i],"user=",5)==0)
user = &(argv[i][5]);
if(strncmp(argv[i],"silent",6)==0)
pam_flag = PAM_SILENT;
}
printf("The user is %s\n",user);
pam_err = pam_start("test_pam",user,&conv,&handle);
if(pam_err != PAM_SUCCESS){
printf("pam_start error : %d %s\n",pam_err,pam_strerror(handle,pam_err));
return pam_err;
}
pam_err = pam_authenticate(handle,pam_flag);
if(pam_err != PAM_SUCCESS){
printf("pam_authenticate error :%d %s\n",pam_err,pam_strerror(handle,pam_err));
return pam_err;
}
else{
printf("Authentication succesful !!\n");
}
/*pam_err = pam_acct_mgmt(handle,0);
if(pam_err != PAM_SUCCESS){
printf("pam_acct_management error :%d %s\n",pam_err,pam_strerror(handle,pam_err));
return pam_err;
for(i=1;i<7;i++){
printf("Now looking up : %s\n",item_msg[i]);
show_item(i,handle);
}
*/
pam_err = pam_end(handle,pam_err);
return pam_err;
}
|
C
|
//
// memoryReVariable.c
// TestingGround
//
// Get the address and size of the variable. Typecast the address to char pointer. Now loop for size of the variable and print the value at typecasted pointer.
//
#include <stdio.h>
typedef unsigned char *bytePointer;
/*
show bytes takes byte pointer as an argument
and prints memory contents from bytePointer
to bytePointer + len
*/
int showBytes(bytePointer start, int len) {
int i;
for (i = 0; i < len; i++)
{
printf(" %.2x", start[i]);
printf("\n");
}
return 0;
}
void showInt(int x)
{
showBytes((bytePointer) &x, sizeof(int));
}
void showFloat(float x)
{
showBytes((bytePointer) &x, sizeof(float));
}
void showPointer(void *x)
{
showBytes((bytePointer) &x, sizeof(void *));
}
/* Drover program to test above functions */
int main(void)
{
int i = 1;
float f = 1.0;
int *p = &i;
showFloat(f);
showInt(i);
showPointer(p);
showInt(i);
return(0);
}
|
C
|
#include "image.h"
void I_print(struct color img[] , int nb_pixels){
for (int i = 0; i < nb_pixels; ++i)
{
C_print(img[i]);
}
}
void I_coef(struct color img[] , int nb_pixels, float coef){
for (int i = 0; i < nb_pixels; ++i)
{
img[i] = C_multiply(img[i],coef);
// C_print(img[i]);
}
}
void I_negative(struct color img[] , int nb_pixels){
for (int i = 0; i < nb_pixels; ++i)
{
img[i] = C_negative(img[i]);
// C_print(img[i]);
}
}
void I_permute(struct color img[] , int nb_pixels){
for (int i = 0; i < nb_pixels; ++i)
{
img[i] = C_permute(img[i]);
// C_print(img[i]);
}
}
void I_grayScale(struct color img[] , int nb_pixels){
for (int i = 0; i < nb_pixels; ++i)
{
img[i] = C_grayScale(img[i]);
// C_print(img[i]);
}
}
void I_threshold(struct color img[] , int nb_pixels, int th){
for (int i = 0; i < nb_pixels; ++i)
{
printf("%d\n", C_threshold(img[i],th));
}
}
void I_compose(struct color img1[], struct color img2[], int nb_pixels,
struct color target){
for (int i = 0; i < nb_pixels; ++i)
{
if(C_areEqual(img1[i],target) == 1){
img2[i].red = target.red;
img2[i].green = target.green;
img2[i].blue = target.blue;
}
}
}
void I_addColor(struct color img[], int nb_pixels, struct color c){
for (int i = 0; i < nb_pixels; ++i)
{
img[i].red += c.red;
img[i].blue += c.blue;
img[i].green += c.green;
}
}
void I_gradient(struct color img_in[], struct color img_out[], int nb_pixels){
img_out[0] = C_new(127,127,127);
for (int i = 1; i < nb_pixels; ++i)
{
img_out[i].red = clamp(img_in[i].red - img_in[i-1].red + 127);
img_out[i].green = clamp(img_in[i].green - img_in[i-1].green + 127);
img_out[i].blue = clamp(img_in[i].blue - img_in[i-1].blue + 127);
}
}
void I_gradient1(struct color img_in[], struct color img_out[], int nb_pixels){
img_out[0] = C_new(255,255,255);
for (int i = 1; i < nb_pixels; ++i)
{
img_out[i].red = clamp(img_in[i].red - img_in[i-1].red + 127);
img_out[i].green = clamp(img_in[i].green - img_in[i-1].green + 127);
img_out[i].blue = clamp(img_in[i].blue - img_in[i-1].blue + 127);
}
}
struct color I_average(struct color img[], int nb_pixels, int fromhere,
int nb_pixels_average){
struct color sum;
sum.red = 0;
sum.green = 0;
sum.blue = 0;
if(fromhere+nb_pixels_average >= nb_pixels){
nb_pixels_average = nb_pixels - fromhere -1;
}
for (int i = fromhere; i < fromhere+nb_pixels_average; ++i)
{
sum.red += img[i].red;
sum.green += img[i].green;
sum.blue += img[i].blue ;
}
sum.red = clamp(sum.red);
sum.green = clamp(sum.green);
sum.blue = clamp(sum.blue);
return sum;
}
void I_motionBlur(struct color img[], struct color img_out[],
int nb_pixels, int strength){
for (int i = 0; i < nb_pixels; ++i)
{
img_out[i] = I_average(img, nb_pixels,i,strength);
}
}
|
C
|
/*
* Rahul Gautam
* Indian Statistical Institute
* MIN-MAX heap
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#define SIZE 10000
typedef struct MINMAX
{
int *arr;
int size;
int capacity;
} MinMax;
void swap(MinMax *mm, int i, int j)
{
int t = mm->arr[i];
mm->arr[i] = mm->arr[j];
mm->arr[j] = t;
}
int parent(MinMax *mm, int i)
{
if (i <= 0)
return -1;
if (i >= mm->size)
return -1;
return (i - 1) / 2;
}
int leftChild(MinMax *mm, int i)
{
if (i < 0)
return -1;
if (i >= mm->size)
return -1;
return 2 * i + 1 > mm->size - 1 ? -1 : 2 * i + 1;
}
int rightChild(MinMax *mm, int i)
{
if (i < 0)
return -1;
if (i >= mm->size)
return -1;
return 2 * i + 2 > mm->size - 1 ? -1 : 2 * i + 2;
}
int smallestChildOrGrandChild(MinMax *mm, int n)
{
int min = mm->arr[n];
int index = n;
int l = leftChild(mm, n);
if (l != -1)
{
int ll = leftChild(mm, l);
int lr = rightChild(mm, l);
if (mm->arr[l] < min)
{
min = mm->arr[l];
index = l;
}
if (ll != -1 && mm->arr[ll] < min)
{
min = mm->arr[ll];
index = ll;
}
if (lr != -1 && mm->arr[lr] < min)
{
min = mm->arr[lr];
index = lr;
}
}
int r = rightChild(mm, n);
if (r != -1)
{
int rl = leftChild(mm, r);
int rr = rightChild(mm, r);
if (mm->arr[r] < min)
{
min = mm->arr[r];
index = r;
}
if (rl != -1 && mm->arr[rl] < min)
{
min = mm->arr[rl];
index = rl;
}
if (rr != -1 && mm->arr[rr] < min)
{
min = mm->arr[rr];
index = rr;
}
}
return index;
}
int largestChildOrGrandChild(MinMax *mm, int n)
{
int min = mm->arr[n];
int index = n;
int l = leftChild(mm, n);
if (l != -1)
{
int ll = leftChild(mm, l);
int lr = rightChild(mm, l);
if (mm->arr[l] > min)
{
min = mm->arr[l];
index = l;
}
if (ll != -1 && mm->arr[ll] > min)
{
min = mm->arr[ll];
index = ll;
}
if (lr != -1 && mm->arr[lr] > min)
{
min = mm->arr[lr];
index = lr;
}
}
int r = rightChild(mm, n);
if (r != -1)
{
int rl = leftChild(mm, r);
int rr = rightChild(mm, r);
if (mm->arr[r] > min)
{
min = mm->arr[r];
index = r;
}
if (rl != -1 && mm->arr[rl] > min)
{
min = mm->arr[rl];
index = rl;
}
if (rr != -1 && mm->arr[rr] > min)
{
min = mm->arr[rr];
index = rr;
}
}
return index;
}
int indexToLevel(int index)
{
assert(index >= 0);
return log(index + 1) / log(2);
}
void shiftDownMin(MinMax *mm, int i)
{
int m = smallestChildOrGrandChild(mm, i);
if (m != i) // i is not smallest among its childern and grandchildren
{
// if any of the children is smallest
if (m == leftChild(mm, i) || m == rightChild(mm, i))
swap(mm, i, m);
else // smallest is one of the grandchildren
{
swap(mm, i, m);
if (mm->arr[m] > mm->arr[parent(mm, m)])
swap(mm, m, parent(mm, m));
shiftDownMin(mm, m);
}
}
}
void shiftDownMax(MinMax *mm, int i)
{
int m = largestChildOrGrandChild(mm, i);
if (m != i) // i is not largest among its childern and grandchildren
{
// if any of the children is largest
if (m == leftChild(mm, i) || m == rightChild(mm, i))
swap(mm, i, m);
else // largest is one of the grandchildren
{
swap(mm, i, m);
if (mm->arr[m] < mm->arr[parent(mm, m)])
swap(mm, m, parent(mm, m));
shiftDownMax(mm, m);
}
}
}
void shiftDown(MinMax *mm, int i)
{
//assert(i>=0 && i< mm->size);
if (indexToLevel(i) % 2) // max node wala level
{
shiftDownMax(mm, i);
}
else
shiftDownMin(mm, i);
}
void bubbleUpMin(MinMax *mm, int i)
{
int g = parent(mm, parent(mm, i));
if (g != -1 && mm->arr[i] < mm->arr[g])
{
swap(mm, i, g);
bubbleUpMin(mm, g);
}
}
void bubbleUpMax(MinMax *mm, int i)
{
int g = parent(mm, parent(mm, i));
if (g != -1 && mm->arr[i] > mm->arr[g])
{
swap(mm, i, g);
bubbleUpMax(mm, g);
}
}
void bubbleUp(MinMax *mm, int i)
{
if (indexToLevel(i) % 2) // max level
{
if (parent(mm, i) != -1 &&
mm->arr[i] < mm->arr[parent(mm, i)])
{
swap(mm, i, parent(mm, i));
bubbleUpMin(mm, parent(mm, i));
}
else
bubbleUpMax(mm, i);
}
else
{
if (parent(mm, i) != -1 &&
mm->arr[i] > mm->arr[parent(mm, i)])
{
swap(mm, i, parent(mm, i));
bubbleUpMax(mm, parent(mm, i));
}
else
bubbleUpMin(mm, i);
}
}
void insert(MinMax *mm, int n)
{
assert(mm->size < mm->capacity);
mm->arr[mm->size++] = n;
bubbleUp(mm, mm->size - 1);
//printf("inseert size: %d\n",mm->size);
}
int extractMin(MinMax *mm)
{
assert(mm->size > 0);
int ret = mm->arr[0];
mm->arr[0] = mm->arr[mm->size - 1];
mm->size--;
shiftDown(mm, 0);
return ret;
}
int findKthSmallest(MinMax* mm,int k)
{
//printf("%d**\n",k);
assert(k>0 && k<=mm->size);
int* arr = (int*)malloc(k*sizeof(int));
for(int i=0;i<k;i++)
arr[i] = extractMin(mm);
for(int i=0;i<k;i++)
insert(mm,arr[i]);
return arr[k-1];
}
int main(int argc, char const *argv[])
{
MinMax mm;
mm.capacity = SIZE;
mm.size = 0;
mm.arr = (int *)malloc(mm.capacity * sizeof(int));
int t;
char temp;
do
{
scanf("%d", &t);
insert(&mm, t);
} while (getchar() != 10);
for (int i = 1; i < argc; i++)
{
int k;
sscanf(argv[i],"%d",&k);
//printf("%d",k);
if(k>0)
printf("%d ",findKthSmallest(&mm,mm.size-k+1));
else
printf("%d ",findKthSmallest(&mm,-k));
}
return 0;
}
|
C
|
#include <stdio.h>
#define ALPHABET 26
int main() {
FILE *in = fopen("task.in", "r");
FILE *out = fopen("task.out", "w");
char symbol;
int letter[ALPHABET];
int index;
for ( int i = 0; i < ALPHABET; i++ ) {
letter[i] = 0;
}
for ( ; fscanf(in, "%c", &symbol) == 1; ) {
if ( symbol >= 'A' && symbol <= 'Z' ) {
index = symbol - 'A';
letter[index] += 1;
} else if ( symbol >= 'a' && symbol <= 'z' ) {
index = symbol - 'a';
letter[index] += 1;
}
}
for ( int i = 0; i < ALPHABET; i++ ) {
if ( letter[i] != 0 ) {
fprintf(out, "%c %d\n", i+'a', letter[i]);
}
}
fclose(in);
fclose(out);
return 0;
}
|
C
|
/*
* Filename: tea.c
* Description: TEA ȣȭ
*
* Author: (aka. , Cronan), ۿ (aka. myevan, ڷ)
*/
#include "stdafx.h"
/*
* TEA Encryption Module Instruction
* Edited by aka. , Cronan
*
* void tea_code(const DWORD sz, const DWORD sy, const DWORD *key, DWORD *dest)
* void tea_decode(const DWORD sz, const DWORD sy, const DWORD *key, DWORD *dest)
* 8Ʈ ȣ/ȣȭ Ҷ ȴ. key 16 Ʈ Ѵ.
* sz, sy 8Ʈ Ѵ.
*
* int tea_decrypt(DWORD *dest, const DWORD *src, const DWORD *key, int size);
* int tea_encrypt(DWORD *dest, const DWORD *src, const DWORD *key, int size);
* Ѳ 8 Ʈ ̻ ȣ/ȣȭ Ҷ Ѵ. size
* 8 ƴϸ 8 ũ⸦ "÷" ȣȭ Ѵ.
*
* ex. tea_code(pdwSrc[1], pdwSrc[0], pdwKey, pdwDest);
* tea_decrypt(pdwDest, pdwSrc, pdwKey, nSize);
*/
#define TEA_ROUND 32 // 32 ϸ, .
#define DELTA 0x9E3779B9 // DELTA ٲ .
char tea_nilbuf[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
INLINE void tea_code(const DWORD sz, const DWORD sy, const DWORD *key, DWORD *dest)
{
DWORD y = sy, z = sz, sum = 0;
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 1
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 2
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 3
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 4
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 5
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 6
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 7
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 8
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 9
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 10
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 11
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 12
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 13
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 14
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 15
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 16
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 17
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 18
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 19
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 20
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 21
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 22
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 23
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 24
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 25
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 26
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 27
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 28
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 29
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 30
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 31
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]); // 32
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
*(dest++) = y;
*dest = z;
}
INLINE void tea_decode(const DWORD sz, const DWORD sy, const DWORD *key, DWORD *dest)
{
DWORD y = sy, z = sz, sum = DELTA * TEA_ROUND;
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 1
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 2
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 3
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 4
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 5
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 6
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 7
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 8
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 9
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 10
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 11
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 12
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 13
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 14
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 15
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 16
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 17
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 18
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 19
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 20
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 21
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 22
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 23
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 24
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 25
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 26
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 27
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 28
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 29
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 30
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 31
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]); // 32
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
*(dest++) = y;
*dest = z;
}
int TEA_Encrypt(DWORD *dest, const DWORD *src, const DWORD * key, int size)
{
int i;
int resize;
if (size % 8 != 0)
{
resize = size + 8 - (size % 8);
memset((char *) src + size, 0, resize - size);
}
else
resize = size;
for (i = 0; i < resize >> 3; i++, dest += 2, src += 2)
tea_code(*(src + 1), *src, key, dest);
return (resize);
}
int TEA_Decrypt(DWORD *dest, const DWORD *src, const DWORD * key, int size)
{
int i;
int resize;
if (size % 8 != 0)
resize = size + 8 - (size % 8);
else
resize = size;
for (i = 0; i < resize >> 3; i++, dest += 2, src += 2)
tea_decode(*(src + 1), *src, key, dest);
return (resize);
}
|
C
|
#include <pebble.h>
#include "nav_series_menu.h"
#include "dashboard.h"
#include "mstrtok.h"
static Window *mWindow;
static SimpleMenuLayer *menu_layer;
static SimpleMenuSection menu_sections[1];
static SimpleMenuItem * menu_items;
int num_a_items = 0;
void nav_series_menu_window_unload(Window *mWindow) {// Deinitialize resources on window unload that were initialized on window load
window_destroy(mWindow);
simple_menu_layer_destroy(menu_layer);
free(menu_items);
}
// You can capture when the user selects a menu icon with a menu item select callback
static void nav_series_select_callback(int index, void *ctx) {
//nav_series_menu_window_unload(mWindow);
window_stack_remove(mWindow,true);
if(index==0){
// close this, and previous two windows
}
}
// This initializes the menu upon window load
static void nav_series_menu_window_load(Window *m_window) {
num_a_items =0;
//char* new_str = malloc(sizeof(char)*strlen(seriesList)); //strlen doesn't work here dunno why.
char* new_str = malloc(sizeof(char)*1000); //because mstrtok alters its subject
strcpy(new_str,seriesList);
char * seriesOption = mstrtok (new_str, "|");
//seriesCount = 25; //DEBUG
menu_items = malloc(sizeof(SimpleMenuItem)*seriesCount);
while (seriesOption != NULL){
menu_items[num_a_items++] = (SimpleMenuItem){
.title = seriesOption,
.subtitle = "Select this ",
.callback = nav_series_select_callback,
};
seriesOption = mstrtok(NULL, "|");
}
// Bind the menu items to the corresponding menu sections
menu_sections[0] = (SimpleMenuSection){
.title = "Nav Series Menu",
.num_items = num_a_items,
.items = menu_items,
};
Layer *window_layer = window_get_root_layer(mWindow);
GRect bounds = layer_get_frame(window_layer);
menu_layer = simple_menu_layer_create(bounds, mWindow, menu_sections, 1, NULL);
layer_add_child(window_layer, simple_menu_layer_get_layer(menu_layer));
free(new_str);
free(seriesOption);
}
// show_nav_series_menu();
//if(index==1)
//show_nav_courses_menu();
void show_nav_series_menu(){
mWindow = window_create();
// Setup the window handlers
window_set_window_handlers(mWindow, (WindowHandlers) {
.load = nav_series_menu_window_load,
.unload = nav_series_menu_window_unload,
});
window_stack_push(mWindow, true /* Animated */);
}
|
C
|
int main(){
int n;
int a=0,b=0,c=0,d=0,e=0,f=0;
scanf("%d",&n);
if(n>=100){
a=(n-n%100)/100;
n=n%100;
}
if(n>=50){
b=(n-n%50)/50;
n=n%50;
}
if(n>=20){
c=(n-n%20)/20;
n=n%20;
}
if(n>=10){
d=(n-n%10)/10;
n=n%10;
}
if(n>=5){
e=(n-n%5)/5;
n=n%5;
}
f=n;
printf("%d\n%d\n%d\n%d\n%d\n%d\n",a,b,c,d,e,f);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>
#include <time.h>
const char hash_pwd1[]={"bd17a274120510b73cc32a41d1eda0fc36ed458a"};
const char hash_pwd2[]={"73b64be4d4f6d838de43460c607805141875ff43"};
const char hash_pwd3[]={"fa54a2c671b251d64060f2776072bf48590abf2e"};
const char salt1[] = {"V0aFg83KN01xCFRosTJ5"};
const char salt2[] = {"GhP49SwLN21VdeSsERt1"};
const char salt3[] = {"NQe0P3ts18bSuNdAe13v"};
void computeHash(char* pwd, const char* salt, unsigned char* buf){
int i;
char salt_pwd[100];
strcpy(salt_pwd, salt);
strcat(salt_pwd, pwd);
unsigned char temp[SHA_DIGEST_LENGTH];
memset(temp, 0x0, SHA_DIGEST_LENGTH);
SHA1((unsigned char *)salt_pwd, strlen(salt_pwd), temp);
for (i=0; i < SHA_DIGEST_LENGTH; i++) {
sprintf((char*)&(buf[i*2]), "%02x", temp[i]);
}
}
char* dictAttack(FILE *fp, const char* salt, const char* hash_pwd){
rewind(fp);
char* line = NULL;
size_t len = 0;
ssize_t read;
int i;
while ((read = getline(&line, &len, fp)) != -1) {
char buf[SHA_DIGEST_LENGTH*2];
//Trimming out the newline character
char pwd[100];
strcpy(pwd, line);
pwd[strlen(line)-2] = '\0';
computeHash(pwd, salt, buf);
if(strncmp(buf, hash_pwd, 2*SHA_DIGEST_LENGTH) == 0){
printf("Password found\n");
return line;
}
}
printf("Password not found\n");
return "";
}
int main(){
clock_t start, end;
double cpu_time_used;
FILE* fp;
fp = fopen("10kpwds.txt", "r");
if(fp == NULL){
printf("Couldn't open file, retry\n");
exit(0);
}
start = clock();
printf("The 1st password is: %s", dictAttack(fp, salt1, hash_pwd1));
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Time taken to crack the password: %f seconds\n", cpu_time_used);
start = clock();
printf("The 2nd password is: %s", dictAttack(fp, salt2, hash_pwd2));
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Time taken to crack the password: %f seconds\n", cpu_time_used);
start = clock();
printf("The 3rd password is: %s", dictAttack(fp, salt3, hash_pwd3));
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Time taken to crack the password: %f seconds\n", cpu_time_used);
}
|
C
|
#include <stdio.h>
#include "inflection.h"
#include "utils.h"
void print_app_comm_data(struct app_comm_msg* comm_data) {
printf("Size = %d | Action = %d | Data = ", comm_data->header.size, comm_data->header.action);
int i = 0;
for (; i < comm_data->header.size; i++) {
putc(comm_data->data[i], stdout);
}
putc('\n', stdout);
}
|
C
|
/*
* gcc library source for MMURTL
*/
#include <stdio.h>
#include <errno.h>
#include <mmlib.h>
/*************** fseek *****************************/
/* Set file LFA to desired position. */
int fseek(FILE *stream, long offset, int origin)
{
int erc, crnt;
if (origin==SEEK_CUR)
erc = GetFileLFA(stream->handle, &crnt);
else if (origin==SEEK_END)
{
offset = 0;
crnt = -1; /* MMURTL Seeks to EOF */
}
else if (origin==SEEK_SET)
crnt = 0;
else
return 1;
erc = SetFileLFA(stream->handle, offset+crnt);
if (erc)
return (1);
else
return (0);
}
|
C
|
#include <string.h>
int numDecodings(char *s)
{
int n[strlen(s)];
int i;
if (!s || !s[0])
return(0);
for (i = 0; s[i]; i++) {
if (i == 0) {
if (s[0] == '0')
return(0);
else
n[0] = 1;
continue;
}
if (i == 1) {
if (s[1] == '0') {
if (s[0] != '1' && s[0] != '2')
return(0);
else
n[1] = 1;
continue;
}
n[1] = n[0];
if (s[1] >= '7' && s[1] <= '9' && s[0] == '1')
n[1]++;
if (s[1] >= '1' && s[1] <= '6' && (s[0] == '1'
|| s[0] == '2'))
n[1]++;
continue;
}
if (s[i] == '0') {
if (s[i - 1] == '0' || (s[i - 1] != '1' &&
s[i - 1] != '2'))
return(0);
else
n[i] = n[i - 2];
} else {
n[i] = n[i - 1];
if (s[i] >= '7' && s[i] <= '9' && s[i - 1] == '1')
n[i] += n[i - 2];
if (s[i] >= '1' && s[i] <= '6' && (s[i - 1] == '1'
|| s[i - 1] == '2'))
n[i] += n[i - 2];
}
}
return(n[i - 1]);
}
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("%d\n", numDecodings(argv[1]));
return(0);
}
|
C
|
#include <stdio.h>
#include <immintrin.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#define SIZE 1024
double a[SIZE][SIZE];
double b[SIZE][SIZE];
void func(double *a[SIZE], double *b[SIZE], int start, int i, int j) {
if(fork() == 0) {
for (int k = 0; k < 64; k++) {
a[i][j] += b[i][k + start] + b[j][k + start];
}
exit(0);
}
}
void main(int argc, char **argv) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
b[i][j] = 20.19;
}
}
for(int j = 0; j < SIZE; j++) {
printf("fork: %d\n", j);
for(int i = 0; i < SIZE; i++) {
a[i][j] = 0;
for(int k = 0; k < 16; k++) {
func(a, b, k * 64, i, j);
}
}
}
}
|
C
|
#include "invertir_c.h"
#include "separar_canales_c.h"
#include "unir_canales_c.h"
#ifndef INVERTIR_C
#define INVERTIR_C
void invertir_c (unsigned char *src, unsigned char *dst, int h, int w, int row_size);
IplImage * aplicar_filtro_invertir_c(IplImage *src, void *param) {
IplImage *final;
final = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U, 3);
invertir_c((unsigned char*)src->imageData, (unsigned char*)(final->imageData), src->height, src->width, final->widthStep);
return final;
}
void invertir_c(unsigned char *src, unsigned char *dst, int h, int w, int row_size) {
for (int j = 0; j < h; j++) {
for (int i = 0; i < w*3; i++) {
*dst = 0xff - *src;
dst++;
src++;
}
dst += row_size - w*3;
src += row_size - w*3;
}
}
#endif
|
C
|
#include <stdio.h>
#include <ctype.h>
#include <string.h>
/* Exercise 5.6. Rewrite appropriate programs from earlier chapters and exercises
* with pointers instead of array indexing. Good possibilities include getline (Chapter 1 and 4),
* atoi, itoa, and their variants (Chapters 2, 3, and 4), reverse (Chapter 3), and strindex and
* getop (Chapter 4).
*/
#define MAXLINE 1000 /* maximum input line size */
int atoi_ptr(char *s);
int atoi_kr(char s[]);
int main()
{
int len, n;
char s[MAXLINE];
printf("Enter a string of integers \n");
scanf("%s", s);
printf("Convert to integer %d \n", atoi_ptr(s));
return 0;
}
/* atoi_ptr: pointer version of convert s to integer; version 2 */
int atoi_ptr(char *s)
{
int sign, i, n;
for ( ; isspace(*s); s++) /* skip white space */
;
sign = (*s == '-') ? -1 : 1;
if (*s == '+' || *s == '-') /* skip sign */
s++;
for (n = 0; isdigit(*s); s++)
n = 10 * n + (*s - '0');
return sign * n;
}
/* atoi_kr: convert s to integer; version 2 */
int atoi_kr(char s[])
{
int sign, i, n;
for (i = 0; isspace(s[i]); i++) /* skip white space */
;
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-') /* skip sign */
i++;
for (n = 0; isdigit(s[i]); i++)
n = 10 * n + (s[i] - '0');
return sign * n;
}
|
C
|
#include "gameControl.h"
int gameSetup(gameRoom** room, int totalRooms)
{
int maxCol, maxRow;
maxRow = 0;
maxCol = 0;
initscr(); //initalize ncurses
noecho(); //reduces characters to go on string
cbreak(); //give me input and output when it is available
curs_set(0); //remove the cursor from screen
start_color(); //starts the colour function within ncurses
/*
Pairing background and foreground colour
*/
init_pair(1, COLOR_GREEN, COLOR_BLACK);
init_pair(2, COLOR_WHITE, COLOR_BLACK);
init_pair(3, COLOR_RED, COLOR_BLACK);
init_pair(4, COLOR_BLUE, COLOR_BLACK);
init_pair(5, COLOR_CYAN, COLOR_BLACK);
init_pair(6, COLOR_MAGENTA, COLOR_BLACK);
attrset(COLOR_PAIR(2)); //display that pair of colours
getmaxyx(stdscr, maxRow, maxCol);
/*
Checks If rooms will fit on the screen
*/
for (int i = 0; i < totalRooms; ++i)
{
if ((room[i]->y + room[i]->rows + 2) > maxRow - 2 || (room[i]->x + room[i]->cols + 1) >= maxCol)
{
endwin();
printf("Game screen problem(s):\n\n");
printf(" Screen Max Row: %d\n Screen Max Cols: %d\n\nRoom number:%d\n\n", maxRow - 2,maxCol ,i + 1);
printf(" Max Row for Room: %d\n Max Col for Room: %d\n\n", room[i]->y + room[i]->rows + 2, room[i]->x + room[i]->cols + 1);
printf("**ERROR CAUSE: Either Room row > Screen row | Room col > Screen col**\n");
return 0;
}
}
return 1;
}
void gameLoop(gameRoom** room, int totalRooms, int** elementsCount, Hero* player)
{
int overStairs; //check if user is over stairs
char input; //user input
input = '?'; //user actions
overStairs = 0;
do
{
getPlayerRoom(room,player,totalRooms); //get the room, the player is in
printAllRooms(room, totalRooms, elementsCount); //print everything but hallways
printAllHallways(room, totalRooms, elementsCount); //prints hallways
if(input == 'p')
{
potionUse(player);
}
else
{
moveHero(input, player); //move hero, and checks if user presses w,a,s,d
}
if(checkChar(input ,player)) //to set if hero is going to walk on wall, and or monsters
{
action(room,elementsCount ,player, &overStairs, totalRooms, input); //hero's action based of element
}
attrset(COLOR_PAIR(1)); //display green colour
mvprintw(1, 5 ,"Hero Gold: %d", player->gold);
printStatus(player);
attrset(COLOR_PAIR(2)); //display white colour
mvaddch(player->y, player->x, '@');
if(input != '?') //to make sure this code runs AFTER user input
{
moveEnemies(room, elementsCount, player, totalRooms); //move all the enemies
printAllRooms(room, totalRooms, elementsCount); //print rooms
printStatus(player);
printAllHallways(room, totalRooms, elementsCount);
attrset(COLOR_PAIR(2)); //display white colour
mvaddch(player->y, player->x, '@');
}
if (!overStairs && player->health > 0) //if hero walks on staircase and or health is < 0:do not ask for user input
{
input = getch();
}
refresh();
clear(); //clear entire screen
} while(input != 'q' && overStairs == 0 && player->health > 0); //if user's presses 'q' and or hero's goes on stairs or health < 0
endwin(); //deinitalize ncurses
printf(" GAME OVER:\n\n");
printf(" Hero Gold: %d\n\n", player->gold);
printf(" Hero's Inventory\n ------------------\n");
for (int i = 0; i < 5; ++i)
{
if (player->ingameInventory[i].filled == 1)
{
switch(player->ingameInventory[i].type) //print all the collected items
{
case 'e':
printf(" Item Number:%d\n Type: Equipment\n Stat: %d\n\n", i + 1,player->ingameInventory[i].stat);
break;
case 'w':
printf(" Item Number:%d\n Type: Common Weapon\n Stat: %d\n\n", i + 1,player->ingameInventory[i].stat);
break;
case 'W':
printf(" Item Number:%d\n Type: Rare weapon\n Stat: %d\n\n", i + 1,player->ingameInventory[i].stat);
break;
}
}
}
if (player->inventoryCount == 0) //if no item is collected
{
printf(" No items collected\n");
}
}
void printAllRooms(gameRoom** room, int totalRooms, int** elementsCount)
{
attrset(COLOR_PAIR(5));
for (int i = 0; i < totalRooms; i = i + 1)
{
printRoom(room[i]->y,room[i]->x ,room[i]->cols,room[i]->rows);
}
attrset(COLOR_PAIR(2));
for (int i = 0; i < totalRooms; ++i)
{
for (int j = 0; j < 3; j = j + 1)
{
for (int k = 0; k < elementsCount[i][j]; ++k)
{
switch(j)
{
case 0:
attrset(COLOR_PAIR(1));
if (room[i]->gameElements->gameDoor[k]->onScreen == 1)
{
mvaddch(room[i]->gameElements->gameDoor[k]->y,room[i]->gameElements->gameDoor[k]->x,'+'); //draw doors
}
attrset(COLOR_PAIR(2));
break;
case 1:
attrset(COLOR_PAIR(3));
if (room[i]->gameElements->gameMonster[k]->onScreen == 1)
{
mvaddch(room[i]->gameElements->gameMonster[k]->y,room[i]->gameElements->gameMonster[k]->x,room[i]->gameElements->gameMonster[k]->look); //draw doors
}
attrset(COLOR_PAIR(2));
break;
case 2:
attrset(COLOR_PAIR(6));
if (room[i]->gameElements->gameItem[k]->onScreen == 1)
{
mvaddch(room[i]->gameElements->gameItem[k]->y,room[i]->gameElements->gameItem[k]->x,room[i]->gameElements->gameItem[k]->look); //draw doors
}
attrset(COLOR_PAIR(2));
break;
default:
mvaddch(0,0,' ');
}
}
}
}
}
void printRoom(int y, int x, int cols, int rows)
{
for (int i = 0; i <= cols + 1; ++i)
{
mvaddch(y - 1, x + i ,'-'); //top wall of room
mvaddch(y + rows,x + i,'-'); //bottom wall of room
}
for (int i = 0; i < rows; ++i)
{
mvaddch(y+i, x,'|'); //left wall of room
mvaddch(y+i, x + cols + 1,'|'); //right wall of room
}
for (int i = x + 1; i <= cols + x; i = i + 1)
{
for (int j = y; j < rows + y; j = j + 1)
{
attrset(COLOR_PAIR(5)); ////display cyan colour
mvaddch(j,i,'.'); //floor ties
}
}
}
|
C
|
//
// get_info.c
// pdbParse
//
// Created by mkaya on 26/07/2017.
// Copyright © 2017 mkaya. All rights reserved.
//
#include "read_file.h"
#include "get_info.h"
struct atom *getAtom(struct protein *P, char chainID, int residueID, char* atomName){
int i;
for(i = 0; i < P->size_atom; i++){
if(strcmp(P->atoms[i].name,atomName) == 0 && P->atoms[i].res->ID == residueID &&P->atoms[i].res->chn->ID == chainID){
return &P->atoms[i];
}
}
printf("The atom you are searching for is not in this protein. Please try again.");
return NULL;
}
struct residue *getResidue(struct protein *P, char chainID, int residueID){
int i;
for(i = 0; i < P->size_residue; i++){
if(P->atoms[i].res->ID == residueID &&P->atoms[i].res->chn->ID == chainID){
return &P->residues[i];
}
}
printf("The atom you are searching for is not in this protein. Please try again.");
return NULL;
}
double *getCoor(struct atom *A){
return A->coor;
};
double *getCoorOfAtom(struct protein *P, char chainID, int residueID, char* atomName){
struct atom *A =getAtom(P, chainID, residueID, atomName);
return A->coor;
}
double distanceBetweenCoor(double *firstCoor, double *secondCoor){
double xLength = firstCoor[0] - secondCoor[0];
double yLength = firstCoor[1] - secondCoor[1];
double zLength = firstCoor[2] - secondCoor[2];
return sqrt(pow(xLength,2)+pow(yLength,2)+pow(zLength,2));
}
double distanceBtwAtom (struct atom *A, struct atom *B) {
return distanceBetweenCoor(A->coor, B->coor);
}
double distanceBtwResidue(struct residue *A, struct residue *B){
double shortestDistance = 0.0;
int size_atomA = A->size_atom;
int size_atomB = B->size_atom;
struct atom *atomA, *atomB;
atomA = A->atoms;
atomB = B->atoms;
int i, j;
for (i=0; i<size_atomA; i++ ) {
for (j=0; j<size_atomB; j++ ) {
if(shortestDistance != 0.0 && distanceBtwAtom(atomA, atomB) < shortestDistance){
shortestDistance = distanceBtwAtom(atomA, atomB);
}else if(shortestDistance == 0){
shortestDistance = distanceBtwAtom(atomA, atomB);
}
atomB++;
}
atomA++;
atomB = B->atoms;
}
return shortestDistance;
}
double distanceBetweenCA(struct residue *A,struct residue *B){
int size_atomA = A->size_atom;
int size_atomB = B->size_atom;
struct atom *atomA, *atomB;
atomA = A->atoms;
atomB = B->atoms;
int i, j;
for (i=0; i<size_atomA; i++ ){
for (j=0; j<size_atomB; j++ ){
if(strcmp(atomA->name," CA ")==0 && strcmp(atomB->name," CA ")==0){
return distanceBtwAtom(atomA, atomB);
}
atomB++;
}
atomA++;
atomB = B->atoms;
}
//printf("There is no CA\n");
return 0.0;
}
void contacts(struct protein *P, double maxDist, int criteria){
int a,b,x = 0;
for(a = 0; a < P->size_residue-criteria; a++){
for(b = a + criteria; b < P->size_residue; b++){
if(distanceBtwResidue(&P->residues[a], &P->residues[b])<=maxDist){
printf("%d(%c)\t\t%d(%c)\t\t%.5lf\t\t%.5lf\n",P->residues[a].ID,P->residues[a].chn->ID,P->residues[b].ID,P->residues[b].chn->ID,distanceBtwResidue(&P->residues[a] , &P->residues[b]),distanceBetweenCA(&P->residues[a], &P->residues[b]));
x++;
}
}
}
printf("There is %d residue who interacts\n",x);
}
void contactsChain(struct chain *C, double maxDist, int criteria){
int a,b,x = 0;
struct residue *resA, *resB;
for(a = 0; a < C->size_residue-criteria; a++){
resA = C->residues + a;
for(b = a + criteria; b < C->size_residue; b++){
resB = C->residues + b;
if(distanceBtwResidue(resA, resB)<=maxDist){
printf("%d(%c)\t\t%d(%c)\t\t%.5lf\t\t%.5lf\n",resA->ID,resA->chn->ID,resB->ID,resB->chn->ID,distanceBtwResidue(resA , resB),distanceBetweenCA(resA, resB));
x++;
}
}
}
printf("There is %d residue who interacts\n",x);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_stream_reset.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: barbare <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/17 13:58:15 by barbare #+# #+# */
/* Updated: 2017/01/18 16:53:37 by barbare ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_stream.h"
#include "libft.h"
#include <stdlib.h>
/*
** ****************************************************************************
** ft_stream_reset_get
** INPUT: Struct stream
** OUTPUT: Struct stream
** Describe: reset get stream
** ****************************************************************************
*/
t_stream ft_stream_reset_get(t_stream stream)
{
if (stream.get != NULL)
free(stream.get);
stream.get = NULL;
return (stream);
}
t_stream ft_stream_reset_buffer(t_stream stream)
{
stream = ft_stream_reset_get(stream);
stream.cursor = 0;
stream.size = 0;
stream.buf[0] = '\0';
return (stream);
}
t_stream ft_stream_filter(t_stream stream,
void (*fct)(int *cursor, char *buf, int mod), int flags)
{
int i;
i = stream.cursor - 1;
if (FLAGS(flags, F_START))
while (++i < (stream.size - stream.cursor))
fct(&stream.cursor, &stream.buf[i], +1);
i = stream.size + 1;
if (FLAGS(flags, F_END))
while (--i < (stream.size - stream.cursor))
fct(&stream.size, &stream.buf[i], -1);
return (stream);
}
|
C
|
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
//follows numpy convention,
//assuming 2-dim matrix, row operations
//summarizes across all rows, (#lines == 1, #columns = original input)
//while column operations summarize across the columns (#lines == #rows, #columns == 1)
int ROW_AXIS=0;
int COL_AXIS=1;
typedef struct config_def {
int bp_col;
int chrm_col;
int start_col;
int end_col;
int base_col_start;
int axis;
char* op;
char* label;
} config_settings;
//tokenize each line to get the coordinates and the list of sample counts
//if doing a axis=COLUMN computation do it per row here
int process_line(int first, char* line, char* delim, double** vals, config_settings config_def, int print_coord)
{
char* line_copy = strdup(line);
char* tok = strtok(line_copy, delim);
int i = 0;
char* chrm;
long start, end;
int static_idx = config_def.base_col_start;
int* col_idx = &static_idx;
if(config_def.axis == ROW_AXIS)
col_idx = &i;
while(tok != NULL)
{
//if first line, only loop through to get
//count of fields, this will be used to create
//the actual storage array for the counts in a 2nd pass
//through (only this line)
if(first)
{
i++;
tok = strtok(NULL,delim);
continue;
}
if(i == config_def.chrm_col)
chrm=strdup(tok);
if(i == config_def.start_col)
start=atol(tok);
if(i == config_def.end_col)
end=atol(tok);
if(i >= config_def.base_col_start)
{
if(strcmp(config_def.op, "sum") == 0 || strcmp(config_def.op, "mean") == 0)
(*vals)[(*col_idx)-config_def.base_col_start] += atof(tok);
}
i++;
tok = strtok(NULL,delim);
}
if(!first && print_coord)
fprintf(stdout,"%s\t%lu\t%lu",chrm,start,end);
if(line_copy)
free(line_copy);
if(!first && chrm)
free(chrm);
if(line)
free(line);
return i;
}
//parameters for the program
static struct option long_opts[] =
{
//can be 0 (ROW) or 1 (COLUMN)
{"axis", required_argument, 0, 'a'},
//can be "sum" or "mean"
{"op", required_argument, 0, 'o'},
//short, descriptive name/id to be used per row or for the final single row
//(depending on axis)
{"label", required_argument, 0, 'l'},
{0,0,0,0}
};
config_settings setup(int argc, char*** argv)
{
int opt_;
int opt_idx = 0;
config_settings config_def;
config_def.chrm_col=0;
config_def.start_col=1;
config_def.end_col=2;
config_def.base_col_start=3;
config_def.axis=COL_AXIS;
config_def.op = "sum";
config_def.label = "";
opt_ = getopt_long(argc, *argv, "a:o:l:", long_opts, &opt_idx);
while(opt_ != -1)
{
switch(opt_)
{
case 'a':
config_def.axis = atoi(optarg);
break;
case 'o':
config_def.op = optarg;
break;
case 'l':
config_def.label = optarg;
break;
case '?':
break;
default:
exit(-1);
}
opt_idx = 0;
opt_ = getopt_long(argc, *argv, "a:o:l:", long_opts, &opt_idx);
}
//printf("axis: %d op: %s label: %s\n",config_def.axis,config_def.op,config_def.label);
return config_def;
}
//modified from https://stackoverflow.com/questions/3501338/c-read-file-line-by-line
int main(int argc, char** argv)
{
config_settings config_def = setup(argc, &argv);
char* line = NULL;
size_t length = 0;
ssize_t bytes_read = 0;
double* vals;
int num_vals = 0;
long num_rows = 0;
int first = 1;
bytes_read=getline(&line, &length, stdin);
//we only print coordinates if doing row-by-row (COL_AXIS) summaries
int print_coords_per_row = config_def.axis == COL_AXIS;
while(bytes_read != -1)
{
//assumes no header
num_rows++;
int num_toks = process_line(first, strdup(line), "\t", &vals, config_def, print_coords_per_row);
//if the first line, we need to know the total # of samples, so make 2 passes through the line
if(first)
{
num_vals = num_toks - config_def.base_col_start;
//one large calloc up front, this array will be resused subsequently for each line
vals = calloc(num_vals,sizeof(double));
first = 0;
num_toks = process_line(first, strdup(line), "\t", &vals, config_def, print_coords_per_row);
}
if(config_def.axis == COL_AXIS)
{
if(strcmp(config_def.op, "mean") == 0)
fprintf(stdout,"\t%.3f",vals[0]/num_vals);
else
fprintf(stdout,"\t%.0f",vals[0]);
printf("\n");
fflush(stdout);
}
//reset the value for a col computation
//no need to reset for a row computation, as we
//keep the running stat for all rows
if(config_def.axis == COL_AXIS)
vals[0] = 0.0;
bytes_read=getline(&line, &length, stdin);
}
if(config_def.axis == ROW_AXIS)
{
if(strlen(config_def.label) > 0)
fprintf(stdout,"%s",config_def.label);
int j;
for(j=0; j < num_vals; j++)
{
if(strcmp(config_def.op, "mean") == 0)
fprintf(stdout,"\t%.3f",vals[j]/num_rows);
else
fprintf(stdout,"\t%.0f",vals[j]);
}
printf("\n");
fflush(stdout);
}
if(line)
free(line);
if(vals)
free(vals);
}
|
C
|
/*
ǺȺ۵⣬ײе0ҳе25ĸȡýСֵ
ʵ2϶5࣬⼴ײ5ĸ
ps:̳ϸҳ5ĸģ20еȷ70 м30Ҳǿܳ0м䲻ܲ
ֻжٸ0
ps:ٴ֤2*5ģͣм0鲻55555555555555~ 7*8*9 = 504 *5=2520
ps:ʵͳ5ĸ0ǿɿأΪλ0Dzܽβ0еġ
Ŀǰͳ5ĸ⣬潫д
*/
#include <stdio.h>
#include <stdlib.h>
int _GetCountOf5(int n) //ͳƷ⣬ǰظͳƵ
{
int i, sum = 0;
for(i = n; i > n/2; i--)
{
if(i%5 == 0)
{
sum += i/5;
sum += _GetCountOf5(i/5);
}
}
return sum;
}
int GetCountOf5(int n)
{
int i, res = 0;
for(i = 5; i <= n; i += 5)
{
int temp = i;
while(temp%5 == 0)
{
res++;
temp /= 5;
}
}
return res;
}
int GetCountOfFive(int n)
{
int i, res = 0, maxNum = 0;
if(n < 5)
return 0;
for(i = n; i > n-5; i--)
{
if(i%5 == 0)
{
maxNum = i;
break;
}
}
res += maxNum/5;
res += GetCountOfFive(maxNum/5);
return res;
}
int main()
{
int n;
scanf("%d", &n);
printf("%d\n", GetCountOf5(n));
printf("%d\n", GetCountOfFive(n));
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "iostr.h"
#include "opstr.h"
int main(int args, char **argv){
//Var
char* inTest1;
char* inTest2;
int inTest3;
char* mainTest4;
char* catTest4;
//Test 1
printf("\x1b[31m");
printf("\nTest 1.\n");
printf("\x1b[34m");
printf("Testing iostr softenStringInput.\n");
printf("Testing opstr oplen.\n");
printf("\x1b[0m");
printf("Input a string and see its result <length><bytes><String>.\n");
printf("Type 'q' to quit:\n");
while(strcmp((inTest1 = softenStringInput()), "q") != 0){
//var
int strSize;
strSize = 0;
strSize = oplen(inTest1);
printf("<%d><%s>\n", strSize, inTest1);
free(inTest1);
}
free(inTest1);
//int input
printf("\x1b[31m");
printf("\nTest 2.\n");
printf("\x1b[34m");
printf("\x1b[34m");
printf("\nTesting iostr softenInt.\n\n");
printf("\x1b[0m");
printf("Input an int and see its result <int value>.\n");
printf("Type 'q' to quit:\n");
while(strcmp((inTest2 = softenStringInput()), "q") != 0){
//var
int intVal;
intVal = 0;
intVal = softenInt(inTest2);
printf("<%d>\n", intVal);
free(inTest2);
}
free(inTest2);
//int input
printf("\x1b[31m");
printf("\nTest 3.\n");
printf("\x1b[34m");
printf("\x1b[34m");
printf("\nTesting iostr softenIntInput.\n\n");
printf("\x1b[0m");
printf("Input an int and see its result <int value>.\n");
printf("type -66 to quit:\n");
inTest3 = 0;
for(int i = 0; inTest3 != -66; i++){
inTest3 = softenIntInput();
printf("<%d>\n", inTest3);
}
//test 5
printf("\x1b[31m");
printf("\nTest 5.\n");
printf("\x1b[34m");
printf("\x1b[34m");
printf("\nTesting iostr opcat.\n\n");
printf("\x1b[0m");
printf("Input two Strings to see concat result <final>.\n");
printf("Type 'q' to quit:\n");
while(strcmp((mainTest4 = softenStringInput()), "q") != 0){
catTest4 = softenStringInput();
opcat(&mainTest4, catTest4);
printf("<%s>\n", mainTest4);
free(mainTest4);
}
free(mainTest4);
return 0;
}
|
C
|
/*
* =====================================================================================
*
* Filename: printf.c
*
* Description:
*
* Created: 10.09.10
* Revision:
* Compiler: GCC 4.4
*
* Author: Yang Zhang, [email protected]
* Company:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#define DEC 10
#define HEX 16
int printf(const char* fmt, ...)
{
char buf[256] = { 0 };
va_list ap;
va_start(ap, fmt);
int buf_len = vsprintf(buf, fmt, ap);
//disp_int(buf_len);
//write(buf, buf_len);
if (buf_len) {
puts(buf);
}
va_end(ap);
return buf_len;
}
int vsprintf(char* buf, const char* fmt, va_list argv)
{
char fill;
char count = 0;
char align = 0;
char* p = buf;
va_list string = argv;
/* in the WHILE below, we must use p instead of buf */
while (*fmt) {
if (*fmt != '%') {
*p++ = *fmt++;
continue;
}
/*-----------------------------------------------------------------------------
* \n \t \b...
* \ and the char followed are one, so no need to case '\'
*-----------------------------------------------------------------------------*/
++fmt;
if (*fmt == '%') {
*p++ = *fmt++;
continue;
}
else if (*fmt == '0') {
fill = '0';
fmt++;
}
else {
fill = ' ';
}
while (*fmt >= '0' && *fmt <= '9') {
align *= 10;
align += (*fmt - '0');
fmt++;
}
switch (*fmt) {
case 'x':
count = i2s(p, *(int*)argv, HEX);
p += count;
__asm__ __volatile__("jmp 1f");
case 'd':
count = i2s(p, *(int*)argv, DEC);
p += count;
__asm__ __volatile__("1:");
if (align) {
if (align < count)
return -1;
char i = count;
char j = align - count;
for ( ; i; i--) {
p--;
*(p + j) = *p;
}
for ( ; j; j--) {
*p++ = fill;
}
p += count;
*p = 0;
align = 0;
}
break;
case 'c':
*p++ = *argv;
break;
case 's':
string = (char*)*(int*)argv;
while (*string) {
*p++ = *string++;
}
break;
default:
break;
}
fmt++;
argv += 4;
}
return (p - buf);
}
|
C
|
/* program to insert a new element in the given array. */
#include<stdio.h>
#define size 100
int main(){
int n, i, p, arr[size], new;
printf("Enter the size of an array : "); //Take the input from user for array size
scanf("%d", &n);
printf("\nEnter %d elements of an array : \n\n", n);
for(i=0; i<n; i++){
printf("Element - %d : ", i); //Take the elements input from user.
scanf("%d", &arr[i]);
}
/* Ask for position of new element to add. */
printf("\nEnter the location where you want to insert a new element : ");
scanf("%d", &p);
/* Take the new element from user */
printf("\nPlease enter the new value : ");
scanf("%d", &new);
for (i = n - 1; i >= p - 1; i--)
arr[i+1] = arr[i];
//assign new element value to old array.
arr[p-1] = new;
printf("\nResultant array is : ");
for (i = 0; i <= n; i++)
printf("\t%d\t", arr[i]);
return 0;
}
|
C
|
#include "vendor/unity.h"
#include "../src/sort.h"
#include <stddef.h>
#include <stdbool.h>
void setUp(void) {}
void tearDown(void) {}
bool verify_orderliness(elementType list[], size_t length, bool (*compare)(elementType a, elementType b)) {
for (size_t i = 0; i < length - 1; i++) {
if (list[i] == list[i+1])
continue;
else if (!compare(list[i], list[i+1]))
return false;
}
return true;
}
static void test_bubble_sort(void) {
elementType list[] = {10, 15, 22, 88, 70, 90, 100, 5, 9, 45, 30, 22};
size_t length = sizeof(list) / sizeof(elementType);
bubble_sort(list, length, more);
bool res = verify_orderliness(list, length, less);
TEST_ASSERT_EQUAL(true, res);
bubble_sort(list, length, less);
res = verify_orderliness(list, length, more);
TEST_ASSERT_EQUAL(true, res);
}
static void test_insertion_sort(void) {
elementType list[] = {10, 15, 22, 88, 70, 90, 100, 5, 9, 45, 30, 22};
size_t length = sizeof(list) / sizeof(elementType);
insertion_sort(list, length, less);
bool res = verify_orderliness(list, length, more);
TEST_ASSERT_EQUAL(true, res);
insertion_sort(list, length, more);
res = verify_orderliness(list, length, less);
TEST_ASSERT_EQUAL(true, res);
}
static void test_merge_sort(void) {
elementType list[] = {10, 15, 22, 88, 70, 90, 100, 5, 9, 45, 30, 22};
size_t length = sizeof(list) / sizeof(elementType);
merge_sort(list, length, less);
bool res = verify_orderliness(list, length, less);
TEST_ASSERT_EQUAL(true, res);
merge_sort(list, length, more);
res = verify_orderliness(list, length, more);
TEST_ASSERT_EQUAL(true, res);
}
int main() {
UnityBegin("test/test_sort.c");
RUN_TEST(test_bubble_sort);
RUN_TEST(test_insertion_sort);
RUN_TEST(test_merge_sort);
return UnityEnd();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int r;
srand ( time(NULL) );
r = rand() % 3;
printf("%d", r);
printf("\n\n");
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strjoin.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: wchoi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/06/08 11:29:44 by wchoi #+# #+# */
/* Updated: 2020/06/15 21:18:24 by wchoi ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
int ft_strlen(char *str)
{
int n;
n = 0;
while (str[n] != '\0')
{
n++;
}
return (n);
}
int count_len(int size, char **strs, char *sep)
{
int i;
int len;
i = 0;
len = 0;
while (i < size)
{
len += ft_strlen(strs[i]);
i++;
}
len += (ft_strlen(sep) * (size - 1));
return (len);
}
char *mk_str(char **strs, int len, int size, char *sep)
{
char *str_all;
int word;
int pos;
int j;
int k;
pos = 0;
str_all = (char*)malloc(sizeof(char) * (len + 1));
if (!str_all)
return (0);
str_all[len] = '\0';
word = 0;
while (word < size)
{
j = 0;
while (strs[word][j] != '\0')
str_all[pos++] = strs[word][j++];
k = 0;
while (k < ft_strlen(sep) && (word < size - 1))
str_all[pos++] = sep[k++];
word++;
}
return (str_all);
}
char *ft_strjoin(int size, char **strs, char *sep)
{
int len;
if (size == 0)
return ((char*)malloc(sizeof(char)));
len = count_len(size, strs, sep);
return (mk_str(strs, len, size, sep));
}
|
C
|
#include<stdio.h>
void convert(int n) {
int ans[100],i=0;
while(n) {
ans[i]=n%16;
i++;
n=n/16;
}
printf("\nHexadecimal number : ");
for(int j=i-1;j>=0;j--){
printf("%X",ans[j]);
}
}
void main() {
int num;
printf("\nDecimal to hexadecimal : \n");
printf("\nEnter a number : ");
scanf("%d",&num);
convert(num);
printf("\n");
}
/*
Output :
*/
|
C
|
#include <stdio.h>
// ĺ ҹ ȯ
// a(97) - A(65) 32 ϰ ҹڸ ȯ ϴ.
int main(void)
{
char small;
char cap = 'G'; // char ʱȭ
if ((cap >= 'A') && (cap <= 'Z')) // ڿ 빮ڹ(ƽŰڵ尪 A(65) ~ Z(90) ̶)
{
small = cap + ('a' - 'A'); // /ҹ ̸ ҹڷ ȯ
// (cap ƽŰڵ尪) + (a(97) - A(65)) 32 .
}
printf("빮 : %c %c", cap, '\n'); // '\n' %c ϸ ٲ.
printf("ҹ : %c", small);
return 0;
}
|
C
|
//
// Created by Arthur.BOURGUE on 05.04.2019.
//
//====================================================================
//Titre: Sous programme "Maquette2"
//auteur: Arthur Bourgue
//But: Fonctionnement complet de la 1re maquette
//====================================================================
#ifndef BATNAV_MAQUETTE2_H
#define BATNAV_MAQUETTE2_H
#endif //BATNAV_MAQUETTE2_H
#define PETIT_BATEAU 1
#define MOYEN_BATEAU1 2
#define MOYEN_BATEAU2 21
#define GRAND_BATEAU 3
#define ENORME_BATEAU 4
char tableauVisu2[9][9] = { //Tout idem que pour maquette1//
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
};
int Maquette2(int col,int lig)
{
lig = lig - 1;
col = col - 1;
int tableauJoueur[9][9] = {
0, 0, 0, 0, 0, 0, 0, 21, 0,
0, 0, 0, 0, 0, 0, 0, 21, 0,
1, 0, 0, 0, 0, 0, 0, 21, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 0, 3, 3, 3, 3, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 2, 2, 2, 0, 0, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
};
if (tableauJoueur[col][lig] == PETIT_BATEAU || tableauJoueur[col][lig] == MOYEN_BATEAU1 ||
tableauJoueur[col][lig] == MOYEN_BATEAU2 || tableauJoueur[col][lig] == GRAND_BATEAU ||
tableauJoueur[col][lig] == ENORME_BATEAU) {
tableauVisu2[col][lig] = 1;
printf("touché!\n");
} else {
tableauVisu2[col][lig] = 3;
printf("loupé\n\n");
}
if(tableauVisu2[3][1] == 1 && tableauVisu2[4][1] == 1){
printf("Coulé");
}
int ligne = 0;
int colonne = 0;
for (ligne = 0; ligne < 9; ligne++) {
for (colonne = 0; colonne < 9; colonne++) {
printf("%d \t", tableauVisu2[ligne][colonne]);
}
printf("\n");
}
}
int HPPbateau2(int col,int lig){
col = col - 1;
lig = lig - 1;
int tableauJoueur[9][9] = {
0, 0, 0, 0, 0, 0, 0, 21, 0,
0, 0, 0, 0, 0, 0, 0, 21, 0,
1, 0, 0, 0, 0, 0, 0, 21, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 0, 3, 3, 3, 3, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 2, 2, 2, 0, 0, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
};
int petitBateau = 0;
if(tableauJoueur[col][lig] == PETIT_BATEAU){
petitBateau = petitBateau + 1;
}
return petitBateau;
}
int HPMbateau2(int col,int lig) {
col = col - 1;
lig = lig - 1;
int tableauJoueur[9][9] = {
0, 0, 0, 0, 0, 0, 0, 21, 0,
0, 0, 0, 0, 0, 0, 0, 21, 0,
1, 0, 0, 0, 0, 0, 0, 21, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 0, 3, 3, 3, 3, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 2, 2, 2, 0, 0, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
};
int moyenBateau = 0;
if (tableauJoueur[col][lig] == MOYEN_BATEAU1) {
moyenBateau = moyenBateau + 1;
}
return moyenBateau;
}
int HPM2bateau2(int col,int lig) {
col = col - 1;
lig = lig - 1;
int tableauJoueur[9][9] = {
0, 0, 0, 0, 0, 0, 0, 21, 0,
0, 0, 0, 0, 0, 0, 0, 21, 0,
1, 0, 0, 0, 0, 0, 0, 21, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 0, 3, 3, 3, 3, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 2, 2, 2, 0, 0, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
};
int moyenBateau2 = 0;
if (tableauJoueur[col][lig] == MOYEN_BATEAU2) {
moyenBateau2 = moyenBateau2 + 1;
}
return moyenBateau2;
}
int HPGbateau2(int col,int lig) {
col = col - 1;
lig = lig - 1;
int tableauJoueur[9][9] = {
0, 0, 0, 0, 0, 0, 0, 21, 0,
0, 0, 0, 0, 0, 0, 0, 21, 0,
1, 0, 0, 0, 0, 0, 0, 21, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 0, 3, 3, 3, 3, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 2, 2, 2, 0, 0, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
};
int grandBateau = 0;
if (tableauJoueur[col][lig] == GRAND_BATEAU) {
grandBateau = grandBateau + 1;
}
return grandBateau;
}
int HPEbateau2(int col,int lig) {
col = col - 1;
lig = lig - 1;
int tableauJoueur[9][9] = {
0, 0, 0, 0, 0, 0, 0, 21, 0,
0, 0, 0, 0, 0, 0, 0, 21, 0,
1, 0, 0, 0, 0, 0, 0, 21, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 0, 3, 3, 3, 3, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 2, 2, 2, 0, 0, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
};
int enormeBateau = 0;
if (tableauJoueur[col][lig] == ENORME_BATEAU) {
enormeBateau = enormeBateau + 1;
}
return enormeBateau;
}
int hpPartie2(int col,int lig){
col = col - 1;
lig = lig - 1;
int tableauJoueur[9][9] = {
0, 0, 0, 0, 0, 0, 0, 21, 0,
0, 0, 0, 0, 0, 0, 0, 21, 0,
1, 0, 0, 0, 0, 0, 0, 21, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 0, 3, 3, 3, 3, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 2, 2, 2, 0, 0, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 4, 0,
};
int hpRestant = 0;
if(tableauJoueur[col][lig] == PETIT_BATEAU){
hpRestant = hpRestant + PETIT_BATEAU;
}else if (tableauJoueur[col][lig] == MOYEN_BATEAU1){
hpRestant = hpRestant + MOYEN_BATEAU1;
}else if(tableauJoueur[col][lig] == MOYEN_BATEAU2){
hpRestant = hpRestant + MOYEN_BATEAU2;
}else if(tableauJoueur[col][lig] == GRAND_BATEAU){
hpRestant = hpRestant + GRAND_BATEAU;
}else if(tableauJoueur[col][lig] == ENORME_BATEAU){
hpRestant = hpRestant + ENORME_BATEAU;
}
return hpRestant;
}
|
C
|
#include "led.h"
#include "uart.h"
#include "stdio.h"
void handler(void)
{
uart_putchar('1');
printf("handler!\n");
return;
}
int mymain(void)
{
char buf[10];
int cpsr;
led_init();
led_on();
// uart_init();
//
cpsr = get_cpsr();
printf("cpsr = %x \n", cpsr);
printf("hello, printf demo\n");
printf("test int 100 = %d \n", 100);
printf("test hex 100 = 0x%x \n", 100);
printf("test char 0x31 = %c \n", 0x31);
printf("test str = %s \n", "bye");
#define PREG(x) printf(#x"= 0x%x \n", *(volatile int *)x )
PREG(0xE8000000);
PREG(0xE8000004);
PREG(0xE8000008);
PREG(0xE800000c);
PREG(0xE8000010);
PREG(0xE8000014);
PREG(0xE8000018);
*(int *)0xe8000000 = 0x31;
PREG(0xE8000000);
dm_init();
dm_read_id(buf);
printf("DM9000 id is %x %x %x %x \n", buf[0], buf[1], buf[2], buf[3]);
delay(5000000);
while (1)
{
printf("send arp ...\n");
dm_send_arp();
printf("recv arp ...\n");
dm_recv_arp();
delay(1000000);
}
return 0;
}
|
C
|
#include <stdio.h>
void pointerInc(int *p1,int *p2){
printf("The address of p1 is %p\n",&p1);
printf("The value of p1 is %p\n",p1);
printf("The address of p2 is %p\n",&p1);
printf("The value of p2 is %p\n",p2);
*p1+=1;
p1=p2;
*p1+=2;
}
int main(){
int i,j,*iptr=&i;
scanf("%d%d",&i,&j);
printf("The address of i is %p\n",&i);
printf("The address of j is %p\n",&j);
printf("The address of iptr is %p\n",&iptr);
printf("i=%d , j=%d\n",i,j);
pointerInc(iptr,&j);
printf("i=%d , j=%d\n",i,j);
*iptr+=5;
printf("i=%d , j=%d\n",i,j);
return 0;
}
|
C
|
/*
** bot_attacks.c for in /home/robin/delivery/CPE/CPE_2016_matchstick
**
** Made by Robin Pronnier
** Login <[email protected]>
**
** Started on Sat Jun 10 21:30:26 2017 Robin Pronnier
** Last update Sat Jun 10 22:00:22 2017 Robin Pronnier
*/
#include <stdlib.h>
#include "my.h"
int find_line_atk(char **map, int max_sticks)
{
int i;
int stick;
int sticks;
int stock_i;
i = 0;
stick = 0;
sticks = 0;
while (map[++i + 1] != NULL)
{
if (strlenstick(map[i]) == 1)
++stick;
else if (strlenstick(map[i]) > 1)
{
++sticks;
stock_i = i;
}
}
if (sticks == 1 && (stick % 2 == 1) &&
strlenstick(map[stock_i]) <= max_sticks)
return (print_bot_attack(map, stock_i, strlenstick(map[stock_i])));
else if (sticks == 1 && (stick % 2 == 0) &&
strlenstick(map[stock_i]) - 1 <= max_sticks)
return (print_bot_attack(map, stock_i, strlenstick(map[stock_i]) - 1));
return (1);
}
int pick_one_stick(char **map, int c)
{
int i;
i = 1;
while (i <= c)
{
if (strlenstick(map[i]) != 0)
return (i);
++i;
}
return (0);
}
|
C
|
// save.c
inherit F_CLEAN_UP;
int main(object me, string arg)
{
object link_ob;
seteuid(getuid());
if( !objectp(link_ob = me->query_temp("link_ob")) )
return notify_fail("你不是经由正常连线进入,不能储存。\n");
if( environment(me)->query("valid_startroom") ) {
me->set("startroom", base_name(environment(me)));
write("当你下次连线进来时,会从这里开始。\n");
}
if((time() - (int)me->query_temp("save")) < 60 )
return notify_fail("刚刚才储存了一次,那么快又要储存了?\n");
if(link_ob->save() && me->save()) {
me->set_temp("save",time());
write("档案储存完毕。\n");
return 1;
} else {
write("储存失败。\n");
return 0;
}
}
int help(object me)
{
write(@HELP
指令格式:save
把你辛苦奋斗的结果存起来,下次上线,你将会出现在上次储存的地方。
相关讯息:quit
HELP
);
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char UserInput[256];
// Find area of the floor
int AreaOfFloor(int length_floor, int width_floor)
{
printf("Please input the Length of the floor: \n");
if (fgets(UserInput, sizeof(UserInput), stdin)) {
if (1 == sscanf(UserInput, "%d\n", &length_floor)) {
}
}
printf("Please input the width of the floor: \n");
if (fgets(UserInput, sizeof(UserInput) , stdin)) {
if (1 == sscanf(UserInput, "%d\n", &width_floor)) {
}
}
//calculate the area of the floor
return length_floor * width_floor;
}
//Cost per tile
int CostPerTile(int cost_per_unit)
{
//Input for cost per tile
printf("Please input the cost per tile: \n");
if (fgets(UserInput, sizeof(UserInput), stdin)) {
if (1 == sscanf(UserInput, "%d\n", &cost_per_unit)) {
}
}
return cost_per_unit;
}
int main(int argc, char *argv[])
{
int length_floor;
int width_floor;
int cost_per_unit;
int CostOfFloor;
// calcualte the cost of the floor
int Area_of_floor = AreaOfFloor(length_floor, width_floor);
int Cost_per_Tile = CostPerTile(cost_per_unit);
CostOfFloor = Area_of_floor * Cost_per_Tile;
//display cost of the floor
printf("The Cost of The Floor is : $%d\n", CostOfFloor);
return 0;
}
|
C
|
/****************************************************************************
**
** Copyright (C) 2010 Agile Genomics, LLC
** All rights reserved.
** Primary author: Luke Ulrich
**
****************************************************************************/
#ifndef PARSEDBIOSTRING_H
#define PARSEDBIOSTRING_H
#include "BioString.h"
/**
* ParsedBioString associates several pieces of information common to a BioString that has been parsed
* and while it may be used elsewhere, it's primary function is for importing sequence data.
*
* Generally speaking, ParsedBioString is a glorified SimpleSeq that additionally contains valid and
* checked flags, which denote whether it is valid and/or selected, respectively.
*/
struct ParsedBioString
{
BioString bioString_; //!< Parsed bioString
QString header_; //!< Arbitrary header data
bool valid_; //!< Flag denoting if this sequence is valid
bool checked_; //!< Flag denoting if user has selected this sequence
/**
* Constructs a a ParsedBioString with bioString, header, valid, and checked status
*/
ParsedBioString(const BioString &bioString, const QString &header = QString(), bool valid = false, bool checked = false) :
bioString_(bioString), header_(header), valid_(valid), checked_(checked)
{}
};
#endif // PARSEDBIOSTRING_H
|
C
|
#include "io.h"
#include <pthread.h>
#include <stdio.h>
#include <sys/select.h>
#include <sys/time.h>
#include <termios.h>
#include "functions.h"
#define INPUT_BUFFER_SIZE 1024
pthread_t read_thread;
struct termios tty_restore;
char input_buffer[1024];
int16_t next_read = 0;
int16_t next_write = 0;
void * read_thread_func(void *unused) {
int read;
for (;;) {
if ((read = fgetc(stdin)) != EOF) {
input_buffer[next_write++] = read;
if (next_write >= INPUT_BUFFER_SIZE) {
next_write = 0;
}
if (next_write == next_read) {
printf("WARNING: input coming in too fast, "
"input buffer is about to be overwritten.\n");
}
} else {
break;
}
}
return NULL;
}
void init_io() {
struct termios tty_state;
tcgetattr(fileno(stdin), &tty_restore);
tcgetattr(fileno(stdin), &tty_state);
tty_state.c_lflag &= ~(ICANON | ECHO);
tty_state.c_cc[VMIN] = 1;
tcsetattr(fileno(stdin), TCSANOW, &tty_state);
pthread_create(&read_thread, NULL, read_thread_func, NULL);
}
void finish_io() {
tcsetattr(fileno(stdin), TCSANOW, &tty_restore);
}
void handle_io(cpu *m) {
if (next_read != next_write) {
m->interrupt_waiting = 0x01;
m->mem[IO_GETCHAR] = input_buffer[next_read++];
if (next_read >= INPUT_BUFFER_SIZE) {
next_read = 0;
}
}
if (get_emu_flag(m, EMU_FLAG_DIRTY)) {
if (m->dirty_mem_addr == IO_PUTCHAR) {
uint8_t val = m->mem[m->dirty_mem_addr];
putchar(val);
fflush(stdout);
}
}
}
|
C
|
#include <ncurses.h>
#define hello_str "Hello, world!"
void get_inch(char *str)
{
int x = 0;
for (; x != sizeof(hello_str) - 1; ++x)
str[x] = mvinch(0, x);
str[x] = '\0';
}
void print_inch()
{
char str[sizeof(hello_str)];
get_inch(str);
addstr(str);
}
int main()
{
initscr();
addstr(hello_str);
getch();
print_inch();
getch();
endwin();
return 0;
}
|
C
|
/* James Snee s3369721 Algorithms and Analysis */
/* Summer 2015 Assignment 2 - Code */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stack.h"
/*The program accepts one command line argument: a user input string. If no*/
/*user input is specified, the program will use the sample input provided*/
/*PLEASE NOTE: due to a bash feature, if entering brackets as a command line*/
/*argument, they need to be preceeded by a forward slash (\) or enclosed in a quote (') */
int main (int argc, char *argv[]){
stack_s stack;
int i, open = 0, close = 0;
/*sample input*/
char *input;
/*check command line args*/
if (argc != 2){
printf("No user input detected, using example input.\n");
input = "((a) + (b)) + ((c)(a))";
}
else {
printf("User input detected.\n");
input = argv[1];
}
stack_init(&stack, INITIAL_STACK_SIZE);
printf("Input String: %s\n", input);
for (i = 0; i < strlen(input); i++){
/*check for open brackets. If it is one, push to stack.
If it is closed, pop from stack.*/
if (input[i] == '('){
open++;
printf("Pushing ( to stack.\n");
stack_push(&stack, '(');
}
else if (input[i] == ')'){
close++;
printf("Popping ) from stack.\n");
stack_pop(&stack);
}
}
printf("Number of open brackets: %i. Number of close brackets: %i.\n", open, close);
if (open == close){
printf("Matching brackets.\n");
}else {
printf("Non matching brackets.\n");
}
stack_free(&stack);
exit(EXIT_SUCCESS);
}
|
C
|
#include<stdio.h>
#include<string.h>
char str[200], temp[30];
/*void checkvalid(char temp[30])
{
int i, flag1= 0, flag2= 0, flag3= 0, flag4=0;
if(strlen(temp)>=6 && strlen(temp)<=15)
{
for(i=0; temp[i]!='\0'; i++)
{
if(temp[i]>='a' && temp[i]<='z')
flag1= 1;
if(temp[i]>='A' && temp[i]<='Z')
flag2= 1;
if(temp[i]>='0' && temp[i]<='9')
flag3= 1;
if(temp[i]=='$' || temp[i]=='#' || temp[i]=='@' || temp[i]=='*' || temp[i]=='!')
flag4= 1;
}
if(flag1==1 && flag2==1 && flag3==1 && flag4==1)
{
printf("%s,", temp);
}
}
}*/
void main()
{
char str[100], temp[100];
for(int i=0; str[i]!='\0'; i++)
{
temp[i] = str[i];
}
puts(temp);
}
|
C
|
/*Program : MenukarDuaAngka.c
* Deskripsi : menukar nilai dari dua angka pada suatu variabel
* Nama : Muhammad Azhar Alauddin
* tanggal/ versi : 31 Januari 2020
*/
#include <stdio.h>
void swapValue(int *value1, int *value2){
int temp;
temp=*value1;
*value1=*value2;
*value2=temp;
}
int main ()
{
int number1,number2;
scanf("%d %d",&number1,&number2);
swapValue(&number1,&number2);
printf("%d %d",number1,number2);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* select_mode.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dquartin <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/12/15 09:23:38 by dquartin #+# #+# */
/* Updated: 2018/02/28 15:59:07 by dquartin ### ########.fr */
/* */
/* ************************************************************************** */
#include "../shell.h"
static char *create_stock(char *line)
{
char *stock;
int j;
j = 0;
stock = ft_strdup(line);
while (stock[j])
{
stock[j] = '\0';
j++;
}
return (stock);
}
static void quit_mode(char *stock, t_index **index)
{
struct winsize size;
ioctl(0, TIOCGWINSZ, &size);
GO("ei");
ft_strdel(&stock);
home(index, size);
(*index)->x = (int)ft_strlen((*index)->line);
ft_putstrin((*index)->line);
(*index)->i = (*index)->x;
GO("im");
}
static void select_right(char *stock, t_index **index)
{
struct winsize size;
char *tmp;
ioctl(0, TIOCGWINSZ, &size);
tmp = ft_getenv((*index)->environ, "PROMPT");
(*index)->prompt = ft_atoi(tmp);
ft_strdel(&tmp);
if ((*index)->i < (*index)->x)
{
go_to_right(index, size);
copy_char(index, &stock);
}
}
static void select_left(char *stock, t_index **index)
{
if ((*index)->i > 0)
{
copy_char(index, &stock);
(*index)->i = go_to_left((*index)->i);
}
}
void select_mode(t_index **index)
{
char buff[6];
char *stock;
char *tmp;
int total;
stock = NULL;
tmp = ft_getenv((*index)->environ, "PROMPT");
(*index)->prompt = ft_atoi(tmp);
ft_strdel(&tmp);
stock = create_stock((*index)->line);
while (1)
{
ft_bzero(buff, 6);
read(0, buff, 6);
total = buff[0] + buff[1] + buff[2] + buff[3] + buff[4] + buff[5];
if (total == ALT_S)
return (quit_mode(stock, index));
else if (total == RIGHT_ARROW)
select_right(stock, index);
else if (total == LEFT_ARROW)
select_left(stock, index);
if (total == ALT_C)
copy_select(stock, index);
}
}
|
C
|
/*
* togo_hashtable.c
*
* Created on: 2015-6-24
* Author: zhuli
*/
#include "togo.h"
#include "togo_load.h"
static uint32_t togo_hashtable_bucket(const TOGO_HASHTABLE * hashtable,
u_char *key, size_t len);
static void togo_hashtable_lock(const TOGO_HASHTABLE * hashtable,
uint32_t current_bucket);
static void togo_hashtable_unlock(const TOGO_HASHTABLE * hashtable,
uint32_t current_bucket);
TOGO_HASHTABLE * togo_hashtable_init(TOGO_POOL * pool)
{
uint32_t i;
TOGO_HASHTABLE_BUCKET * bucket = togo_pool_calloc(pool,
sizeof(TOGO_HASHTABLE_BUCKET) * TOGO_HASHTABLE_BUCKET_NUM);
if (bucket == NULL) {
togo_log(ERROR, "malloc TOGO_HASHTABLE_BUCKET fail");
togo_exit();
}
TOGO_HASHTABLE *hashtable = togo_pool_calloc(pool, sizeof(TOGO_HASHTABLE));
if (hashtable == NULL) {
togo_log(ERROR, "malloc TOGO_HASHTABLE fail");
togo_exit();
}
/* Init Hashtable lock */
uint32_t lock_num = TOGO_HASHTABLE_BUCKET_NUM / TOGO_HASHTABLE_LOCK_SIZE;
pthread_mutex_t * lock = togo_pool_calloc(pool,
sizeof(pthread_mutex_t) * lock_num);
if (lock == NULL) {
togo_log(ERROR, "malloc TOGO_HASHTABLE_BUCKET lock fail");
togo_exit();
}
for (i = 0; i < lock_num; i++) {
pthread_mutex_init((lock + i), NULL);
}
pthread_mutex_init(&hashtable->global_lock, NULL);
hashtable->pool = pool;
hashtable->lock = lock;
hashtable->bucket = bucket;
hashtable->total_get = 0;
hashtable->total_remove = 0;
hashtable->total_size = 0;
hashtable->total_bucket = TOGO_HASHTABLE_BUCKET_NUM; //default 1024
return hashtable;
}
BOOL togo_hashtable_add(const TOGO_HASHTABLE * hashtable, u_char *key, void * p)
{
size_t len = strlen(key);
uint32_t current_bucket = togo_hashtable_bucket(hashtable, key, len);
TOGO_HASHTABLE_BUCKET * bucket = (hashtable->bucket + current_bucket);
TOGO_POOL * pool = hashtable->pool;
TOGO_HASHTABLE_ITEM * item = togo_pool_calloc(pool,
sizeof(TOGO_HASHTABLE_ITEM));
if (item == NULL) {
togo_log(INFO, "Malloc TOGO_HASHTABLE_ITEM Fail");
return FALSE;
}
togo_hashtable_lock(hashtable, current_bucket);
item->key = key;
item->key_len = len;
item->p = p;
item->next = bucket->item;
bucket->item = item;
bucket->size++;
togo_hashtable_unlock(hashtable, current_bucket);
return TRUE;
}
BOOL togo_hashtable_remove(const TOGO_HASHTABLE * hashtable, u_char *key)
{
int len = strlen(key);
uint32_t current_bucket = togo_hashtable_bucket(hashtable, key, len);
TOGO_HASHTABLE_BUCKET * bucket = (hashtable->bucket + current_bucket);
togo_hashtable_lock(hashtable, current_bucket);
TOGO_HASHTABLE_ITEM * item = bucket->item;
TOGO_HASHTABLE_ITEM * pre = NULL;
while (item != NULL) {
if (len == item->key_len && strncmp(item->key, key, len) == 0) {
if (pre == NULL) {
bucket->item = item->next;
} else {
pre->next = item->next;
}
togo_pool_free_data(hashtable->pool, item);
bucket->size--;
break;
}
pre = item;
item = item->next;
}
togo_hashtable_unlock(hashtable, current_bucket);
return TRUE;
}
TOGO_HASHTABLE_ITEM * togo_hashtable_get(const TOGO_HASHTABLE * hashtable,
u_char *key)
{
int len = strlen(key);
uint32_t current_bucket = togo_hashtable_bucket(hashtable, key, len);
TOGO_HASHTABLE_BUCKET * bucket = (hashtable->bucket + current_bucket);
TOGO_HASHTABLE_ITEM * item = bucket->item;
TOGO_HASHTABLE_ITEM * current = NULL;
while (item != NULL) {
if (strcmp(item->key, key) == 0) {
current = item;
break;
}
item = item->next;
}
return current;
}
BOOL togo_hashtable_flush(TOGO_HASHTABLE * hashtable)
{
pthread_mutex_t global_lock = hashtable->global_lock;
pthread_mutex_lock(&global_lock); //lock
uint32_t i;
TOGO_HASHTABLE_BUCKET * bucket = hashtable->bucket;
for (i = 0; i < TOGO_HASHTABLE_BUCKET_NUM; i++) {
while (bucket->item != NULL) {
TOGO_HASHTABLE_ITEM * item = bucket->item;
bucket->item = bucket->item->next;
free(item);
}
bucket->size = 0;
bucket = bucket++;
}
hashtable->total_get = 0;
hashtable->total_remove = 0;
hashtable->total_size = 0;
pthread_mutex_unlock(&global_lock); //unlock
return TRUE;
}
static void togo_hashtable_lock(const TOGO_HASHTABLE * hashtable,
uint32_t current_bucket)
{
uint32_t x =
togo_hashtable_get_lock(current_bucket, TOGO_HASHTABLE_LOCK_SIZE);
pthread_mutex_t * lock = hashtable->lock;
pthread_mutex_lock((lock + x)); //lock
}
static void togo_hashtable_unlock(const TOGO_HASHTABLE * hashtable,
uint32_t current_bucket)
{
uint32_t x =
togo_hashtable_get_lock(current_bucket, TOGO_HASHTABLE_LOCK_SIZE);
pthread_mutex_t * lock = hashtable->lock;
pthread_mutex_unlock((lock + x)); //unlock
}
static uint32_t togo_hashtable_bucket(const TOGO_HASHTABLE * hashtable,
u_char *key, size_t len)
{
int code = togo_djb_hash(key);
uint32_t total_bucke = hashtable->total_bucket;
uint32_t bucket_len = abs(code % total_bucke);
return bucket_len;
}
|
C
|
/*===============================================================
* Copyright (C) 2020 All rights reserved.
*
* 文件名称:daily5_homework4.c
* 创 建 者: dwl
* 创建日期:2020/08/17
* 描 述:
*
* 更新日志:
*
================================================================*/
#include <stdio.h>
int main()
{
int Num, bit, bit_count;
int Sum=0, count;
int mul;
printf("Please input the Num:");
scanf("%d", &Num);
printf("Please input the lenght:");
scanf("%d", &bit);
for(; bit > 0; bit--)
{
if(1 == bit_count)
Sum += Num;
else
{
for(bit_count = bit; bit_count>=1; bit_count--)
{
for(mul = Num, count = 1; count < bit_count; count++)
{
mul *= 10;
printf("mul = %d\n", mul);
}
Sum += mul;
}
}
}
printf("总数是%d\n", Sum);
return 0;
}
|
C
|
int main ()
{ int a,b,c,d,e,f,s[1000],i;
for(i=0;a!=0;i++){
scanf("%d%d%d%d%d%d",&a,&b,&c,&d,&e,&f);
s[i]=f+60*e+3600*d-c-60*b-3600*a+3600*12;
if(a!=0){printf("%d\n",s[i]);}
}
return 0;
}
|
C
|
/* just a hack for testsuites, do not use for security purposes. */
#include <stdlib.h>
#include <limits.h>
static unsigned int rseed;
int rand_r(unsigned int *seedp)
{
unsigned int rnd;
/* Lower 16bits. */
*seedp = *seedp * 1103515245 + 12345;
rnd = *seedp;
rnd >>= 16;
/* Upper 16bits. */
*seedp = *seedp * 1103515245 + 12345;
rnd |= (*seedp >> 16) << 16;
rnd &= RAND_MAX;
return rnd;
}
int rand(void)
{
return rand_r(&rseed);
}
void srand(unsigned int seed)
{
rseed = seed;
}
|
C
|
#include <stdio.h>
#include <stdint.h>
/*
1. https://graphics.stanford.edu/~seander/bithacks.html
2. Hacker's Delight 2nd Edition, Chapter 5. Counting Bits
*/
void print_bits(uint32_t n) {
int i = 32;
while(i--){
if ((n >> i) & 1)
printf("1");
else
printf("0");
}
printf("\n");
}
/* O(logn) */
int hammingWeight_1(uint32_t n) {
int ret = 0;
while (n) {
ret += n & 0x01;
n >>= 1;
}
return ret;
}
/* O(m) */
int hammingWeight_2(uint32_t n) {
int ret = 0;
while (n) {
n = n & (n - 1);
ret ++;
}
return ret;
}
/*****************************
Code to count 0 bits
while (n != 0xFFFFFFFF) {
n = n | (n + 1);
ret++;
}
Or,
n = ~n;
count1Bits(n);
******************************/
/* 5 steps */
int hammingWeight_3(uint32_t n) {
uint32_t t = n;
/* add up odd and even bits 1 bit */
t = ((t & 0xAAAAAAAA) >> 1) + (t & 0x55555555);
/* 2 bits */
t = ((t & 0xCCCCCCCC) >> 2) + (t & 0x33333333);
/* 4 bits */
t = ((t & 0xF0F0F0F0) >> 4) + (t & 0x0F0F0F0F);
/* 8 bits */
t = ((t & 0xFF00FF00) >> 8) + (t & 0x00FF00FF);
/* 16 bits */
t = ((t & 0xFFFF0000) >> 16) + (t & 0x0000FFFF);
return t;
}
/* simplification of hammingWeight_3 */
int hammingWeight_4(uint32_t n) {
n = n - ((n >> 1) & 0x55555555);
n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
n = (n + (n >> 4)) & 0x0F0F0F0F;
n = n + (n >> 8);
n = n + (n >> 16);
return n & 0x0000003F;
}
/* HAKMEM */
int hammingWeight_5(uint32_t n) {
uint32_t t;
t = (n >> 1) & 033333333333; // Count bits in
n = n - t; // each 3-bit
t = (t >> 1) & 033333333333; // field.
n = n - t;
n = (n + (n >> 3)) & 030707070707;
return n % 63; // Add 6-bit sums.
//((n * 0404040404) >> 26) + (n >> 30)
}
/* variation of HAKMEM */
int hammingWeight(uint32_t n) {
uint32_t t;
t = (n >> 1) & 0x77777777; // Count bits in
n = n - t; // each 4-bit
t = (t >> 1) & 0x77777777; // field.
n = n - t;
t = (t >> 1) & 0x77777777;
n = n - t;
n = (n + (n >> 4)) & 0x0F0F0F0F; // Get byte sums.
n = n * 0x01010101; // Add the bytes.
return n >> 24;
}
int main() {
uint32_t n = 11;
printf("%d\n", hammingWeight(n));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "utils.h"
#include "../shared/typedefs.h"
/*
shortArrToDouble takes in a short array,
a size of the array in BYTES, and whether the program is in debug mode or not.
the function will allocate enough space for a double array with the same number
of elements as the double array (size * 2) and copy the elements over to the
new array.
*/
double* shortArrToDouble(short* arr, unsigned int size, BOOL debug){
//short has 2 bytes, double has 8, must allocated 8/2= 4x the number of bytes
//Also ensure that the bytes allocated for double array are 8 aligned
int extraBytes = BYTES_DOUBLE / BYTES_SHORT;
int doublePad = size % BYTES_DOUBLE;
int requiredBytes = (size + doublePad) * extraBytes;
double *toReturn = malloc(requiredBytes);
int i;
//size is in bytes, short is 2 bytes long - must divide by 2
for(i = 0; i < (size / BYTES_SHORT); i++){
toReturn[i] = (double)arr[i];
}
if(debug == FALSE){
free(arr);
}
return toReturn;
}
/*
doubleArrtoShort takes in a double array, a by reference integer to output the
number of bytes allocated, a size of the array in BYTES, and whether the program
is in debug mode or not.
the function will allocate enough space for a short array with the same number
of elements as the double array (size / 4) and copy the elements over to the
new array.
*/
short* doubleArrToShort(double* arr, unsigned int *out_bytes, unsigned int size, BOOL debug){
int i;
short *output;
//ensure we are short aligned. Also need half the number of bytes for short
(*out_bytes) = (size + size % BYTES_SHORT) / 4;
output = malloc(*out_bytes);
if(output != NULL){
for (i = 0; i < (size / BYTES_DOUBLE); i++){
output[i] = (short)(arr[i]);
}
if(debug == FALSE){
free(arr);
}
}else{
(*out_bytes) = 0;
if(debug == TRUE)
printf("Failed to allocate memory for short array in floatArrToShort\n");
}
return output;
}
|
C
|
#include <stdio.h>
#include <string.h>
int fib_num[100];
int f_calls = 0;
int fib(int n)
{
f_calls += 1;
if (n == 1 || n == 2) {
fib_num[0] = 0;
fib_num[1] = 1;
fib_num[2] = 1;
return 1;
}
if (fib_num[n] == 0) {
fib_num[n] = fib(n - 1) + fib(n - 2);
return fib_num[n];
}
return fib_num[n];
}
int main()
{
int n;
char s[3];
scanf("%d", &n);
if (n == 1) {
strcpy(s, "st");
}
else if (n == 2) {
strcpy(s, "nd");
}
else if (n == 3) {
strcpy(s, "rd");
}
else {
strcpy(s, "th");
}
if (n < 0) {
printf("Undefined\n");
return 0;
}
printf("%d%s fib: %d\n", n, s, fib(n));
printf("Number of function calls: %d\n", f_calls);
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
int main(){
char str[48] = "`1234567890-=QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./";
char ch;
while(scanf("%c",&ch)==1){
if(ch=='\n' || ch == ' '){
printf("%c",ch);
}
else{
int index=0,i;
for(i=0;i<48;i++){
if(str[i]==ch){
index = i;
break;
}
}
printf("%c",str[index-1]);
}
}
return 0;
}
|
C
|
#include "q_incs.h"
#include <strings.h>
#include <math.h>
#include "_cum_for_evan_dt_F4_I4.h"
#define FTYPE float
#define GTYPE int32_t
int
main(
int argc,
char **argv
)
{
int status = 0;
int nF = 1024;
int chunk_size = 64;
FTYPE *F = malloc(nF * sizeof(FTYPE)); // input
GTYPE *G = malloc(nF * sizeof(GTYPE)); // input
FTYPE *V = malloc(nF * sizeof(FTYPE)); // output
double *S = malloc(nF * sizeof(double)); // output
uint32_t *N = malloc(nF * sizeof(uint32_t)); // output
int min_repeat = 1;
int max_repeat = 8;
int repeat = min_repeat;
int fidx = 0;
float fval = 1;
for ( ; ; ) {
for ( int repeat = min_repeat; repeat < max_repeat; repeat++ ) {
for ( int i = 0; i < repeat; i++ ) {
F[fidx] = fval;
G[fidx] = (int32_t)fval;
fidx++;
if ( fidx >= nF ) { break; }
}
fval++;
if ( fidx >= nF ) { break; }
}
if ( fidx >= nF ) { break; }
}
// confirmt that F is sorted ascending
for ( int i = 1; i < nF; i++ ) {
if ( F[i] < F[i-1] ) { go_BYE(-1); }
}
// for ( int i = 0; i < nF; i++ ) { printf("%f,%d\n", F[i], G[i]); }
int num_blocks = nF / chunk_size;
if ( num_blocks * chunk_size < nF ) {
num_blocks++;
}
uint64_t aidx = 0;
uint64_t num_in_V = 0;
uint64_t nV = chunk_size;
for ( int b = 0; b < num_blocks; b++ ) {
bool is_first;
int lb = b * chunk_size;
int ub = lb + chunk_size;
if ( ub > nF ) { ub = nF; }
uint64_t n_in = ub - lb;
if ( b == 0 ) { is_first = true; } else { is_first = false; }
status = cum_for_evan_dt_F4_I4(is_first, F+lb, G+lb, &aidx, n_in,
V, S, N, nV, &num_in_V);
cBYE(status);
if ( aidx == n_in ) { aidx = 0; }
// TODO: Need to test case of input and output not being
// consumed/produced evenly
}
/*
fval = 1;
int vidx = 0;
int exp_total = min_repeat;
for ( ; ; vidx++ ) {
if ( V[vidx] != fval ) { go_BYE(-1); }
int total = 0;
for ( int i = 0; i < ng; i++ ) {
total += cnts[i][vidx];
}
if ( total != exp_total ) { go_BYE(-1); }
exp_total++;
if ( exp_total > max_repeat ) { exp_total = min_repeat; }
if ( V[vidx] == F[nF-1] ) { break; }
fval++;
}
*/
BYE:
free_if_non_null(F);
free_if_non_null(G);
free_if_non_null(V);
free_if_non_null(S);
free_if_non_null(N);
}
|
C
|
#include <stdio.h>
typedef struct _ {
int x; // 4 bytes
float y;
double z;
} newtype;
/*
compile and then object dump (objdump -s binaryfile)
and look at the .DATA segmment
double y = 1.2345;
int x = 0x12345678;
int x1 = 0x88888888;
int x2 = 0x99999999;
char c = 'A';
*/
int main(){
newtype var2; // debugger - gdb
printf("%lu\n", sizeof(var2));
return 0;
}
|
C
|
#include<linux/init.h> //required for initialization of the module
#include<linux/module.h> //required to the kernel know this is a Loadable Kernel Module
int hello_init(void)
{
printk(KERN_ALERT "inside %s function\n",__FUNCTION__);
return 0;
}
int hello_exit(void)
{
printk(KERN_ALERT "inside %s function\n",__FUNCTION__);
return 0;
}
module_init(hello_init);
module_exit(hello_exit);
|
C
|
#include <stdio.h>
int main(int argc, char const *argv[])
{
float a = 2.95;
int b = a;
printf("%d\n", b);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int dp[5000][2];
//dp[i][0] stores the min num of ops,-1 means not possible
//dp[i][1] stores sum of last block.
//store the min block sum among all 'min' num of operations
int main(int argc, char *argv[])
{
int i,j,k,n,opt;
int max=0,sum=0;
scanf("%d",&n);
int *a=(int*)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
dp[i][0]=0;dp[i][1]=0;
}
dp[0][0]=1;
dp[0][1]=a[0];
for(i=1;i<n;i++)
{
sum=0;opt=0;max=0;
for(j=i;j>0;j--)
{
sum+=a[j];
if(sum>=dp[j-1][1] )
{
if(max<dp[j-1][0])
{
max=dp[j-1][0];
opt=sum;
}
}
}
if(max==0)
{
dp[i][0]=1;
dp[i][1]=sum;
}
else
{
dp[i][0]=max+1;
dp[i][1]=opt;
}
}
printf("%d\n",n-dp[n-1][0]);
return(0);
}
|
C
|
/*! \file
* Implementation of a simple memory allocator. The allocator manages a small
* pool of memory, provides memory chunks on request, and reintegrates freed
* memory back into the pool.
*
* Adapted from Andre DeHon's CS24 2004, 2006 material.
* Copyright (C) California Institute of Technology, 2004-2010.
* All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include "myalloc.h"
/*!
* These variables are used to specify the size and address of the memory pool
* that the simple allocator works against. The memory pool is allocated within
* init_myalloc(), and then myalloc() and free() work against this pool of
* memory that mem points to.
*/
int MEMORY_SIZE;
unsigned char *mem;
unsigned char *startptr;
#define HEAD_SIZE sizeof(int)
/*!
* This function initializes both the allocator state, and the memory pool. It
* must be called before myalloc() or myfree() will work at all.
*
* Note that we allocate the entire memory pool using malloc(). This is so we
* can create different memory-pool sizes for testing. Obviously, in a real
* allocator, this memory pool would either be a fixed memory region, or the
* allocator would request a memory region from the operating system (see the
* C standard function sbrk(), for example).
*/
void init_myalloc() {
/*
* Allocate the entire memory pool, from which our simple allocator will
* serve allocation requests.
*/
mem = (unsigned char *) malloc(MEMORY_SIZE);
if (mem == 0) {
fprintf(stderr,
"init_myalloc: could not get %d bytes from the system\n",
MEMORY_SIZE);
abort();
}
/*
* header starts at the beginnning of the allocated memory, then
* the freeptr starts at the memory start plus the size of the header
*/
startptr = mem;
*((int *) startptr) = (MEMORY_SIZE - HEAD_SIZE);
}
/*!
* Attempt to allocate a chunk of memory of "size" bytes. Return 0 if
* allocation fails. The time complexity of this operation is O(n). This
* is because we look through all of the blocks we have to find which one is
* best fit for a block of the inputted size.
*/
unsigned char *myalloc(int size) {
// set the current pointer to the beginning of our code
unsigned char *current = mem;
unsigned char *best_fit;
int best_size = MEMORY_SIZE;
int cur_head_val;
/*
* loop through our memory until our pointer refrences memory that is
* no longer there (the range of our memory)
*/
while (current < mem + MEMORY_SIZE) {
cur_head_val = * (int *) current;
/*
* if the value stored at current is greater than the amount of bytes
* we want to be allocated
*/
if (cur_head_val > size + HEAD_SIZE) {
// If our current value is smaller than our best one, make it the
// value that we are going to return
if (best_size > cur_head_val && cur_head_val > 0) {
best_size = cur_head_val;
best_fit = current;
}
}
// Increment the current pointer
current += abs(cur_head_val) + HEAD_SIZE;
}
/*
* we need to change the header at our best fit, and the value slash header
* that is immediately afterwards
*/
if (best_size != MEMORY_SIZE) {
// make the next block have correct header information. This ("splits")
// the blocks apart
*((int *)(best_fit + HEAD_SIZE + size)) = *(int *)(best_fit) - size
- HEAD_SIZE;
*(int*) (best_fit) = -size; /* mark our block as used */
return best_fit + HEAD_SIZE;
}
else {
// if it couldn't work
fprintf(stderr, "myalloc: cannot service request of size %d \n", size);
return (unsigned char *) 0;
}
}
/*!
* Free a previously allocated pointer. oldptr should be an address returned by
* myalloc(). The freeing the value takes constant time, and our coalescing
* takes O(n) time because we need to check the blocks before and afterwards
* of our given updated point.
*/
void myfree(unsigned char *oldptr) {
int add_for_next; /* this will be the pointer offset between blocks */
int cur_head_val;
* (int *) (oldptr - HEAD_SIZE) = abs (* (int *) (oldptr - HEAD_SIZE));
unsigned char *current = mem;
/* loop through all of the memory in the array, and stop if we pass
the end*/
while (current < mem + MEMORY_SIZE) {
cur_head_val = * (int *) current;
add_for_next = HEAD_SIZE + abs(cur_head_val);
/* If two adjacent blocks are free, we need to free it together
this if statement also makes sure that our next is still in our mem */
if ( * (int *) (current + add_for_next) >= 0 &&
cur_head_val >= 0 && (current + add_for_next < mem + MEMORY_SIZE)) {
/* update current pointer value */
* (int *) current = cur_head_val + HEAD_SIZE +
* (int *)( current + add_for_next);
continue;
}
/* Increment the current pointers */
current += add_for_next;
}
}
/*!
* Clean up the allocator state.
* All this really has to do is free the user memory pool. This function mostly
* ensures that the test program doesn't leak memory, so it's easy to check
* if the allocator does.
*/
void close_myalloc() {
free(mem);
}
|
C
|
/*
* merge.c
* 2016s1 Prac Exam #2
* UNSW comp1917
*
* Created by Daniel Lau
* Share freely
* 4/06/16
*/
#include <stdio.h>
#include <stdlib.h>
#include "merge.h"
void merge(list listA, list listB, list mergeList) {
//keeping track of where you are in each of the 3 lists
link currA = listA->head;
link currB = listB->head;
link currC = NULL;
//Case 1 - both listA and listB are empty
if(currA == NULL && currB == NULL) {
mergeList->head = NULL;
}
//Case 2 - listB is empty
if(currA != NULL && currB == NULL) {
mergeList->head = currA;
}
//Case 3 - listA is empty
if(currA == NULL && currB != NULL) {
mergeList->head = currB;
}
//Case 4 - listA and listB are not empty
//Case for the head for mergeList
if(currA != NULL && currB != NULL) {
//if a < b or a = b (when a = b, a still comes first)
if(currA->value <= currB->value) {
mergeList->head = currA;
currC = currA;
currA = currA->next;
//if b < a
} else if(currB->value < currA->value) {
mergeList->head = currB;
currC = currB;
currB = currB->next;
}
//currC is head of mergeList now
//currA and currB are holding the relative positions in their relative lists
//Case for the rest of the mergeList
while(currA != NULL || currB != NULL) {
//if a < b or a = b (when a = b, a still comes first)
if(currA->value <= currB->value || currA != NULL && currB == NULL) {
currC->next = currA;
//node after currC is currA now
currA = currA->next;
//move currA to the next node in listA
currC = currC->next;
//move currC to the end of mergeList or where currA was just formed
//if b < a
} else if(currB->value < currA->value || currB != NULL && currA == NULL) {
currC->next = currB;
currB = currB->next;
currC = currC->next;
//same thing
}
}
}
listA->head = NULL;
listB->head = NULL;
//making listA and listB empty and pointing to NULL
}
|
C
|
/* Modem for MIPS AJF October 1996
Equalizer routines */
#include <stdio.h>
#include <string.h>
#include "private.h"
#include "complex.h"
#include "equalize.h"
void equalizer::reset()
{ for (int i = 0; i < 2*np+1; i++) coeffs[i] = 0.0;
coeffs[np] = 1.0;
for (int i = 0; i < size; i++) in[i] = 0.0;
next = 0;
}
void equalizer::insert(complex z)
{ /* circular buffer */
in[next] = z;
if (++next >= size) next = 0;
}
complex equalizer::get()
{ /* get equalized value */
complex z = 0.0; int ncs = 2*np+1;
for (int i = 0; i < ncs; i++)
{ int p = (next+i) & (size-1);
z += coeffs[i] * in[p];
}
return z;
}
void equalizer::upd(complex eps, int n)
{ complex deps = (delta / (2*n+1)) * eps;
for (int i = np-n; i <= np+n; i++)
{ int p = (next+i) & (size-1);
coeffs[i] += deps * cconj(in[p]);
}
}
int equalizer::getdt()
{ int k1 = 0, k2 = 2*np;
float p1 = 0.0, p2 = 0.0; /* total power to left of k1, right of k2 */
while (k1 < k2)
{ if (p1 > p2) p2 += power(coeffs[k2--]);
else p1 += power(coeffs[k1++]);
}
return k1-np; /* return timing (sample point) error, in units of half a symbol */
}
void equalizer::shift(int dt)
{ int ncs = 2*np+1;
if (dt > 0)
{ memmove(&coeffs[dt], &coeffs[0], (ncs-dt) * sizeof(complex));
memset(&coeffs[0], 0, dt * sizeof(complex));
}
if (dt < 0)
{ dt = -dt;
memmove(&coeffs[0], &coeffs[dt], (ncs-dt) * sizeof(complex));
memset(&coeffs[ncs-dt], 0, dt * sizeof(complex));
}
}
void equalizer::print(char *fn)
{ FILE *fi = fopen(fn, "w");
if (fi != NULL)
{ fprintf(fi, ".sp 0.5i\n.G1 8i\n");
fprintf(fi, "new solid\n");
for (int j = -np; j <= +np; j++) fprintf(fi, "%d %g\n", j, coeffs[np+j].re);
fprintf(fi, "new dashed\n");
for (int j = -np; j <= +np; j++) fprintf(fi, "%d %g\n", j, coeffs[np+j].im);
fprintf(fi, "new dotted\n");
for (int j = -np; j <= +np; j++) fprintf(fi, "%d %g\n", j, power(coeffs[np+j]));
fprintf(fi, ".G2\n.bp\n");
for (int j = -np; j <= +np; j++) fprintf(fi, "{ %10.6f, %10.6f },\n", coeffs[np+j].re, coeffs[np+j].im);
fclose(fi);
}
else fprintf(stderr, "can't create %s\n", fn);
}
|
C
|
/*
Name: p4q6.c
Desc: Quiz program.
*/
//directives
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//defined data
#define Q_FILE "Questions.txt"
#define A_FILE "Answers.txt"
//data structures
typedef struct {
char question[30];
char answer[30];
} Quiz;
//declarations
int getQuestion(Quiz *quiz, FILE* qFile, FILE* aFile);
int getAnswer(char *userAnswer, Quiz *quiz);
int compareAnswer(Quiz *quiz, char *userAnswer);
int main(void)
{
//variables
Quiz quiz;
FILE *qFile, *aFile;
char userAnswer[30];
int correct, questions;
double score;
qFile = fopen(Q_FILE, "r");
aFile = fopen(A_FILE, "r");
while(getQuestion(&quiz, qFile, aFile) != 0)
{
getAnswer(userAnswer, &quiz);
if((compareAnswer(&quiz, userAnswer)) == 1)
{
printf("Correct!\n");
questions++;
correct++;
}
else
{
printf("Wrong, answer should be %s\n", quiz.answer);
questions++;
}
}
//calculate score
score = (double) correct / questions * 100;
//display results
printf("\n" "Number of correct answers\t= %d\n"
"Total number of questions\t= %d"
"\n"
"\tYour score\t>>>>>>>\t%.2f%%", correct, questions, score);
}
//definitions
//get a question from the question file
int getQuestion(Quiz *quiz, FILE* qFile, FILE *aFile)
{
//get first question, write to question
if(fscanf(qFile, "%[^\n]\n", &quiz->question) == EOF)
return 0;
//get answer
if(fscanf(aFile, "%[^\n]\n", &quiz->answer) == EOF)
return 0;
//return
return 1;
}
//get an answer from the user
int getAnswer(char *userAnswer, Quiz *quiz)
{
//ask for input
printf("%s ", quiz->question);
//get string
scanf("%29[^\n]", userAnswer);
rewind(stdin);
//return success
return 0;
}
//check the answer
int compareAnswer(Quiz *quiz, char *userAnswer)
{
//compare if userAnswer is same as quiz answer
if (strcmp(quiz->answer, userAnswer) == 0)
{
return 1;
}
else
{
return 0;
}
}
|
C
|
#include <stdint.h>
#include <string.h>
int user1_tobool(const char *Str) {
if (!memcmp(Str, "true", 4) || !memcmp(Str, "1", 1)) {
return 1;
} else if (!memcmp(Str, "false", 5) || !memcmp(Str, "0", 1)) {
return 0;
}
return -1;
}
int user2_tobool(const char *const StrIn, unsigned Len) {
int64_t Word = 0;
// There was a bug here if Len was bigger than Word
Len = (Len > sizeof Word) ? sizeof Word : Len;
memcpy(&Word, StrIn, Len);
switch (Word | 32) {
case '0':
case 'f':
case 0x65736c6166:
case 'n':
case 0x6f6e:
return 0;
case '1':
case 't':
case 0x65757274:
case 'y':
case 0x736579:
return 1;
}
return -1;
}
|
C
|
#include <stdio.h>
int main(int argc,char **argv)
{
int num;//declaration of integer
int *numPtr;//declaration of pointer
int num2;
num=100;
numPtr=#//&num= address of variable num
num2=*numPtr;//*numPtr = value on numPtr address
printf("num=%d, numPtr=%d, address of num=%d, num2=%d", num, numPtr, &num, num2);
return 0;
}
|
C
|
// Implements a dictionary's functionality
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <strings.h>
#include "dictionary.h"
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Number of buckets in hash table
const unsigned int N = 26 * 26 * 26 * 26;
// Overall hash table size
unsigned int tableSize = 0;
// Hash table
node *table[N];
// Returns true if word is in dictionary else false
bool check(const char *word)
{
node *tmp = table[hash(word)];
while (tmp != NULL)
{
if (strcasecmp(tmp->word, word) == 0)
{
return true;
}
tmp = tmp->next;
}
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
unsigned int count = 0;
for (int i = 0, n = strlen(word); i < n; i++)
{
count += tolower(word[i]);
count *= tolower(word[i]);
}
return count % N;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// Array to store each word
char word[45];
// Open file with words (dictionary)
FILE *dictionaryFile = fopen(dictionary, "r");
// Error checking
if (dictionaryFile == NULL)
{
return false;
}
// Add new nodes while there are words
while (fscanf(dictionaryFile, "%s", word) != EOF)
{
// New node
node *n = malloc(sizeof(node));
// Error checking
if (n == NULL)
{
fclose(dictionaryFile);
return false;
}
// Set word variable to new word in file
strcpy(n->word, word);
// Next points to nothing
n->next = NULL;
// Get an index from hash function
int index = hash(word);
// If the hash table isn't pointing to anything, point to this new node
if (table[index] == NULL)
{
table[index] = n;
}
// Else...
else
{
// Point the new node next variable to what the table points to (which is a node)
n->next = table[index];
// And point the table to the new node
table[index] = n;
}
// Increment the overall hash table size
tableSize++;
}
// Close the file
fclose(dictionaryFile);
// Return true as successful
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
return tableSize;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
// Temporary pointers
node *tmp, *cursor;
// Go through each row
for (int i = 0; i < N; i++)
{
// Set the temporary variables ot the current row in the hash table
tmp = table[i], cursor = table[i];
// While the temp variable is not null
while (tmp != NULL)
{
// Set the cursor temp variable to the next node in this row
cursor = tmp->next;
// Free the current node
free(tmp);
// Set temp variable to next node
tmp = cursor;
}
}
return true;
}
|
C
|
#include <stdio.h>
float max(float arr[], int n) {
int i;
float t = arr[0];
for (i=0; i<n; i++) {
t = t > arr[i] ? t : arr[i];
}
return t;
}
float min(float arr[], int n) {
int i;
float t = arr[0];
for (i=0; i<n; i++) {
t = t < arr[i] ? t : arr[i];
}
return t;
}
void pop(float value, float arr[], int n, float arr2[]) {
int i;
int j = 0;
int already_poped = 0;
for (i=0; i<n; i++) {
if (arr[i] == value && already_poped != 1) {
already_poped = 1;
continue;
}
arr2[j++] = arr[i];
}
}
float mean(float arr[], int n) {
int i;
float t = 0;
for (i=0; i<n; i++) {
t += arr[i];
}
return t / n;
}
int main() {
int i;
float t[7], t2[6], t3[5];
for (i=0; i<7; i++) {
scanf("%f", &t[i]);
}
pop(max(t, 7), t, 7, t2);
pop(min(t, 7), t2, 6, t3);
printf("%.2f\n", mean(t3, 5));
return 0;
}
|
C
|
#include<Stdio.h>
int main()
{
int a;
printf("Enter a negative integer which is perfectly divisible by 2 : ");
scanf("%d", &a);
if ((a<0)&&(a%2==0))
{
printf("Good Job!");
}
else
{
printf("What's wrong with you?");
}
}
|
C
|
#include "const_errors.h"
void insertion_sort_array(int n, struct thing *object)
{
int location;
struct thing new_element;
for (int i = 1; i < n; i++)
{
new_element = object[i];
location = i - 1;
while (location >= 0 && object[location].weight / object[location].size \
> new_element.weight / new_element.size)
{
object[location + 1] = object[location];
location--;
}
object[location + 1] = new_element;
}
}
int find_str_in_name(struct thing object, char *str_to_find)
{
int success = 1;
for (int i = 0; str_to_find[i] != '\0' && success == 1; i++)
if (str_to_find[i] != object.name[i])
success = 0;
return success;
}
int form_array_of_found_objects(struct thing *object, int arr_size, char *str_to_find)
{
int ind = 0;
while (ind < arr_size)
{
if (!find_str_in_name(object[ind], str_to_find))
{
for (int j = ind; j < arr_size - 1; j++)
object[j] = object[j + 1];
arr_size--;
ind--;
}
ind++;
}
return arr_size;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* trace_map.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abezgrar <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/22 22:26:23 by abezgrar #+# #+# */
/* Updated: 2017/11/23 23:34:25 by abezgrar ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
void get_pas(t_pts p1, t_pts p2, t_calc *c)
{
c->z = (double)p1.z;
c->pas_z = (double)(p2.z - p1.z) / sqrt(((p2.x - p1.x) *
(p2.x - p1.x))
+ ((p2.y - p1.y) * (p2.y - p1.y)));
}
void bresen(t_window *w, t_pts p1, t_pts p2)
{
t_calc calc;
calc.dx = abs((p2.x - p1.x));
calc.sx = p1.x < p2.x ? 1 : -1;
calc.dy = abs((p2.y - p1.y));
calc.sy = p1.y < p2.y ? 1 : -1;
calc.err = (calc.dx > calc.dy ? calc.dx : -calc.dy) / 2;
get_pas(p1, p2, &calc);
while (!(p1.x == p2.x || p1.y == p2.y))
{
print_pixel(w, p1.x + w->x_start, p1.y + w->y_start, p1.z);
calc.z += calc.pas_z;
calc.e2 = calc.err;
if (calc.e2 > -calc.dx)
{
calc.err -= calc.dy;
p1.x += calc.sx;
}
if (calc.e2 < calc.dy)
{
calc.err += calc.dx;
p1.y += calc.sy;
}
}
}
void fill_pts_stru(int i, int j, int **map, t_window *w)
{
t_pts p1;
t_pts p2;
if (i < w->size_vertic - 1)
{
p1.x = -5 * w->zoom * ((sqrt(2) / 2)) * (i - j);
p1.y = -5 * w->zoom * MAUR;
p1.z = map[i][j] * w->z_start;
p2.x = -5 * w->zoom * ((sqrt(2) / 2)) * ((i + 1) - j);
p2.y = -5 * w->zoom * LOL;
p2.z = map[i + 1][j] * w->z_start;
bresen(w, p1, p2);
}
if (j < w->size_hori - 1)
{
p1.x = -5 * w->zoom * ((sqrt(2) / 2)) * (i - j);
p1.y = -5 * w->zoom * MAUR;
p1.z = map[i][j] * w->z_start;
p2.x = -5 * w->zoom * ((sqrt(2) / 2)) * (i - (j + 1));
p2.y = -5 * w->zoom * LUL;
p2.z = map[i][j + 1] * w->z_start;
bresen(w, p1, p2);
}
}
void print_map(t_window *w)
{
int i;
int j;
i = 0;
j = 0;
while (i < w->size_vertic)
{
while (j < w->size_hori)
{
fill_pts_stru(i, j, w->map, w);
j++;
}
i++;
j = 0;
}
}
void trace_map(t_window *w)
{
mlx_hook(w->win_ptr, 2, (1L << 0), key, (void*)w);
refresh(w);
mlx_loop(w->mlx);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE{
int num;
struct NODE * next;
}node;
void addtohead(node ** head,node * new );
void addbetween(node ** frist,node ** next, node * new );
void addtotail(node ** head,node * new);
int main(){
node * head=malloc(sizeof(node));
//check if creation success
node * Node1=malloc(sizeof(node));
//check if creation success
node * Node2=malloc(sizeof(node));
//check if creation success
node * Node3=malloc(sizeof(node));
//check if creation success
node * Node4=malloc(sizeof(node));
//check if creation success
node * Node5=malloc(sizeof(node));
//check if creation success
head->num=2;
head->next=Node1;
Node1->num=3;
Node1->next=Node2;
Node2->num=4;
Node2->next=NULL;
Node3->num=5;
Node3->next=NULL;
Node4->num=20;
Node4->next=NULL;
Node5->num=25;
Node5->next=NULL;
puts("Before");
node * temp=head;
while(temp!=NULL){
printf("%d\n",temp->num);
temp=temp->next;
}
addtohead(&head,Node4);
addbetween(&Node1,&Node2,Node3);
addtotail(&head,Node5);
puts("\nAfter");
temp=head;
while(temp!=NULL){
printf("%d\n",temp->num);
temp=temp->next;
}
return 0;
}
//=====================
void addbetween(node ** first,node ** next, node * new ){
new->next=*next;
(*first)->next=new;
}
//===============
void addtohead(node ** head,node * new ){
new->next=*head;
*head=new;
}
//================
void addtotail(node** head,node* new){
node* temp=*head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=new;
new->next=NULL;
}
|
C
|
// printqueue_print.c: send jobs to a printer.
// Run one process for each printer.
#include "headers.h"
int main(int argc, char *argv[]) {
//initializing and creating semaphore, should be done before program is used normally
if(strcmp(argv[1],"-init")==0){
sem_t *sem = sem_open("/printqueue_sem", O_CREAT, S_IRUSR | S_IWUSR);
sem_init(sem, 1, 1);
sem_close(sem);
return 0;
}
if(argc < 2){
printf("usage: %s <printqueue.txt>\n",
argv[0]);
exit(1);
}
size_t size;
char *file_chars =
mmap_file(argv[1],&size);
int line_num = 1;
int file_pos = 0;
sem_t *sem = sem_open(sem_name, O_CREAT, S_IRUSR | S_IWUSR); //open semaphore
while(file_pos < size){
sem_wait(sem); //wait until we can read the file without anyone modifying it
char status, filename[MAXLINE];
sscanf(file_chars+file_pos,
"%c %1024[^\n]",
&status, filename);
if(status == '*'){
file_chars[file_pos] = 'P';
sem_post(sem); //Unlock the file now that we have "claimed" this print job by changing its status
send_to_printer(filename,MY_PRINTER);
file_chars[file_pos] = 'D';
}
else{
sem_post(sem); //unlock file
}
file_pos += strlen(filename)+3;
line_num++;
}
sem_close(sem); //cleanup by closing the semaphore
return 0;
}
|
C
|
#include "lists.h"
#include <stdlib.h>
/**
* list_len - return number of elements in a linked list.
*
* @h: Pointer to list header.
* Return: Size of linked list
*/
size_t list_len(const list_t *h)
{
size_t size = 0;
if (h == NULL)
return (0);
while (h != NULL)
{
size++;
h = h->next;
}
return (size);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "basic.h"
int DetermineFunction(char *name)
{
int i;
char *string[4] = {"GOTO", "IF", "PRINT", "STOP"};
for (i = 0 ; i < 4 ; i++)
if (strcmp(name, string[i]) == 0)
return i+1;
return 0;
}
int DetermineCompare(char *code)
{
char *string[6] = {"==", "!=", ">", "<", ">=", "<="};
int i;
for (i = 0 ; i < 6 ; i++)
if (strcmp(code, string[i]) == 0)
return i+1;
return 0;
}
|
C
|
#include <stddef.h>
#include "mm.h"
#include "stats.h"
/* lower triangular matrix multiplication */
void mm1(double *restrict A, const double *restrict B,
const double *restrict C, size_t N)
{
{
start_stats();
for (size_t i = 0; i < N; i++) {
size_t ii = i * (i+1) / 2;
for (size_t j = 0; j <= i; j++) {
double sum = 0.0;
for (size_t k = j; k <= i; k++) {
size_t kk = k * (k+1) / 2;
sum += B[ii + k] * C[kk + j];
}
A[ii + j] = sum;
}
}
stop_stats();
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int a[5][5] = { 0 };
int tanknum = 0;
int x, y; //x y
int hitnum_user = 0;
int hitnum_com = 0;
srand((unsigned int) time(NULL));
////////////////////////////////////////////////
//
////////////////////////////////////////////////
printf("ũ ġ Ͻÿ :\n");
while (1)
{
printf("ũ %d :", tanknum + 1);
scanf("%d", &x);
printf("ũ %d :", tanknum + 1);
scanf("%d", &y);
if (a[x][y] == 0)
{
a[x][y] = 1;
tanknum += 1;
}
else
{
printf("ũ 2 ũ1 ġ ĥ ϴ. ٽ ԷϽÿ.\n");
}
if (tanknum == 2)
{
break;
}
}
////////////////////////////////////////////////
// ǻ
////////////////////////////////////////////////
tanknum = 0;
while (1)
{
x = rand() % 5; //ǻʹ ġ
y = rand() % 5;
if (a[x][y] == 0)
{
a[x][y] = 2;
tanknum += 1;
}
if (tanknum == 2)
{
break;
}
}
printf("\n");
////////////////////////////////////////////////
//
////////////////////////////////////////////////
while (1)
{
////////////////////////////////////////////////
//
////////////////////////////////////////////////
printf("ǻ ũ ?\n");
printf(":");
scanf("%d", &x);
printf(":");
scanf("%d", &y);
if (a[x][y] == 2)
{
printf(" Ÿݼ\n");
hitnum_user++;
}
else
{
printf(" Ÿݺҹ\n");
}
if (hitnum_user == 2)
{
printf(" ¸\n");
break;
}
////////////////////////////////////////////////
// ǻ
////////////////////////////////////////////////
x = rand() % 5;
y = rand() % 5;
if (a[x][y] == 1)
{
printf("ǻ Ÿݼ\n");
hitnum_com++;
}
else
{
printf("ǻ Ÿݺҹ\n");
}
if (hitnum_com == 2)
{
printf("ǻ ¸\n");
break;
}
}
return 0;
}
|
C
|
#include <stdio.h>
int main() {
// Array ar[n]
// int + k
// print (i,j)
// i < j
// (ar[i] + ar[j]) % k = 0
int k = 5;
int n = 6;
int ar[6] = {1, 2, 3, 4, 5 ,6};
for (int i = 0; i < n; i++) {
for (int j = 1; j < n; j++) {
if (i < j && (ar[i] + ar[j]) % k == 0) {
printf("[%d,%d] \0", ar[i], ar[j]);
}
}
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_newmem.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nflores <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/05/17 10:36:54 by nflores #+# #+# */
/* Updated: 2016/05/30 13:20:44 by nflores ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/vm.h"
t_mem *ft_newmem(int n)
{
t_mem *ret;
ret = (t_mem *)malloc(sizeof(t_mem));
if (!ret)
exit(write(2, "Malloc error\n", 13));
ret->oct = 0;
ret->n = n;
ret->champ_own = 0;
ret->champ_wr = 0;
ret->prev = ret;
ret->next = ret;
return (ret);
}
void ft_meminit(t_mem **mem, int size)
{
t_mem *tmp;
t_mem *new;
int i;
i = 0;
*mem = ft_newmem(0);
tmp = *mem;
while (i < size - 1)
{
new = ft_newmem(i + 1);
new->prev = tmp;
new->next = tmp->next;
tmp->next->prev = new;
tmp->next = new;
tmp = tmp->next;
i++;
}
}
void ft_gameinit(t_mem **mem, t_champ_list *lst, int nb_champ)
{
int i;
int j;
t_mem *tmp;
i = 0;
tmp = *mem;
while (i < MEM_SIZE)
{
j = 0;
while (j < lst->champ->prog_size)
{
if (j == 0)
lst->champ->pc = tmp->n;
tmp->oct = lst->champ->prog[j];
tmp->champ_own = lst->champ->reg[0];
tmp->champ_wr = lst->champ->reg[0];
j++;
tmp = tmp->next;
}
i += MEM_SIZE / nb_champ + lst->champ->pc % 2;
while (tmp->n != i - lst->champ->pc % 2 && tmp->n != MEM_SIZE - 1)
tmp = tmp->next;
lst = lst->next;
}
tmp = NULL;
}
|
C
|
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
#include "../../base/osplatformutil.h"
struct Product /*声明结构*/
{
char cName[10]; /*产品的名称*/
char cShape[20]; /*形状*/
char cColor[10]; /*颜色*/
int iPrice; /*价格*/
char cArea[20]; /*产地*/
} ;
struct Product2 {
char name[20];
char shape[30];
char color[20];
double price;
char area[100];
};
typedef struct Product2 Pro;
int main() {
#if defined I_OS_MAC
printf("this is mac\n");
#elif defined I_OS_WIN32
system("chcp 65001");
printf("this is windows\n");
#elif defined I_OS_LINUX
printf("this is linux\n");
#endif
struct Product product1; /*定义结构体变量*/
struct Product2 product2;
strcpy(product2.area, "小地方");
strcpy(product2.name, "高达");
strcpy(product2.shape, "椭圆");
product2.price = 23.3;
printf("name: %s; shape: %s; area: %s; price: %f; \n", product2.name, product2.shape, product2.area, product2.price);
Pro product3;
strcpy(product3.area, "小地方");
strcpy(product3.name, "高达");
strcpy(product3.shape, "椭圆");
product3.price = 23.3;
printf("name: %s; shape: %s; area: %s; price: %f; \n", product3.name, product3.shape, product3.area, product3.price);
printf("please enter product's name\n"); /*信息提示*/
scanf("%s", &product1.cName); /*输出结构成员*/
printf("please enter product's shape\n");/*信息提示*/
scanf("%s", &product1.cShape); /*输出结构成员*/
printf("please enter product's color\n");/*信息提示*/
scanf("%s", &product1.cColor); /*输出结构成员*/
printf("please enter product's price\n");/*信息提示*/
scanf("%d", &product1.iPrice); /*输出结构成员*/
printf("please enter product's area\n");/*信息提示*/
scanf("%s", &product1.cArea); /*输出结构成员*/
printf("Name: %s\n", product1.cName); /*将成员变量输出*/
printf("Shape: %s\n", product1.cShape);
printf("Color: %s\n", product1.cColor);
printf("Price: %d\n", product1.iPrice);
printf("Area: %s\n", product1.cArea);
return 0;
}
|
C
|
#include <allegro.h>
#include "../include/defines.h"
#include "../include/global.h"
#include "../include/menu.h"
#include "../include/menus.h"
static int _id = DEMO_STATE_MISC;
static int id(void)
{
return _id;
}
static char *choice_yes_no[] = { "no", "yes", 0 };
static void on_fps(DEMO_MENU * item)
{
display_framerate = item->extra;
}
static void on_limit(DEMO_MENU * item)
{
limit_framerate = item->extra;
}
static void on_yield(DEMO_MENU * item)
{
reduce_cpu_usage = item->extra;
}
static DEMO_MENU menu[] = {
{demo_text_proc, "SYSTEM SETTINGS", 0, 0, 0, 0},
{demo_choice_proc, "Show Framerate", DEMO_MENU_SELECTABLE, 0,
(void *)choice_yes_no, on_fps},
{demo_choice_proc, "Cap Framerate", DEMO_MENU_SELECTABLE, 0,
(void *)choice_yes_no, on_limit},
{demo_choice_proc, "Conserve Power", DEMO_MENU_SELECTABLE, 0,
(void *)choice_yes_no, on_yield},
{demo_button_proc, "Back", DEMO_MENU_SELECTABLE,
DEMO_STATE_OPTIONS, 0,
0},
{0, 0, 0, 0, 0, 0}
};
static void init(void)
{
init_demo_menu(menu, TRUE);
menu[1].extra = display_framerate;
menu[2].extra = limit_framerate;
menu[3].extra = reduce_cpu_usage;
}
static int update(void)
{
int ret = update_demo_menu(menu);
switch (ret) {
case DEMO_MENU_CONTINUE:
return id();
case DEMO_MENU_BACK:
return DEMO_STATE_OPTIONS;
default:
return ret;
};
}
static void draw(BITMAP *canvas)
{
draw_demo_menu(canvas, menu);
}
void create_misc_menu(GAMESTATE * state)
{
state->id = id;
state->init = init;
state->update = update;
state->draw = draw;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 20002
#define PLOT_DOWN '\\'
#define PLOT_FLAT '_'
#define PLOT_UP '/'
typedef struct section { int j, size; } sec_t;
int main(int argc, char **argv) {
char buf[MAX_SIZE];
char *ret;
int i, j, m, n, total, sub;
int s1[MAX_SIZE];
sec_t tmp;
sec_t s2[MAX_SIZE / 2];
ret = fgets(buf, MAX_SIZE, stdin);
if (ret == NULL) exit(1);
for (i = m = n = total = 0; buf[i] != '\0'; ++i) {
switch (buf[i]) {
case PLOT_DOWN:
s1[m++] = i;
break;
case PLOT_UP:
if (m < 1) break;
j = s1[--m];
total += i - j;
sub = i - j;
while (n > 0) {
tmp = s2[--n];
if (j > tmp.j) {
++n;
break;
}
sub += tmp.size;
}
s2[n].j = j;
s2[n].size = sub;
n++;
break;
}
}
printf("%d\n%d", (int) total, n);
for (i = 0; i < n; ++i) printf(" %d", (int) s2[i].size);
printf("\n");
exit(0);
}
|
C
|
#include<stdio.h>
char a, c;
int b;
int main(){
c=getchar();
while(c!='\n'){
a=c;
b=0;
while(c==a){
b++;
c=getchar();
}
printf("%c%d", a, b);
}
putchar('\n');
}
|
C
|
#include <stdio.h>
int CountR( int iNo )
{
static int iCnt = 0;
if ( iNo != 0 )
{
iCnt++;
iNo = iNo / 10;
CountR( iNo );
}
return iCnt;
}
int main()
{
int iRet = 0;
iRet = CountR(1121);
printf( "%d", iRet );
return 0;
}
|
C
|
/*
*******************************************************************************
* *
* Copyright (c) *
* All rights reserved. *
* *
*******************************************************************************
*
* Filename: std_type.h
*
******************************************************************************* *
* Description:
*
* (For a detailed description look at the object description in the UML model)
*
*******************************************************************************
* History
*******************************************************************************
* Version: 16.0
* Author/Date: JSO / 2018-09-30
* Change: Add the typedef of unsigned int
*******************************************************************************
* Version: 14.0
* Author/Date: JSO / 2018-09-29
* Change: Initial version
*******************************************************************************
*/
#ifndef STD_TYPE_H_
#define STD_TYPE_H_
#include <string.h>
/* define C boolean */
#ifndef false
#define false (0)
#endif
#ifndef true
#define true (!false)
#endif
#ifndef FALSE
#define FALSE (0)
#endif
#ifndef TRUE
#define TRUE (!FALSE)
#endif
/* TYPE DEFINITIONS */
typedef signed int sint;
typedef unsigned int uint;
typedef signed char sint8; // -128 to +127
typedef unsigned char uint8; // 0 to 255
typedef signed short sint16; // -32768 to +32767
typedef unsigned short uint16; // 0 to 65535
typedef signed long sint32; // -2147483648 to +2147483647
typedef unsigned long uint32; // 0 to 4294967295
typedef float real32;
typedef double real64;
typedef unsigned char bool;
#endif /* STD_TYPE_H_ */
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_draw.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mbourdel <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/01/04 13:24:57 by mbourdel #+# #+# */
/* Updated: 2015/04/28 15:40:18 by mbourdel ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
void ft_draw(t_pt2d origin, t_pt2d arrival, t_env *env)
{
float dx;
float dy;
dx = arrival.x - origin.x;
dy = arrival.y - origin.y;
if (fabs(dx) > fabs(dy))
{
if (dx > 0)
dy <= 0 ? ft_draw_cone(origin, arrival, env)
: ft_draw_ctwo(origin, arrival, env);
else
dy >= 0 ? ft_draw_cone(arrival, origin, env)
: ft_draw_ctwo(arrival, origin, env);
}
else
{
if (dy < 0)
dx >= 0 ? ft_draw_cfive(arrival, origin, env)
: ft_draw_csix(arrival, origin, env);
else
dx <= 0 ? ft_draw_cfive(origin, arrival, env)
: ft_draw_csix(origin, arrival, env);
}
return ;
}
|
C
|
/*NICOLESCU Daniel-Marian-314CB*/
#ifndef _HASH_H_
#define _HASH_H_
//structura hash
typedef struct
{
TFHash fh;
TLG *v;
KeyCmp cmp;
ShowKey show_key;
FreeKey free_key;
} TH;
//prototipurile functiilor:
//functia hash
unsigned int hash_f(const void*, size_t, size_t);
void free_key(void*);
int int_cmp(void*, void*);
int string_cmp(void*, void*);
void show_int_key(void*, FILE*);
void show_string_key(void*, FILE*);
void show_mat_value(void*, FILE*);
void show_stud_value(void*, FILE*);
void free_mat_value(void*);
void free_stud_value(void*);
void Print_Hash(TH*, size_t, FILE*);
//initiere Hash table
TH* IniTH(size_t, TFHash, KeyCmp, ShowKey, FreeKey);
//inserare element in Hash table
int InsTH(TH*, void*, size_t, void*, size_t, size_t, ShowValue, FreeValue);
//inserare element in lista generica determinata de InsTH
int InsLG(ALG, KeyCmp, void*, size_t, void*, size_t, ShowValue, FreeValue, FreeKey);
//redimensionare Hash table
int ResTH(TH*, size_t, size_t, size_t);
void find_value_by_key(TH*, void*, size_t, size_t, FILE*);
int del_by_key(TH*, void*, size_t, size_t);
void free_hash(TH**, size_t);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
#define MAX_LIB_SIZE 100
#define MAX_LENGTH 1024
typedef struct song{
char songName[MAX_LENGTH];
char artist[MAX_LENGTH];
char genre[MAX_LENGTH];
} Song;
/* Function Prototypes */
void inputStringFromUser(char prompt[], char s[], int arraySize);
void printMusicLibraryEmpty();
void printMusicLibraryTitle();
void printLibrary(Song library[], int size);
void cocktailSort(Song library[], int size);
int customStrcmp(char *, char*);
/* Prompt the user for a string safely, without buffer overflow */
void inputStringFromUser(char prompt[], char s[], int maxStrLength) {
int i = 0;
char c;
printf("%s --> ", prompt);
while(i < maxStrLength && (c = (char) getchar()) != '\n')
s[i++] = c;
s[i] = '\0';
}
/* Function to call when printing an empty music library. */
void printMusicLibraryEmpty(){
printf("\nThe music library is empty.\n");
}
/* Function to call to print a title when the entire music library is printed. */
void printMusicLibraryTitle(){
printf("\nMy Personal Music Library: \n");
}
/*
* A custom string compare function that compares the lowercase strings of the songs.
* This is done to eliminate the possibility of error in ordering songs without capitalization.
*/
int customStrcmp(char *stringToCompare, char *stringToCompareWith){
//creates temporary space to store the source and destination strings/arrays
char *tempStringToCompare = (char*) malloc(sizeof(char)*(MAX_LENGTH + 1));
char *tempStringToCompareWith = (char*) malloc(sizeof(char)*(MAX_LENGTH + 1));
int i = 0, j = 0;
while(stringToCompare[i] != '\0'){ //custom string copy function
tempStringToCompare[i] = (char) tolower(stringToCompare[i]); //store the lowercase alphabet
i++;
}
tempStringToCompare[i] = '\0';
while(stringToCompareWith[j] != '\0'){
tempStringToCompareWith[j] = (char) tolower(stringToCompareWith[j]); //store the lowercase alphabet
j++;
}
tempStringToCompareWith[i] = '\0';
int compare = strcmp(tempStringToCompare, tempStringToCompareWith);
free(tempStringToCompare); //free the temporary memory
free(tempStringToCompareWith);
return compare; //returns the integer resulting from comparing the lower case version of two the strings.
}
/* Sorting the library array in ascending alphabetical order, by artist */
void cocktailSort(Song library[], int size){ //Bubble sort both ways
bool goingUp = true;
bool sorted = false;
bool shouldSwap;
int bottom = 0, top = size - 1, i;
while(bottom < top && !sorted){
sorted = true;
if(goingUp){
for(i = bottom; i < top; i++){
if(customStrcmp(library[i].artist, library[i+1].artist) > 0){
shouldSwap = true;
} else if(customStrcmp(library[i].artist, library[i+1].artist) == 0){
if(customStrcmp(library[i].songName, library[i+1].songName) > 0){
shouldSwap = true;
} else shouldSwap = false;
} else shouldSwap = false;
if(shouldSwap){
Song temp = library[i];
library[i] = library[i+1];
library[i+1] = temp;
sorted = false;
}
}
top--;
goingUp = false;
} else{
for(i = top; i > bottom; i--){
if(customStrcmp(library[i].artist, library[i-1].artist) < 0){
shouldSwap = true;
} else if(customStrcmp(library[i].artist, library[i-1].artist) == 0){
if(customStrcmp(library[i].songName, library[i-1].songName) < 0){
shouldSwap = true;
} else shouldSwap = false;
} else shouldSwap = false;
if(shouldSwap){
Song temp = library[i-1];
library[i-1] = library[i];
library[i] = temp;
sorted = false;
}
}
bottom++;
goingUp = true;
}
}
}
/* Printing the entire music library */
void printLibrary(Song library[], int librarySize){
if(librarySize){
printMusicLibraryTitle();
for(int i = 0; i < librarySize; i++)
printf("\n%s\n%s\n%s\n", library[i].songName, library[i].artist, library[i].genre);
}
else printMusicLibraryEmpty();
}
int main(void){
Song library[MAX_LIB_SIZE]; //static declaration
int librarySize = 0; //number of elements stored in the library
printf("Personal Music Library.\n\n"); //Announce the start of the program
printf("Commands are I (insert), S (sort by artist), P (print), Q (quit).\n");
char response;
char input[MAX_LENGTH + 1];
do{
inputStringFromUser("\nCommand", input, MAX_LENGTH);
response = (char) toupper(input[0]); // Response is the first character entered by user.
if(response == 'I'){ //Insert a song into the array.
char *promptName = "Song name";
char *promptArtist = "Artist";
char *promptGenre = "Genre";
inputStringFromUser(promptName, library[librarySize].songName, MAX_LENGTH);
inputStringFromUser(promptArtist, library[librarySize].artist, MAX_LENGTH);
inputStringFromUser(promptGenre, library[librarySize].genre, MAX_LENGTH);
librarySize++; //increment the library size by one
} else if(response == 'P'){ //Print the music library.
printLibrary(library, librarySize);
} else if(response == 'S'){
cocktailSort(library, librarySize); //Sort the library in ascending order
printLibrary(library, librarySize); //Print the sorted music library
} else if(response == 'Q'){
; //do nothing
} else{ //do this if no command matched ...
printf("\nInvalid command.\n");
}
} while(response != 'Q');
return 0;
}
|
C
|
/*
Author: AnOnYmOus001100
Date: 08/08/2020
Description: Ramanujan number is the smallest number that can be expressed as sum of two cubes in two different ways.
Find all such numbers upto a resonable limit.
*/
#include<stdio.h>
int main()
{
int i, n1, n2, x, y, r;
printf("Input a range n1 n2 between which to find Ramanujan No.: ");
scanf("%d %d", &n1, &n2);
// only 1729 is the ramunajan number among all such numbers as it is the smallest number which passes the condition
printf ("\nList of all such numbers are: \n");
for(i = n1; i < n2; i++){
r = 0;
for(x = 1;x*x*x < i;x++){
for(y = x+1; x*x*x + y*y*y <= i; y++){
if(x*x*x + y*y*y == i){
r++;
x++;
}
}
}
if(r == 2){
printf("%d ", i);
}
}
return 0;
}
|
C
|
#include <stdio.h>
#define max(a,b) (a>b?a:b)
int dp[55][55][55][55] = {0};
int arr[55][55] = {0};
int main()
{
int m,n;//ѧλmn
scanf("%d%d",&m,&n);
int i = 0;
int j = 0;
//ͬѧԣ1,1m,n)λѧĺøж
for(i = 1; i <= m; i++)
{
for(j = 1; j <= n; j++)
{
scanf("%d",&arr[i][j]);
}
}
int i1,j1,i2,j2;
for(i1 = 1; i1 <= m; i1++)
{
for(j1 = 1; j1 <= n; j1++)
{
for(i2 = 1; i2 <= m; i2++)
{
for(j2 = 1; j2 <= n; j2++)
{
//ֽͬĺøж
int same = max(dp[i1-1][j1][i2-1][j2],dp[i1][j1-1][i2][j2-1]);
//췽ֽĺøж
int diff = max(dp[i1][j1-1][i2-1][j2],dp[i1-1][j1][i2][j2-1]);
dp[i1][j1][i2][j2] = max(same,diff) + arr[i1][j1];
//жǷͬһλ
if(i1!=i2 && j1!=j2)
{
dp[i1][j1][i2][j2] += arr[i2][j2];
}
//printf("%d\n",dp[i1][j1][i2][j2]);
}
}
}
}
printf("%d\n",dp[m][n][m][n]);
return 0;
}
|
C
|
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#define NUM 5
pthread_mutex_t chopsticks[NUM];
void *philosopher(void *arg)
{
const char *args = (const char *)arg;
char id = args[0];
char d1 = args[1];
char d2 = args[2];
int o1 = d1 - '0' - 1;
int o2 = d2 - '0' - 1;
pthread_mutex_t *left = chopsticks + o1;
pthread_mutex_t *right = chopsticks + o2;
while (1)
{
usleep(rand() % 10);
if (pthread_mutex_trylock(left) != 0)
{
continue;
}
printf("Philosopher %c fetches chopstick %c\n", id, d1);
if (pthread_mutex_trylock(right) != 0)
{
pthread_mutex_unlock(left);
printf("Philosopher %c gives up chopstick %c\n", id, d1);
continue;
}
printf("Philosopher %c fetches chopstick %c\n", id, d2);
usleep(rand() % 10);
printf("Philosopher %c releases chopstick %c %c\n", id, d1, d2);
pthread_mutex_unlock(left);
pthread_mutex_unlock(right);
}
}
pthread_mutex_t *make_mutex(pthread_mutex_t *mutex)
{
int n = pthread_mutex_init(mutex, NULL);
if (n != 0)
{
perror("make_lock failed");
exit(1);
}
return mutex;
}
int main(int argc, char *argv[])
{
pthread_t a, b, c, d, e;
for (int i = 0; i < NUM; i += 1)
{
make_mutex(chopsticks + i);
}
pthread_create(&a, NULL, philosopher, "a51");
pthread_create(&b, NULL, philosopher, "b12");
pthread_create(&c, NULL, philosopher, "c23");
pthread_create(&d, NULL, philosopher, "d34");
pthread_create(&e, NULL, philosopher, "e45");
pthread_join(a, NULL);
pthread_join(b, NULL);
pthread_join(c, NULL);
pthread_join(d, NULL);
pthread_join(e, NULL);
return 0;
}
|
C
|
#include<stdio.h>
#include<time.h>
void insertion_sort(int array[], int length);
char* printArray(int* array, int length);
#define size sizeof(array) / sizeof(array[0])
int main()
{
// int array[] = {5, 2, 9, 4, 6, 1, 3, 8};
clock_t start, end;
double elapsed;
start = clock();
int array[1900];
for (int i = 1899; i > -1; i--)
{
int indexSize = size - i;
array[indexSize] = i;
}
int arraySize = size; //sizeof(array) / sizeof(array[0]);
insertion_sort(array, size);
end = clock();
elapsed = ((double)(end - start)) / (double)CLOCKS_PER_SEC;
printf("Processor time taken: %8.90f", elapsed);
}
//http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_19.html
char* printArray(int* array, int length)
{
char* value = malloc (sizeof(array));
for (int i = 0; i < length + 1; i++)
{
printf("%d ", array[i]);
value[i] = '0' + array[i];
}
printf("\n");
return value;
}
void insertion_sort(int array[], int length)
{
for( int j = 1; j < length; j++)
{
int key = array[j];
int i = j - 1;
while (i >= 0 && array[i] > key)
{
array[i + 1] = array[i];
i--;
array[i + 1] = key;
}
}
}
|
C
|
#include<stdio.h>
#include<unistd.h>
int main()
{
int i;
i=fork();
if(i==0)
{
printf("\n");
char *p[]={"./child.sh",NULL};
execvp("./child.sh",p);
}
else
{
printf("\n");
char *p[]={"./parent.sh",NULL};
execvp("./parent.sh",p);
}
return 0;
}
|
C
|
/* set.c -- Set routines for Khepera
* Created: Wed Nov 9 13:31:24 1994 by [email protected]
* Copyright 1994-1997, 2002 Rickard E. Faith ([email protected])
* Copyright 2002-2008 Aleksey Cheusov ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* \section{Set Routines}
*
* \intro The set implementation is similar to the hash table
* implementation, except that the set object does not associate a |datum|
* with a |key|. For sets, keys are called elements. All of the hash
* table functions are supported, with the addition of a membership test
* and several set operations.
*
* The underlying data structure is a hash table of prime length, with
* self-organizing linked lists \cite[pp.~398--9]{faith:Knuth73c} used for
* collision resolution. The hash table automatically grows as necessary
* to preserve efficient access.
*
*/
#include "maaP.h"
typedef struct bucket {
const void *elem;
unsigned long hash;
struct bucket *next;
} *bucketType;
typedef struct set {
#if MAA_MAGIC
int magic;
#endif
unsigned long prime;
unsigned long entries;
bucketType *buckets;
unsigned long resizings;
unsigned long retrievals;
unsigned long hits;
unsigned long misses;
unsigned long (*hash)(const void *);
int (*compare)(const void *, const void *);
int readonly;
} *setType;
static void _set_check(setType t, const char *function)
{
if (!t) err_internal(function, "set is null");
#if MAA_MAGIC
if (t->magic != SET_MAGIC)
err_internal(function,
"Bad magic: 0x%08x (should be 0x%08x)",
t->magic,
SET_MAGIC);
#endif
}
static set_Set _set_create(unsigned long seed,
set_HashFunction hash,
set_CompareFunction compare)
{
setType t;
unsigned long i;
unsigned long prime = prm_next_prime(seed);
t = xmalloc(sizeof(struct set));
#if MAA_MAGIC
t->magic = SET_MAGIC;
#endif
t->prime = prime;
t->entries = 0;
t->buckets = xmalloc(t->prime * sizeof(struct bucket));
t->resizings = 0;
t->retrievals = 0;
t->hits = 0;
t->misses = 0;
t->hash = hash ? hash : hsh_string_hash;
t->compare = compare ? compare : hsh_string_compare;
t->readonly = 0;
for (i = 0; i < t->prime; i++) t->buckets[i] = NULL;
return t;
}
/* \doc The |set_create| function initilizes a set object. Elements are
pointers to "void".
The internal representation of the set will grow automatically when an
insertion is performed and the table is more than half full.
The |hash| function should take a pointer to a |elem| and return an
"unsigned int". If |hash| is "NULL", then the |elem| is assumed to be a
pointer to a null-terminated string, and the function shown in
\grindref{fig:hshstringhash} will be used for |hash|.
The |compare| function should take a pair of pointers to elements and
return zero if the elements are the same and non-zero if they are
different. If |compare| is "NULL", then the elements are assumed to
point to null-terminated strings, and the |strcmp| function will be used
for |compare|.
Additionally, the |hsh_pointer_hash| and |hsh_pointer_compare| functions
are available and can be used to treat the \emph{value} of the "void"
pointer as the element. These functions are often useful for
maintaining sets of objects. */
set_Set set_create(set_HashFunction hash, set_CompareFunction compare)
{
return _set_create(0, hash, compare);
}
set_HashFunction set_get_hash(set_Set set)
{
setType t = (setType)set;
_set_check(t, __func__);
return t->hash;
}
set_CompareFunction set_get_compare(set_Set set)
{
setType t = (setType)set;
_set_check(t, __func__);
return t->compare;
}
static void _set_destroy_buckets(set_Set set)
{
unsigned long i;
setType t = (setType)set;
_set_check(t, __func__);
for (i = 0; i < t->prime; i++) {
bucketType b = t->buckets[i];
while (b) {
bucketType next = b->next;
xfree(b); /* terminal */
b = next;
}
}
xfree(t->buckets); /* terminal */
t->buckets = NULL;
}
static void _set_destroy_table(set_Set set)
{
setType t = (setType)set;
_set_check(t, __func__);
#if MAA_MAGIC
t->magic = SET_MAGIC_FREED;
#endif
xfree(t); /* terminal */
}
/* \doc |set_destroy| frees all of the memory associated with the set
object.
The memory used by elements is \emph{not} freed---this memory is the
responsibility of the user. However, a call to |set_iterate| can be
used to free this memory \emph{immediately} before a call to
|set_destroy|. */
void set_destroy(set_Set set)
{
setType t = (setType)set;
_set_check(t, __func__);
if (t->readonly)
err_internal(__func__, "Attempt to destroy readonly set");
_set_destroy_buckets(set);
_set_destroy_table(set);
}
static void _set_insert(set_Set set, unsigned long hash, const void *elem)
{
setType t = (setType)set;
unsigned long h = hash % t->prime;
bucketType b;
_set_check(t, __func__);
b = xmalloc(sizeof(struct bucket));
b->hash = hash;
b->elem = elem;
b->next = NULL;
if (t->buckets[h]) b->next = t->buckets[h];
t->buckets[h] = b;
++t->entries;
}
/* \doc |set_insert| inserts a new |elem| into the |set|. If the insertion
is successful, zero is returned. If the |elem| already exists, 1 is
returned.
If the internal representation of the set becomes more than half full,
its size is increased automatically. At present, this requires that all
of the element pointers are copied into a new set. Rehashing is not
required, however, since the hash values are stored for each element. */
int set_insert(set_Set set, const void *elem)
{
setType t = (setType)set;
unsigned long hashValue = t->hash(elem);
unsigned long h;
_set_check(t, __func__);
if (t->readonly)
err_internal(__func__, "Attempt to insert into readonly set");
/* Keep table less than half full */
if (t->entries * 2 > t->prime) {
setType new = _set_create(t->prime * 3, t->hash, t->compare);
unsigned long i;
for (i = 0; i < t->prime; i++) {
if (t->buckets[i]) {
bucketType pt;
for (pt = t->buckets[i]; pt; pt = pt->next)
_set_insert(new, pt->hash, pt->elem);
}
}
/* fixup values */
_set_destroy_buckets(t);
t->prime = new->prime;
t->buckets = new->buckets;
_set_destroy_table(new);
++t->resizings;
}
h = hashValue % t->prime;
if (t->buckets[h]) { /* Assert uniqueness */
bucketType pt;
for (pt = t->buckets[h]; pt; pt = pt->next)
if (!t->compare(pt->elem, elem)) return 1;
}
_set_insert(t, hashValue, elem);
return 0;
}
/* \doc |set_delete| removes an |elem| from the |set|. Zero is returned if
the |elem| was present. Otherwise, 1 is returned. */
int set_delete(set_Set set, const void *elem)
{
setType t = (setType)set;
unsigned long h = t->hash(elem) % t->prime;
_set_check(t, __func__);
if (t->readonly)
err_internal(__func__, "Attempt to delete from readonly set");
if (t->buckets[h]) {
bucketType pt;
bucketType prev;
for (prev = NULL, pt = t->buckets[h]; pt; prev = pt, pt = pt->next)
if (!t->compare(pt->elem, elem)) {
--t->entries;
if (!prev) t->buckets[h] = pt->next;
else prev->next = pt->next;
xfree(pt);
return 0;
}
}
return 1;
}
/* \doc |set_member| returns 1 if |elem| is in |set|. Otherwise, zero is
returned. */
int set_member(set_Set set, const void *elem)
{
setType t = (setType)set;
unsigned long h = t->hash(elem) % t->prime;
_set_check(t, __func__);
++t->retrievals;
if (t->buckets[h]) {
bucketType pt;
bucketType prev;
for (prev = NULL, pt = t->buckets[h]; pt; prev = pt, pt = pt->next)
if (!t->compare(pt->elem, elem)) {
if (!prev) {
++t->hits;
} else if (!t->readonly) {
/* Self organize */
prev->next = pt->next;
pt->next = t->buckets[h];
t->buckets[h] = pt;
}
return 1;
}
}
++t->misses;
return 0;
}
/* \doc |set_iterate| is used to iterate a function over every |elem| in
the |set|. The function, |iterator|, is passed each |elem|. If
|iterator| returns a non-zero value, the iterations stop, and
|set_iterate| returns. Note that the elements are in some arbitrary
order, and that this order may change between two successive calls to
|set_iterate|. */
int set_iterate(set_Set set,
int (*iterator)(const void *elem))
{
setType t = (setType)set;
unsigned long i;
int savedReadonly;
_set_check(t, __func__);
savedReadonly = t->readonly;
t->readonly = 1;
for (i = 0; i < t->prime; i++) {
if (t->buckets[i]) {
bucketType pt;
for (pt = t->buckets[i]; pt; pt = pt->next)
if (iterator(pt->elem)) {
t->readonly = savedReadonly;
return 1;
}
}
}
t->readonly = savedReadonly;
return 0;
}
/* \doc |set_iterate_arg| is used to iterate a function over every |elem|
in the |set|. The function, |iterator|, is passed each |elem|. If
|iterator| returns a non-zero value, the iterations stop, and
|set_iterate| returns. Note that the elements are in some arbitrary
order, and that this order may change between two successive calls to
|set_iterate|. */
int set_iterate_arg(set_Set set,
int (*iterator)(const void *elem, void *arg),
void *arg)
{
setType t = (setType)set;
unsigned long i;
int savedReadonly;
_set_check(t, __func__);
savedReadonly = t->readonly;
t->readonly = 1;
for (i = 0; i < t->prime; i++) {
if (t->buckets[i]) {
bucketType pt;
for (pt = t->buckets[i]; pt; pt = pt->next)
if (iterator(pt->elem, arg)) {
t->readonly = savedReadonly;
return 1;
}
}
}
t->readonly = savedReadonly;
return 0;
}
/* \doc |set_init_position| returns a position marker for some arbitary
first element in the set. This marker can be used with
|set_next_position| and |set_get_position|. */
set_Position set_init_position(set_Set set)
{
setType t = (setType)set;
unsigned long i;
_set_check(t, __func__);
for (i = 0; i < t->prime; i++) if (t->buckets[i]) {
t->readonly = 1;
return t->buckets[i];
}
return NULL;
}
/* \doc |set_next_position| returns a position marker for the next element
in the set. Elements are in arbitrary order based on their positions in
the hash table. */
set_Position set_next_position(set_Set set, set_Position position)
{
setType t = (setType)set;
bucketType b = (bucketType)position;
unsigned long i;
unsigned long h;
_set_check(t, __func__);
if (!b) {
t->readonly = 0;
return NULL;
}
if (b->next) return b->next;
for (h = b->hash % t->prime, i = h + 1; i < t->prime; i++)
if (t->buckets[i]) return t->buckets[i];
t->readonly = 0;
return NULL;
}
/* \doc |set_get_position| returns the element associated with the
|position| marker, or "NULL" if there is no such element. */
void *set_get_position(set_Position position)
{
bucketType b = (bucketType)position;
if (!b) return NULL;
return __UNCONST(b->elem); /* Discard const */
}
/* \doc |set_readonly| sets the |readonly| flag for the |set| to |flag|.
|flag| should be 0 or 1. The value of the previous flag is returned.
When a set is marked as readonly, self-organization of the
bucket-overflow lists will not take place, and any attempt to modify the
list (e.g., insertion or deletion) will result in an error. */
int set_readonly(set_Set set, int flag)
{
setType t = (setType)set;
int current;
_set_check(t, __func__);
current = t->readonly;
t->readonly = flag;
return current;
}
/* \doc |set_add| returns |set1|, which now contains all of the elements
in |set1| and |set2|. Only pointers to elements are copied, \emph{not}
the data pointed (this has memory management implications). The |hash|
and |compare| functions must be identical for the two sets. |set2| is
not changed. */
set_Set set_add(set_Set set1, set_Set set2)
{
setType t1 = (setType)set1;
setType t2 = (setType)set2;
unsigned long i;
_set_check(t1, __func__);
_set_check(t2, __func__);
if (t1->hash != t2->hash)
err_fatal(__func__,
"Sets do not have identical hash functions");
if (t1->compare != t2->compare)
err_fatal(__func__,
"Sets do not have identical comparison functions");
for (i = 0; i < t2->prime; i++) {
if (t2->buckets[i]) {
bucketType pt;
for (pt = t2->buckets[i]; pt; pt = pt->next)
set_insert(set1, pt->elem);
}
}
return set1;
}
/* \doc |set_del| returns |set1|, which now contains all of the elements in
|set1| other than those in |set2|. Only pointers to elements are
copied, \emph{not} the data pointed (this has memory management
implications). The |hash| and |compare| functions must be identical for
the two sets. |set2| is not changed. */
set_Set set_del(set_Set set1, set_Set set2)
{
setType t1 = (setType)set1;
setType t2 = (setType)set2;
unsigned long i;
_set_check(t1, __func__);
_set_check(t2, __func__);
if (t1->hash != t2->hash)
err_fatal(__func__,
"Sets do not have identical hash functions");
if (t1->compare != t2->compare)
err_fatal(__func__,
"Sets do not have identical comparison functions");
for (i = 0; i < t2->prime; i++) {
if (t2->buckets[i]) {
bucketType pt;
for (pt = t2->buckets[i]; pt; pt = pt->next)
set_delete(set1, pt->elem);
}
}
return set1;
}
/* \doc |set_union| returns a new set which is the union of |set1| and
|set2|. Only pointers to elements are copied, \emph{not} the data
pointed (this has memory management implications). The |hash| and
|compare| functions must be identical for the two sets. */
set_Set set_union(set_Set set1, set_Set set2)
{
setType t1 = (setType)set1;
setType t2 = (setType)set2;
set_Set set;
unsigned long i;
_set_check(t1, __func__);
_set_check(t2, __func__);
if (t1->hash != t2->hash)
err_fatal(__func__,
"Sets do not have identical hash functions");
if (t1->compare != t2->compare)
err_fatal(__func__,
"Sets do not have identical comparison functions");
set = set_create(t1->hash, t1->compare);
for (i = 0; i < t1->prime; i++) {
if (t1->buckets[i]) {
bucketType pt;
for (pt = t1->buckets[i]; pt; pt = pt->next)
set_insert(set, pt->elem);
}
}
for (i = 0; i < t2->prime; i++) {
if (t2->buckets[i]) {
bucketType pt;
for (pt = t2->buckets[i]; pt; pt = pt->next)
set_insert(set, pt->elem);
}
}
return set;
}
/* \doc |set_inter| returns a new set which is the intersection of |set1|
and |set2|. Only pointers to elements are copied, \emph{not} the data
pointed (this has memory management implications). The |hash| and
|compare| functions must be identical for the two sets. */
set_Set set_inter(set_Set set1, set_Set set2)
{
setType t1 = (setType)set1;
setType t2 = (setType)set2;
set_Set set;
unsigned long i;
int savedReadonly;
_set_check(t1, __func__);
_set_check(t2, __func__);
if (t1->hash != t2->hash)
err_fatal(__func__,
"Sets do not have identical hash functions");
if (t1->compare != t2->compare)
err_fatal(__func__,
"Sets do not have identical comparison functions");
set = set_create(t1->hash, t1->compare);
savedReadonly = t2->readonly;
t2->readonly = 1; /* save time on set_member */
for (i = 0; i < t1->prime; i++) {
if (t1->buckets[i]) {
bucketType pt;
for (pt = t1->buckets[i]; pt; pt = pt->next)
if (set_member(t2, pt->elem))
set_insert(set, pt->elem);
}
}
t2->readonly = savedReadonly;
return set;
}
/* \doc |set_diff| returns a new set which is the difference resulting from
removing every element in |set2| from the elements in |set1|. Only
pointers to elements are copied, \emph{not} the data pointed (this has
memory management implications). The |hash| and |compare| functions
must be identical for the two sets. */
set_Set set_diff(set_Set set1, set_Set set2)
{
setType t1 = (setType)set1;
setType t2 = (setType)set2;
set_Set set;
unsigned long i;
int savedReadonly;
_set_check(t1, __func__);
_set_check(t2, __func__);
if (t1->hash != t2->hash)
err_fatal(__func__,
"Sets do not have identical hash functions");
if (t1->compare != t2->compare)
err_fatal(__func__,
"Sets do not have identical comparison functions");
set = set_create(t1->hash, t1->compare);
savedReadonly = t2->readonly;
t2->readonly = 1; /* save time on set_member */
for (i = 0; i < t1->prime; i++) {
if (t1->buckets[i]) {
bucketType pt;
for (pt = t1->buckets[i]; pt; pt = pt->next)
if (!set_member(t2, pt->elem))
set_insert(set, pt->elem);
}
}
t2->readonly = savedReadonly;
return set;
}
/* \doc |set_equal| returns non-zero if |set1| and |set2| contain the same
number of elements, and all of the elements in |set1| are also in
|set2|. The |hash| and |compare| functions must be identical for the
two sets. */
int set_equal(set_Set set1, set_Set set2)
{
setType t1 = (setType)set1;
setType t2 = (setType)set2;
unsigned long i;
int savedReadonly;
_set_check(t1, __func__);
_set_check(t2, __func__);
if (t1->hash != t2->hash)
err_fatal(__func__,
"Sets do not have identical hash functions");
if (t1->compare != t2->compare)
err_fatal(__func__,
"Sets do not have identical comparison functions");
if (t1->entries != t2->entries) return 0; /* not equal */
savedReadonly = t2->readonly;
t2->readonly = 1; /* save time on set_member */
for (i = 0; i < t1->prime; i++) {
if (t1->buckets[i]) {
bucketType pt;
for (pt = t1->buckets[i]; pt; pt = pt->next)
if (!set_member(t2, pt->elem)) {
t2->readonly = savedReadonly;
return 0; /* not equal */
}
}
}
t2->readonly = savedReadonly;
return 1; /* equal */
}
int set_count(set_Set set)
{
setType t = (setType)set;
_set_check(t, __func__);
return t->entries;
}
/* \doc |set_get_stats| returns statistics about the |set|. The
|set_Stats| structure is shown in \grind{set_Stats}. */
set_Stats set_get_stats(set_Set set)
{
setType t = (setType)set;
set_Stats s = xmalloc(sizeof(struct set_Stats));
unsigned long i;
unsigned long count;
_set_check(t, __func__);
s->size = t->prime;
s->resizings = t->resizings;
s->entries = 0;
s->buckets_used = 0;
s->singletons = 0;
s->maximum_length = 0;
s->retrievals = t->retrievals;
s->hits = t->hits;
s->misses = t->misses;
for (i = 0; i < t->prime; i++) {
if (t->buckets[i]) {
bucketType pt;
++s->buckets_used;
for (count = 0, pt = t->buckets[i]; pt; ++count, pt = pt->next);
if (count == 1) ++s->singletons;
s->maximum_length = max(s->maximum_length, count);
s->entries += count;
}
}
if (t->entries != s->entries)
err_internal(__func__,
"Incorrect count for entries: %lu vs. %lu",
t->entries,
s->entries);
return s;
}
/* \doc |set_print_stats| prints the statistics for |set| on the specified
|stream|. If |stream| is "NULL", then "stdout" will be used. */
void set_print_stats(set_Set set, FILE *stream)
{
setType t = (setType)set;
FILE *str = stream ? stream : stdout;
set_Stats s = set_get_stats(t);
_set_check(t, __func__);
fprintf(str, "Statistics for set at %p:\n", set);
fprintf(str, " %lu resizings to %lu total\n", s->resizings, s->size);
fprintf(str, " %lu entries (%lu buckets used, %lu without overflow)\n",
s->entries, s->buckets_used, s->singletons);
fprintf(str, " maximum list length is %lu", s->maximum_length);
if (s->buckets_used)
fprintf(str, " (optimal is %.1f)\n",
(double)s->entries / (double)s->buckets_used);
else
fprintf(str, "\n");
fprintf(str, " %lu retrievals (%lu from top, %lu failed)\n",
s->retrievals, s->hits, s->misses);
xfree(s); /* rare */
}
|
C
|
/*
Reverse bits of a given 32 bits unsigned integer.
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596,
so return 964176192 which its binary representation is 00111001011110000010100101000000.
Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293,
so return 3221225471 which its binary representation is 10101111110010110010011101101001.
*/
uint32_t reverseBits(uint32_t n) {
/*
bitset<32> a(n);
string s=a.to_string();
reverse(s.begin(),s.end());
bitset<32> b(s);
return b.to_ulong();
*/
uint32_t res=0;
for(int i=0;i<32;i++){
res=(res<<1)+((n>>i)&1);
}
return res;
}
|
C
|
#include<stdio.h>
int main(){
int x;
printf("Which subjects did you pass\n");
printf("if passed maths enter the value 1\n");
printf("if passed science enter the value 2\n");
printf("if passed maths and science enter the value 3\n");
scanf("%d",&x);
if (x==1){
printf("You won 15 rupees\n");
printf("Congratulations on winning!!");
}
else if (x==2){
printf("You won 15 rupees\n");
printf("Congratulations on winning!!");
}
else if (x==3){
printf("You won 45 rupees\n");
printf("Congratulations on winning!!");
}
else{
printf("Please enter the correct value");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _gruppo
{
char* principale;
char** stringhe;
int nStringhe;
} gruppo;
int OrdinaCaratteri(const void* a, const void* b)
{
char uno[2];
char due[2];
uno[0] = *((char*) a);
due[0] = *((char*) b);
uno[1] = '\0'; due[1] = '\0';
return strcmp(uno, due);
}
int OrdinaStringhe(const void* a, const void* b)
{
char* uno = *((char**) a);
char* due = *((char**) b);
return strcmp(uno, due);
}
int OrdinaGruppi(const void* a, const void* b)
{
gruppo uno = *((gruppo*) a);
gruppo due = *((gruppo*) b);
return strcmp(uno.principale, due.principale);
}
char* AnagrammaPrincipale(char* stringa)
{
int len = strlen(stringa);
char* principale = malloc((len+1) * sizeof(char));
strncpy(principale, stringa, len+1);
qsort(principale, len, sizeof(char), OrdinaCaratteri);
return principale;
}
int CercaGruppo(gruppo* gruppi, int nGruppi, char* principale)
{
int trovato=0;
int i=0;
while(i<nGruppi && !trovato)
{
if(strcmp(gruppi[i].principale, principale) == 0) trovato=1;
else i++;
}
if(!trovato) i=-1;
return i;
}
int main()
{
int n; //n numero totale di stringhe
scanf("%d", &n);
gruppo* gruppi = malloc(n * sizeof(gruppo));
int nGruppi = 0;
//Leggo e memorizzo le stringhe
int i;
for(i=0; i<n; i++)
{
char* stringa = malloc(20 * sizeof(char));
scanf("%s", stringa);
char* principale = AnagrammaPrincipale(stringa);
int iGruppo = CercaGruppo(gruppi, nGruppi, principale);
if(iGruppo != -1)
{
//Esiste già un gruppo con quell'anagramma principale
free(principale);
int indiceInserimento = gruppi[iGruppo].nStringhe;
gruppi[iGruppo].stringhe[indiceInserimento] = stringa;
gruppi[iGruppo].nStringhe++;
}
else
{
//Non esiste ancora un gruppo con quell'anagramma principale
gruppi[nGruppi].principale = principale;
gruppi[nGruppi].nStringhe = 1;
gruppi[nGruppi].stringhe = malloc(n * sizeof(char*));
gruppi[nGruppi].stringhe[0] = stringa;
nGruppi++;
}
}
//Ordino array dei gruppi
qsort(gruppi, nGruppi, sizeof(gruppo), OrdinaGruppi);
//Ordino le stringhe di ogni gruppo, stampo e dealloco
for(i=0; i<nGruppi; i++)
{
free(gruppi[i].principale);
qsort(gruppi[i].stringhe, gruppi[i].nStringhe, sizeof(char*), OrdinaStringhe);
int j;
for(j=0; j < gruppi[i].nStringhe; j++)
{
printf("%s", gruppi[i].stringhe[j]);
if(j+1 < gruppi[i].nStringhe) printf(" ");
free(gruppi[i].stringhe[j]);
}
free(gruppi[i].stringhe);
if(i+1 < nGruppi) printf("\n");
}
free(gruppi);
return 0;
}
|
C
|
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/types.h>
#define LEN 256
int dir_tree(const char *path, int n)
{
int i;
struct dirent *dir;
char sub_dir[LEN];
DIR *dirp;
dirp = opendir(path);
if (dirp == NULL)
{
printf("path:%s\n", path);
perror("opendir failed");
return -1;
}
while (dir = readdir(dirp))
{
memset(sub_dir, 0, LEN);
strcat(sub_dir, path);
if (strcmp(dir->d_name, ".") && strcmp(dir->d_name, ".."))
{
for (i = 0; i < n; i++)
{
printf("\t");
}
printf("%s%s\n", path, dir->d_name);
}
if ((dir->d_type == DT_DIR) && strcmp(dir->d_name, ".") && strcmp(dir->d_name, ".."))
{
strcat(sub_dir, dir->d_name);
strcat(sub_dir, "/");
dir_tree(sub_dir, n + 1);
}
}
printf("\n");
return 0;
}
int main(int argc, char *argv[])
{
if (argc == 1)
dir_tree("./", 0);
else
dir_tree(argv[1], 0);
return 0;
}
|
C
|
/*
GaussianBlurMatrixGen: generate Gaussian Matrix[nxn] by given standard deviation(σ) and radius(r), (n = 2 * r + 1)
Gaussian distribution formula in two-dimensions: G(x, y) = 1 * (e ^ (-(x*x + y*y) / (2 * σ * σ))) / (2 * pi * σ * σ)
Gaussian distribution formula in one-dimensions: G(x) = 1 * (e ^ (-(x*x) / (2 * σ * σ))) / (2 * pi * σ * σ)^(1/2)
*/
#include <stdio.h>
#include <math.h>
#include "PreDefine.h"
static const double PI = 3.14159265358979;
EXPORT int GetGaussianMatrixIn2d(float matrix[], int matrixlen, float sd, int r)
{
int len = (r + r + 1) * (r + r + 1);
if (len > matrixlen)
return 1;
// 8/8 section
for (int x = 0; x <= r; x++) {
for (int y = 0; y <= x; y++) {
matrix[(r + r + 1) * (r + y) + x + r] = (float)(exp(-(y * y + x * x) / (2 * sd * sd)) / (2 * PI * sd * sd));
}
}
// 8/8 -> 1/8 section
for (int x = 0; x <= r; x++) {
for (int y = 1; y <= x; y++) {
matrix[(r + r + 1) * (r - y) + x + r] = matrix[(r + r + 1) * (r + y) + x + r];
}
}
// 8/8 + 1/8 -> 5/8 + 4/8
for (int x = 1; x <= r; x++) {
for (int y = -x; y <= x; y++) {
matrix[(r + r + 1) * (r + y) + r - x] = matrix[(r + r + 1) * (r + y) + r + x];
}
}
// 1/8 -> 2/8 section
for (int y = 0; y <= r; y++) {
for (int x = 0; x < r - y; x++) {
matrix[(r + r + 1) * y + x + r] = matrix[(r + r + 1) * (r - x) + r - y + r];
}
}
// 2/8 -> 3/8 section
for (int y = 0; y <= r; y++) {
for (int x = 1; x < r - y; x++) {
matrix[(r + r + 1) * y + r - x] = matrix[(r + r + 1) * y + r + x];
}
}
// 2/8 + 3/8 -> 7/8 + 6/8
for (int y = 1; y <= r; y++) {
for (int x = -y + 1; x < y; x++) {
matrix[(r + r + 1) * (r + y) + r + x] = matrix[(r + r + 1) * (r - y) + r + x];
}
}
float total = 0.0f;
for (int i = 0; i < len; i++) {
total += matrix[i];
}
for (int i = 0; i < len; i++) {
matrix[i] /= total;
}
return 0;
}
EXPORT int GetGaussianMatrixIn1d(float matrix[], int matrixlen, float sd, int r)
{
int len = (r + r + 1);
if (len > matrixlen)
return 1;
for (int x = 0; x <= r; x++) {
matrix[x + r] = (float)(exp(-(x * x) / (2 * sd * sd)) / pow(2 * PI * sd * sd, 1 / 2));
}
for (int x = 0; x < r; x++) {
matrix[x] = matrix[r + r - x];
}
float total = 0.0f;
for (int i = 0; i < len; i++) {
total += matrix[i];
}
for (int i = 0; i < len; i++) {
matrix[i] /= total;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
int x,y,m,n,a,b,xAB,yAB,xBC,yBC,xCA,yCA,AB_BC,BC_CA,CA_AB;
printf("Пожалуйста, введите координаты вершин треугольника АBC через пробел:\n");
printf ("A = ");
scanf("%d %d",&x,&y);
printf ("B = ");
scanf("%d %d",&m,&n);
printf ("C = ");
scanf("%d %d",&a,&b);
xAB=m-x; yAB=n-y; xBC=a-m; yBC=b-n; xCA=x-a; yCA=y-b;
AB_BC=xAB*xBC+yAB*yBC; BC_CA=xBC*xCA+yBC*yCA; CA_AB=xCA*xAB+yCA*yAB;
if ((AB_BC==0)&&(BC_CA==0)&&(CA_AB==0)) {printf("Вы ввели точку.");return 0;}
if ((AB_BC==0)||(BC_CA==0)||(CA_AB==0)) {printf("Ваш треугольник является прямоугольным.");return 0;}
else printf("Ваш треугольник не является прямоугольным.");
return 0;
}
|
C
|
/*******************************************************************************
Summary:
Command line program for printing VideoCore log messages
or assertion logs messages
Licensing:
Copyright (c) 2022, Joanna Rousseau - Raspberry Pi Ltd All rights reserved.
*******************************************************************************/
#include <assert.h>
#include <sys/types.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <time.h>
#include <unistd.h>
/*******************************************************************************
Typedef & Enums & structs & Const
*******************************************************************************/
int boundary = 16; /*memory boundary in relation to counting how misaligned
an address is from this boundary*/
bool continuously_check_logs =
false; /*User decides whether they want the program to continuously check for
new logs coming in*/
enum Log_requested { /*used to parse which logs the user wants printing*/
log_unknown = -1,
log_msg = 0,
log_assert = 1,
};
/* STRUCTS headers below describe how VC arranges it's data within the regions
of interest:
NOTE: Since the VC might have a different memory model from the host (32-bit vs
64-bit) structs values need to be of the same size. This code defines
fixed-width types that match the VC memory types*/
/*Individual entries header:
Asserts/msg individual messages each have a header prefixing it to describe
it's state for easy reading */
typedef struct {
int32_t time; // time log produced in centi format
uint16_t seq_num; // if two entries have same timestamp then
// this seq num differentiates them
uint16_t size; // size of entire log entry = this header + data
} Individual_msg_hdr_t;
/*Individual entries are found within a region of VC's memory, this structs
is found at the start ( the header) of this region:
In VC memory, before each 'message type' such as assert or msg,
there is a header that describes what is within this section of VC memory and
the start and end of the messages within it. This region works like a circular
buffer*/
typedef struct {
uint8_t name[4];
uint32_t start; // circular buffer start for this type of message (
// assert/msg/etc):defined when the log is created and
// does not change
uint32_t end; // circular buffer end :defined when the log is created
// and does not change
uint32_t write; // Points to where VC will write the next msg
uint32_t read; /* Points to the first message (oldest message written by
VC) for reading; the read pointer gets updated when the circular buffer is
full and wrappes around : VC wipes the oldest message with it's latest msg*/
Individual_msg_hdr_t header; // Before each message there is a header that
// holds information about the message
} VC_region_requested_hdr_t;
/*This struct describes the whole of VC memory:
This struct is found at the beginning of VC memory and provide a table of
contents of where each message type ( assert/ task/ msg) and other info is
found*/
typedef struct {
uint8_t padding[32]; // VC has extra information which we don't need so just
// adding padding
int32_t type_assert;
uint32_t ptr_log_assert;
int32_t type_msg;
uint32_t ptr_log_msg;
int32_t type_task;
uint32_t ptr_log_task;
} VC_Table_of_contents_t;
// this struct is used to save ( and keep together) the start and end of a memory
// region so the details can be sent to functions that check a pointer doesn't wrap
//around within the circular buffer
typedef struct {
char *start; // start of region in memory
char *end; // start of region in memory
} Mem_region_t;
// this struct keeps the same location in memory but both in physical VC memory +
//virtual mmaped region location
typedef struct {
VC_Table_of_contents_t *actual; // Physical location in memory of all logs
// start (with maskAliasing)
VC_Table_of_contents_t
*virtual; // Virtual ( mmaped) location in memory of all logs start
} phy_and_virt_toc_t;
/******************************************************************************
Function declarations
******************************************************************************/
/*Check and parse arguments to select either log msg or assert returns -1 if
* not type known*/
static enum Log_requested parse_cmd_args(int argc, char *argv[]);
/*Get start of VC memory where all logs are found and the size of all the logs:
* from Device Tree*/
static bool get_logs_start_and_size_from_DT(VC_Table_of_contents_t **logStart,
size_t *all_logs_size);
/*Clear top two bits - which are the VideoCore aliasing*/
static void *maskVCAliasing(uint32_t val);
/*Find offset in Actual physical memory and apply it to within the mmaped
* region*/
static void *get_loc_in_virtual_mem(const phy_and_virt_toc_t *toc,
void *curr_pos);
/*Combination of the above two functions : clear top two bits and offset the
* pointer in the correct location within virtual memory */
static void *correct_to_be_in_virtual_loc(const phy_and_virt_toc_t *toc,
uint32_t val);
/*Look inside the header/struct that prefixes all logs (Like a table of
content) to find the start of the type of logs the user requested: Function
returns the header of the message type chosen ( msg or assert)*/
static VC_region_requested_hdr_t *find_hdr_requested_log(
const phy_and_virt_toc_t *toc, enum Log_requested type);
/*Make a copy of the txt keeping in mind it might wrap around within the
buffer - correct if this is the case*/
static bool mem_check_and_copy(char *dest, const char *src, Mem_region_t *region,
size_t size_to_copy);
/*Checks if the location where VC is writing it's new message (end all
messages) is within the space in memory occupied by the current message we
are reading, this happens when we copy during a write by VC*/
static bool vc_write_ptr_within_current_msg(
const Individual_msg_hdr_t *hrd_msg_reading, char *VC_write_ptr,
Mem_region_t *buffer_region);
/*Increment the pointer by offset, wrapping it when it reaches end of buffer
Function returns the location of the new pointer which can be before the
curr_position */
static char *increment_ptr_within_region(size_t offset, Mem_region_t *region,
const char *curr_position);
/*Parse assert (-a) text*/
static bool parse_and_print_assert_msg(char *txt, size_t size_of_text,
int32_t time);
/* Memcpy with unaligned addresses: In certain architectures, memcpy fails if
src address is not a aligned to a boundary at the start of memcpy (and at the
end of the region copied)
dest & src MUST have the same alignment */
static void memcpy_vc_memory(char *restrict dest, const volatile char *restrict src,
size_t n);
/******************************************************************************
Main Function
******************************************************************************/
int32_t main(int32_t argc, char *argv[]) {
// parse command line arguments to know which log we want to print
enum Log_requested type_msg_chosen = parse_cmd_args(argc, argv);
if (type_msg_chosen < 0) {
fprintf(stderr,
"Usage:\n\t%s [-f] <-m|-a>\n\t%s [--follow] <--msg|--assert>\n",
argv[0], argv[0]);
return EXIT_FAILURE;
}
/* Get Log Start and Log Size from device tree and change from bigEndian to
* littleEndian */
VC_Table_of_contents_t *logs_start = NULL;
size_t all_logs_size = 0;
if (!get_logs_start_and_size_from_DT(&logs_start, &all_logs_size)) {
fprintf(stderr,
"Could not read from Device Tree log starts and log size\n");
return EXIT_FAILURE;
}
/* File descriptor for : MMAP using toc and all_logs_size*/
const char *const dev_mem_path =
"/dev/mem"; // make sure the pointer and value don't change
int32_t dev_mem = open(dev_mem_path, O_RDONLY);
if (dev_mem == -1) {
fprintf(stderr, "Could not open dev/mem: %s\n", strerror(errno));
return EXIT_FAILURE;
}
/* Get a virtual memory ptr so point at the same adress as VC physical
address (where all logs begin)*/
char *mmaped_all_logs_hdr = mmap(NULL, all_logs_size, PROT_READ, MAP_PRIVATE,
dev_mem, (uintptr_t)logs_start);
/* file descriptor can be immediately closed without affecting mmap */
close(dev_mem);
if (mmaped_all_logs_hdr == MAP_FAILED) {
fprintf(stderr, "Could not map VC memory: %s\n", strerror(errno));
return EXIT_FAILURE;
}
// Save start of all logs in physical memory and the virtual mmaped adress
// so we can later calculate offsets within physical memory
phy_and_virt_toc_t toc = {logs_start,
(VC_Table_of_contents_t *)mmaped_all_logs_hdr};
phy_and_virt_toc_t *toc_ptr = &toc;
// FIND the pointer to the beginning of header for type of msg we want to
// print ( msg or assert)
const VC_region_requested_hdr_t *selected_log_header =
find_hdr_requested_log(toc_ptr, type_msg_chosen);
if (!selected_log_header)
goto cleanup;
/* from that header : Get the pointer that points to the very last message
(which is the current VC write position) before copying the buffer directly
from physical VC memory AND offset its location within the mmaped region*/
char *end_all_msgs =
correct_to_be_in_virtual_loc(toc_ptr, selected_log_header->write);
/* AND get the start and end of the buffer*/
const char *const buffer_start =
correct_to_be_in_virtual_loc(toc_ptr, selected_log_header->start);
const char *const buffer_end =
correct_to_be_in_virtual_loc(toc_ptr, selected_log_header->end);
/*check there was no issue finding the locations of each pointer within the
* mmaped region*/
if (!end_all_msgs || !buffer_start || !buffer_end)
goto cleanup;
/* COPY & PARSE:
Malloc space so we can copy and parse the selected logs:*/
/* copy the current state of 'circular buffer' that holds the logs that user
* selected to parse:*/
/*Buffer_start can be an unaligned address (in certain architectures this
causes a bus error as the address is io mapping); So to copy the buffer we
might need to make adjustements so mallocing a full boundary extra to give us
space for this*/
size_t buffer_size = buffer_end - buffer_start;
void *const circular_buffer = (void *)malloc(buffer_size + boundary);
if (!circular_buffer) {
fprintf(stderr, "Failed to allocate buffer for VC msgs\n");
goto cleanup;
}
/*Count number of bytes buffer_start is misaligned by within boundary in
memory*/
size_t size_unaligned = (size_t)buffer_start % boundary;
/*align circular_buffer to be the same as buffer_start and keep track of where
* start_circular_buffer is located*/
char *const start_circular_buff = ((char *)circular_buffer + size_unaligned);
/*then: Copy circular buffer so we can parse it */
memcpy_vc_memory(start_circular_buff, buffer_start, buffer_size);
/*Store start and end of buffer in struct ( so can pass in functions)*/
Mem_region_t buff = {start_circular_buff, start_circular_buff + buffer_size};
Mem_region_t *const buffer_details = &buff;
/* Now we copied the current state, we need to parse the messages*/
/*user might choose option to constinously search for new logs. If this is
* false the below loop will only run once; Else we start again from where we
* last read a message successfully*/
int num_times_checked_if_new_logs = 0; /*counts number of times we copied
buffer and read logs*/
bool print_logs =
true; /*Set to true at first and changes at the end of the loop depending
on whether the user decided to keep checking for new messages */
const Individual_msg_hdr_t
*header_current_msg = NULL; /*header of first message to parse*/
const size_t size_of_msg_header =
sizeof(Individual_msg_hdr_t); /*Individual messages each have headers that
are always the same size, which we will
need to skip to parse the text*/
char *copied_text = NULL; /*pointer to beginning of each individual message to parse*/
/*PARSE all individual messages from the copied state of circular buffer (one message at
a time) and if the user selected to continuously check for further messages arriving,
keep looping indefinitely waiting for new messages to arrive*/
while (print_logs) {
/*PREP FOR PARSING:*/
/*If this is the first time we parse the circular buffer:*/
if (num_times_checked_if_new_logs == 0) {
/* re-read VC memory to get the most recent 'start of first message' to
* parse the buffer:*/
header_current_msg =
correct_to_be_in_virtual_loc(toc_ptr, selected_log_header->read);
if (!header_current_msg) {
fprintf(stderr,
"Failed to offset correct position within mmaped region");
free(circular_buffer);
goto cleanup;
}
/* adjust relevant pointers to point at correct offset in circular_buffer
* (as currently pointing to physical mem)*/
header_current_msg =
(Individual_msg_hdr_t *)((char *)header_current_msg - buffer_start +
start_circular_buff);
end_all_msgs = end_all_msgs - buffer_start + start_circular_buff;
}
/*If we already parsed circular buffer at least once and need to copy the
new state of circular_buffer:*/
else {
/*sleep to give CPU time to do other tasks as this is an endless loop*/
nanosleep((const struct timespec[]){{0, 1000000L}}, NULL);
/*wipe all content in circular_buffer so we can re-copy it and get its new
* current state*/
memset(start_circular_buff, 0, buffer_size);
/*remember header_current_msg's (from the previous iteration) position
* that we didn't parse*/
size_t offset_of_current_read_pos =
(char *)header_current_msg - start_circular_buff;
/*find current VC write position ie current end of all messages*/
end_all_msgs =
correct_to_be_in_virtual_loc(toc_ptr, selected_log_header->write);
/*find it's offset position in circular_buffer*/
size_t offset_of_current_write_pos = end_all_msgs - buffer_start;
end_all_msgs = start_circular_buff + offset_of_current_write_pos;
/*Calculate size between current read and end_all_msgs ie the size of
* buffer to copy for parsing:*/
size_t size_copying;
/*and copy the new logs we didn't parse in previous iteration:*/
/* if we can copy 'header_current_msg' up to 'end_all_msgs' without
* wrapping around in circular buffer then do just one memcpy*/
if ((char *)header_current_msg < end_all_msgs) {
size_copying = end_all_msgs - (char *)header_current_msg;
memcpy_vc_memory(start_circular_buff + offset_of_current_read_pos,
buffer_start + offset_of_current_read_pos,
size_copying);
}
/*if the new logs wrap around in the buffer*/
else {
/*count how much we copy until reaching end of buffer and copy that
* first*/
size_copying = buff.end - (char *)header_current_msg;
size_t left_in_buffer = buff.end - (char *)header_current_msg;
memcpy_vc_memory(start_circular_buff + offset_of_current_read_pos,
buffer_start + offset_of_current_read_pos,
left_in_buffer);
/*then from start of buffer to the write position*/
size_copying += (end_all_msgs - buff.start);
memcpy_vc_memory(start_circular_buff, buffer_start,
offset_of_current_write_pos);
}
}
/*PARSE Circular buffer:*/
/* if the start of the message matches the end of all messages, VC has no
* messages to display currently*/
if ((char *)header_current_msg == end_all_msgs) {
/*if the user didn't choose the option to keep waiting until we get a
* message then we need to exit now:*/
if (!continuously_check_logs) {
fprintf(stdout, "No messages available\n");
free(circular_buffer);
goto cleanup;
}
/*else we just let the code skip to the next iteration of this while loop
and increment the tracker of times we read circular_buffer for parsing*/
}
/*Parse individual log messages until we reach the current write position
* (ie end of all messages currently in this state of circular_buffer)*/
while ((char *)header_current_msg != end_all_msgs) {
/* make a copy of the header details so we can access the size of the text
* (the header may wrap around the buffer)*/
char header[size_of_msg_header];
if (!mem_check_and_copy(header, (char *)header_current_msg,
buffer_details, size_of_msg_header))
break;
Individual_msg_hdr_t *temp_header = (Individual_msg_hdr_t *)header;
/* size=0 usually indicates a message that is still being written by VC so
at present we assume it is the last message and exit OR if end_all_message
is between the start and end of the current message: then the current
message is corrupted (VC is currently writting to it and has not yet
updated the end of message pointer)*/
if (temp_header->size == 0 ||
vc_write_ptr_within_current_msg(header_current_msg, end_all_msgs,
buffer_details))
break;
/* get the pointer to the start of the text we want to parse:
header or 'following text' might have wrapped around in buffer (text is
right after header)*/
const char *ptr_text = increment_ptr_within_region(
size_of_msg_header, buffer_details, (char *)header_current_msg);
if (!ptr_text)
break;
size_t size_of_text = temp_header->size - size_of_msg_header;
/* if the type of message chosen is msg, part of that text is logging
level which we don't need, so we need to remove this from the size and
move ptr to the correct 'start of text positions'*/
if (type_msg_chosen == log_msg) {
size_of_text -= sizeof(uint32_t);
ptr_text = increment_ptr_within_region(sizeof(uint32_t), buffer_details,
ptr_text);
}
/* We need to store the full txt into a temp variable as:
A)we need to make sure msg is null terminate in case of a corruption
during read so can parse it
B)can walk the string to parse it without worrying about wrapping around
buffer
*/
/* if this isn't the first time we parse the individual msg we need to free
the previous copied text*/
if (copied_text)
free(copied_text);
char *copied_text = (char *)calloc(size_of_text, sizeof(char));
if (!copied_text)
break;
if (!mem_check_and_copy(copied_text, ptr_text, buffer_details, size_of_text))
break;
/* parse copied text:
if command argv is -a or assert*/
if (type_msg_chosen == log_assert) {
if (!parse_and_print_assert_msg(copied_text, size_of_text,
header_current_msg->time))
// we assume here if one failed it means there was a corruption
// and we should exit
break;
}
/*if command argv is -m or msg */
else if (type_msg_chosen == log_msg)
/* Format of the data in VC for msg after header is:
-32 bit logging level ( so we will use sizeof(uint32_t) to skip over
this)
-null terminated message*/
fprintf(stdout, "%06i.%03i: %.*s\n", header_current_msg->time / 1000,
header_current_msg->time % 1000, (int)size_of_text,
copied_text);
// find the next message
header_current_msg = (Individual_msg_hdr_t *)((char *)header_current_msg +
header_current_msg->size);
}
// if we haven't freed copied_text during the while loop above then free it
if (copied_text)
free(copied_text);
/*This is increased to keep track of how many times we have checked for new
* logs (allowing the user to ask for the program to keep checking for new
* messages)*/
num_times_checked_if_new_logs++;
/*if the user didn't select the follow option, 'continuously_check_logs' is
* false and the loop ends here*/
print_logs = continuously_check_logs;
}
free(circular_buffer);
cleanup:
munmap(mmaped_all_logs_hdr, all_logs_size);
return EXIT_SUCCESS;
}
/*******************************************************************************
FUNCTIONS
*******************************************************************************/
enum Log_requested parse_cmd_args(int argc, char *argv[]) {
/*Parse argv commands to select either log message or log assert */
int assert = 0;
int msg = 0;
/*Optionally, the user might choose to continuously wait for new logs and parse
* them*/
int follow = 0;
struct option long_options[] = {/* If either the long or short option is
chosen we set the above ints to 1 */
{"a", no_argument, &assert, 1},
{"assert", no_argument, &assert, 1},
{"m", no_argument, &msg, 1},
{"msg", no_argument, &msg, 1},
{"f", no_argument, &follow, 1},
{"follow", no_argument, &follow, 1},
{0, 0, 0, 0}};
while (getopt_long_only(argc, argv, "", long_options, NULL) != -1)
;
/*set the bool that will later determine if we continuously check for new
* logs*/
continuously_check_logs = follow;
/* If the user didn't choose between 'assert' of 'msg' logs :*/
if (!(assert ^ msg))
return log_unknown;
return assert ? log_assert : log_msg;
}
/*****************************************************************************/
static bool get_logs_start_and_size_from_DT(VC_Table_of_contents_t **logs_start,
size_t *all_logs_size) {
bool ret = false;
if (!logs_start || !all_logs_size)
goto exit;
/*VideoCore logs start and size can be found in the device tree:*/
const char *const filename = "/proc/device-tree/chosen/log";
FILE *fileptr = fopen(filename, "r");
if (!fileptr)
goto exit;
#define NVALS 2
uint32_t vals[NVALS];
if (fread(vals, sizeof(uint32_t), NVALS, fileptr) != NVALS)
goto cleanup;
/*convert values between host and network byte order*/
*logs_start = (VC_Table_of_contents_t *)((uintptr_t)htonl(vals[0]));
*all_logs_size = htonl(vals[1]);
ret = true;
cleanup:
fclose(fileptr);
exit:
return ret;
}
/*****************************************************************************/
static VC_region_requested_hdr_t *find_hdr_requested_log(
const phy_and_virt_toc_t *toc, enum Log_requested type) {
uint32_t val;
if (!toc)
return NULL;
/* find the start to the mmaped region (get the table of contents)
and find in that table ( structure that holds the start of all types of
messages) the address of what the user chose ( msg/ assert)*/
switch (type) {
case log_assert:
val = toc->virtual->ptr_log_assert;
break;
case log_msg:
val = toc->virtual->ptr_log_msg;
break;
default:
return NULL;
}
/*This pointer is currently pointing to the physical memory of VC :
however we need the location within the mmaped region and we need to correct
the top two bits*/
return correct_to_be_in_virtual_loc(toc, val);
}
/*******************************************************************************/
static void *correct_to_be_in_virtual_loc(const phy_and_virt_toc_t *toc,
uint32_t val) {
if (!toc || !val)
return NULL;
/*Mask top two bits of that address: Top two bits of pointer are VC aliasing
* so we need to clear them*/
void *result = maskVCAliasing(val);
/*Get offset withn physical memory and add this to start of mmaped region*/
result = get_loc_in_virtual_mem(toc, result);
return result;
}
/*******************************************************************************/
static void *maskVCAliasing(uint32_t val) {
return (void *)((uintptr_t)(val & 0x3fffffffU));
}
/*******************************************************************************/
static void *get_loc_in_virtual_mem(const phy_and_virt_toc_t *toc,
void *curr_pos) {
if (!toc || !curr_pos)
return NULL;
// Get offset in physical memory ( toc->actual - current position)
// then add that to the beginning of the virtual memory
return ((char *)toc->virtual + ((char *)curr_pos - (char *)toc->actual));
}
/*******************************************************************************/
bool mem_check_and_copy(char *dest, const char *src, Mem_region_t *region,
size_t size_to_copy) {
if (!src || !region)
return false;
size_t left_in_buffer = region->end - src;
// check if all text doesn't wrap around within the region
if (size_to_copy <= left_in_buffer)
memcpy(dest, src, size_to_copy);
// else we need to copy first half message up to end region and then from
// start up to end of text
else {
memcpy(dest, src, left_in_buffer);
memcpy(dest + left_in_buffer, region->start, size_to_copy - left_in_buffer);
}
return true;
}
/******************************************************************************/
char *increment_ptr_within_region(size_t offset, Mem_region_t *region,
const char *curr_position) {
if (!region || !curr_position)
return NULL;
size_t left_in_buffer = region->end - curr_position;
while (left_in_buffer < offset) {
offset -= (region->end - curr_position);
curr_position = region->start;
left_in_buffer = region->end - curr_position;
}
return ((char *)curr_position + offset);
}
/******************************************************************************/
bool parse_and_print_assert_msg(char *txt, size_t size_of_text, int32_t time) {
/* Format of the data in VC for asserts after header is:
-null terminated filename
-32 bit line numb
-null terminated assertion condition
*/
// make copy of text as we will walk the copied variable to fetch the next
// data ( linenbr, cond_str)
char *subsequent_data = txt;
/* move past the first null terminated string to get to next
* data->linenumber*/
size_t filename_len = strnlen(txt, size_of_text);
if (filename_len == size_of_text) {
fprintf(stderr, "Issue with length of the log assert message\n");
return false;
}
subsequent_data += (filename_len + 1);
// save linenumber and move past linenumber
uint32_t linenumber;
memcpy(&linenumber, subsequent_data, sizeof(linenumber));
subsequent_data += sizeof(linenumber);
// the next variable to save is a null terminated string ( so even if there
// is data after this, we can just save it as is)
char *cond_str = subsequent_data;
fprintf(stdout,
"%06i.%03i: assert( %s ) failed; %s line %d\n----------------\n",
time / 1000, time % 1000, cond_str, txt, linenumber);
return true;
}
/*****************************************************************************/
static bool vc_write_ptr_within_current_msg(
const Individual_msg_hdr_t *hrd_msg_reading, char *vc_write_ptr,
Mem_region_t *buffer_region) {
/*During a copy we might have caught a message that is currently being
written by VC, this means VC hasn't updated it's write pointer ( which is the
end of all our messages we want to read) and we will have a corrupted
message*/
if (!hrd_msg_reading || !vc_write_ptr || !buffer_region)
return false;
// if header or text wrapped the pointer to the end of the message we are
// readign might be before the start of it
char *end_msg_reading = increment_ptr_within_region(
(size_t)hrd_msg_reading->size, buffer_region, (char *)hrd_msg_reading);
if (!end_msg_reading)
return false;
// Now we know where the start and end of the message pointers are witin the
// buffer, we need to check where the VC_write_ptr is relative to this
// In scenario header or text has wrapped: write pointer cannot be between
// start of region and end of messages OR start of message and end of buffer
if (vc_write_ptr < end_msg_reading || vc_write_ptr > (char *)hrd_msg_reading)
return false;
// In scenario header or text has not wrapped, if the write_ptr is within
// start and end of message
else if (vc_write_ptr > (char *)hrd_msg_reading &&
vc_write_ptr < end_msg_reading)
return false;
return true;
}
/********************************************************************************/
/* Note: gcc with -O2 or higher may replace most of this code with memcpy */
/* which causes a bus error when given an insufficiently aligned mmap-ed buffer */
/* Using volatile disables that optimisation */
/********************************************************************************/
static void memcpy_vc_memory(char *restrict dest, const volatile char *restrict src,
size_t n) {
// Calculate non-boundary aligned bytes at start/end of region
size_t src_offset = (uintptr_t)src % boundary;
size_t bytes_until_boundary = src_offset ? boundary - src_offset : 0;
size_t bytes_over_end_boundary = (uintptr_t)(src + n) % boundary;
// Manually copy bytes before first boundary
size_t bytes_to_manually_copy =
n < bytes_until_boundary ? n : bytes_until_boundary;
n -= bytes_to_manually_copy;
while (bytes_to_manually_copy--) {
*dest = *src++;
dest++;
}
// return if we copied all of n
if (!n)
return;
// memcpy centre region starting/ending on boundaries
int bytes_to_memcpy = n - bytes_over_end_boundary;
if (bytes_to_memcpy) {
memcpy(dest, (const void *)src, bytes_to_memcpy);
dest += bytes_to_memcpy;
src += bytes_to_memcpy;
n -= bytes_to_memcpy;
}
// Manually copy bytes after last boundary
n -= bytes_over_end_boundary;
while (bytes_over_end_boundary--) {
*dest = *src++;
dest++;
}
}
/*****************************************************************************/
|
C
|
#include <stdio.h>
int main(void) {
int n, a, b, sum, t, ans = 0;
scanf("%d %d %d", &n, &a, &b);
for(int i = 1; i <= n; i++){
t = i;
sum = 0;
while(t > 0){
sum += t % 10;
t /= 10;
}
if(a <= sum && sum <= b) {
ans += i;
}
}
printf("%d", ans);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int i,a[10],len,element,pos;
printf("Program to insert element into array:");
/*inputting the array*/
printf("\nEnter the size of the array:");
scanf("%d",&len);
for(i=0;i<len;i++)
{
printf("Enter the element:");
scanf("%d",&a[i]);
}
/*inserting the element*/
printf("Enter the element and position to be inserted:");
scanf("%d %d",&element,&pos);
for(i=(len-1);i>=(pos-1);i--)
{
a[i+1]=a[i];
}
a[pos-1]=element;
/*Output*/
for(i=0;i<=len;i++)
{
printf("%d \t",a[i]);
}
}
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
int num = 1;
while (num != 0)
{
printf("num = ? (0 : 종료) : ");
scanf("%d", &num);
if (num < 0)
{
// 음수면 continue 수행, 루프의 선두로 복귀
printf("num : Negative number ! \n\n");
continue;
}
printf("Squareroot of %d = %f \n\n", num, sqrt(num));
}
printf("The end \n");
}
|
C
|
#include <stdio.h>
#include <sys/time.h>
#include <math.h>
#include "micromouse.h"
#include "position.h"
/**
* i_pos, i_vel, i_acc: initial position, velocity and acceleration
* status: the micromouse data
*/
void init_pos(Vec3 i_pos, Vec3 i_vel, Vec3 i_acc,
Vec3 i_ang, Vec3 i_ang_vel, Vec3 i_ang_acc,
struct Micromouse* status)
{
// ms to s
float ts = status->time_step / 1000.0f;
status->prev_pose.pos.x = status->cur_pose.pos.x = i_pos.x + i_vel.x * ts + 0.5f * i_acc.x * ts * ts;
status->prev_pose.pos.y = status->cur_pose.pos.y = i_pos.y + i_vel.y * ts + 0.5f * i_acc.y * ts * ts;
status->prev_pose.pos.z = status->cur_pose.pos.z = i_pos.z + i_vel.z * ts + 0.5f * i_acc.z * ts * ts;
status->prev_pose.ang.x = status->cur_pose.ang.x = i_ang.x + i_ang_vel.x * ts + 0.5f * i_ang_acc.x * ts * ts;
status->prev_pose.ang.y = status->cur_pose.ang.y = i_ang.y + i_ang_vel.y * ts + 0.5f * i_ang_acc.y * ts * ts;
status->prev_pose.ang.z = status->cur_pose.ang.z = i_ang.z + i_ang_vel.z * ts + 0.5f * i_ang_acc.z * ts * ts;
status->prev_time_stamp = status->sensor_data.time_stamp;
}
/**
* m: micrmouse struct containing the micro mouse data
*/
void update_pos(struct Micromouse* m)
{
// updating the previous pose value
m->prev_pose = m->cur_pose;
// ms to s
float java = (m->sensor_data.time_stamp - m->prev_time_stamp) / 1000;
// float c = m->time_step;
float ts = java / 1000.0f;
//printf("JAVA STAMP = %g, C STAMP = %g, ERR = %g\n", java, c, java-c);
m->cur_pose.ang.x = m->cur_pose.ang.x + m->sensor_data.gyro.ypr.x * ts;
m->cur_pose.ang.y = m->cur_pose.ang.y + m->sensor_data.gyro.ypr.y * ts;
m->cur_pose.ang.z = m->cur_pose.ang.z + m->sensor_data.gyro.ypr.z * ts;
// normalize to [0, 2*PI]
if(m->cur_pose.ang.z > 2 * M_PI || m->cur_pose.ang.z < 0)
m->cur_pose.ang.z = fmod(m->cur_pose.ang.z + 2*M_PI, 2*M_PI);
// taking the average of the encoder values as the vehicle's displacement value in lines
float displacement = ((m->sensor_data.encoders[0] - m->prev_enc[0]) +
(m->sensor_data.encoders[1] - m->prev_enc[1])) / 2;
// converting encoder lines to revolutions and then to length
displacement = displacement / m->header_data.lines_per_revolution * m->header_data.wheel_circumference;
// finding the displacement
m->cur_pose.pos.x = m->cur_pose.pos.x - displacement * sin(m->cur_pose.ang.z);
m->cur_pose.pos.y = m->cur_pose.pos.y + displacement * cos(m->cur_pose.ang.z);
m->cur_pose.pos.z = 0;
// updating the previous encoder values
m->prev_enc[0] = m->sensor_data.encoders[0];
m->prev_enc[1] = m->sensor_data.encoders[1];
m->prev_time_stamp = m->sensor_data.time_stamp;
}
|
C
|
#include "dctime.h"
uint8_t time_is_leap_year(struct tm* tm){
uint16_t year = tm->tm_year + 1900;
if ((year % 400) == 0){
return 1; //Exactly divisible by 400
}
else if ((year % 100) == 0){
return 0; //Exactly divisible by 100, but not 400
}
else if ((year % 4) == 0){
return 1; //Exactly divisible by 4, but not by 100 or 400
}
else {
return 0; //Fallback case
}
}
uint8_t time_days_in_month(struct tm* tm){
uint8_t m = tm->tm_mon;
if (m == 0 || m == 2 || m == 4 || m == 6 || m == 7 || m == 9 || m == 11){
return 31;
}
else if (m == 3 || m == 5 || m == 8 || m == 10){
return 30;
}
else if (m == 1){
if (time_is_leap_year(tm)){
return 29;
}
else {
return 28;
}
}
return 0xFF;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.