language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> unsigned char* ReadBMP(char* filename) { FILE* img = fopen(filename, "rb"); //read the file unsigned char header[54]; fread(header, sizeof(unsigned char), 54, img); // read the 54-byte header u_int32_t width = header[0x12]; //size 4 printf("width = %i \n", width); u_int32_t height = header[0x16]; //size 4 printf("height = %i \n", height); u_int32_t offset = header[0x0a]; //size 4 printf("offset = 0x%04x \n", offset); u_int32_t size = header[0x02]; //size 4 printf("size of file = %i \n", size); u_int16_t info = header[0]; //size 2 printf("info header = 0x%x \n", info); u_int16_t bpp = header[0x1c]; //size 2 printf("Number of bits per pixel = %i \n", bpp); offset-=54; //correct start data address fread(header, sizeof(unsigned char), offset, img); // read the 54-byte header int index; u_int16_t cores[width]; for (int j = 0; j<height; j++) { fread(cores, 2, width, img); // read the data row by row for (int k = 0; k<width; k++) { printf("x=%i, y=%i, 0x%04x,\n\r", k,j, cores[k]); } printf("\n\r"); } //u_int16_t header1[54]; //fread(header1, sizeof(unsigned char), 54, img); // read the 54-byte header //printf("%i\n\r", sizeof(unsigned char)); //printf("0x%04x, \n\r", header1[0]); //printf("0x%04x, \n\r", header1[1]); //printf("0x%04x, \n\r", header1[2]); //printf("0x%04x, \n\r", header1[3]); fclose(img); //close the file } int main() { // ReadBMP("Untitled.bmp"); ReadBMP("image1.bmp"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #define MAX(a, b) ((a) > (b) ? (a) : (b)) int dp[1001]; int main() { int n; scanf("%d", &n); int *p = calloc(n+1, sizeof(int)); for (int p_i = 1; p_i <= n; ++p_i) { scanf("%d", &p[p_i]); } for (int n_i = 1; n_i <= n; ++n_i) { dp[n_i] = p[n_i]; // dp[n_i] = dp[0] + p[n_i] for (int sub_i = 1; sub_i < n_i; ++sub_i) { dp[n_i] = MAX(dp[n_i], dp[sub_i]+p[n_i-sub_i]); } } printf("%d\n", dp[n]); return 0; }
C
#include "hash_tables.h" /** * hash_table_delete - function deletes a hash table * * @ht: ptr to hash table * * Return: void */ void hash_table_delete(hash_table_t *ht) { unsigned int x = 0; hash_node_t *node = NULL; hash_node_t *temp = NULL; for (; x < ht->size; x++) { node = ht->array[x]; while (node != NULL) { temp = node; node = node->next; free(temp->key); free(temp->value); free(temp); } } free(ht->array); free(ht); }
C
/************************************************************************* > File Name: dir.c > Author: > Mail: > Created Time: 2019年03月30日 星期六 10时53分17秒 ************************************************************************/ #include<stdio.h> #include"../common/common.h" #include<dirent.h> int main() { struct dirent *dir_con; char dirname[] = "../client" ; DIR *dir_fp = opendir(dirname); int i = 1; while (dir_con = readdir(dir_fp)) { printf("Filename %d = %s\n", i, dir_con->d_name); printf("file type = %d\n", dir_con->d_type); } closedir(dir_fp); return 0; }
C
#include <stdio.h> int main() { void f(int x); int a; printf("请输入一个整数:\n"); scanf("%d",&a); f(a); return 0; } void f(int x) { int i; for(i=2;i<=x;i++) { if(x%i==0) { if(i<x) { printf("不是素数"); break; } else printf("是素数"); } } }
C
#include<stdio.h> struct stack { int data; struct stack* link; }; void push(struct stack**s, int data) { struct stack *temp = (struct stack *)(malloc (sizeof(struct stack))); temp->data = data; temp->link = *s; *s = temp; } int pop(struct stack** s) { if(*s == NULL) return NULL; int temp = (*s)->data; struct stack * node = *s; *s = node->link; free(node); return temp; } int isEmpty(struct stack *s) { if(s == NULL) return 1; else return 0; } struct stack *s1 = NULL; struct stack *s2 = NULL; struct stack *s3 = NULL; void moveDisk(char fp,char tp); void moveTower(int height,char fromPole, char toPole, char withPole) { if (height >= 1) { moveTower(height-1,fromPole,withPole,toPole); moveDisk(fromPole,toPole); moveTower(height-1,withPole,toPole,fromPole); } } void moveDisk(char fp,char tp) { printf("moving disk from %c to %c\n",fp, tp); } void main() { moveTower(5,'A','B','C'); }
C
#include<stdio.h> int calculateSum(int); int main() { int i, num; int result; printf("Nhap mot so bat ky: "); scanf("%d", &num); result = calculateSum(num); printf("\nTong cac so tu 1 toi %d la: %d", num, result); return 0; } int calculateSum(int num) { int res; if (num == 1) { return (1); } else { res = num + calculateSum(num - 1); } return (res); }
C
/* * File: main.c * Author: jota * * Created on May 15, 2012, 12:23 PM */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> /* * */ int main(int argc, char** argv) { int **matrix; int seed = 0; //int matrix_size = 63; /*L1*/ //int matrix_size = 180; /*L2*/ //int matrix_size = 1000; /*L3*/ int matrix_size = 27386; /*MM*/ int sum_number = 31000; unsigned int total_sum =0; int order; /* 0 = row, 1 = column, 2 = random sum */ /*get order from input*/ if(argv[1][0] == '0') order = 0; if(argv[1][0] == '1') order = 1; if(argv[1][0] == '2') order = 2; /*create matrix*/ matrix = malloc(matrix_size * sizeof (int *)); for (int i = 0; i < matrix_size; i++) { matrix[i] = malloc(matrix_size * sizeof (int)); for (int j = 0; j < matrix_size; j++) { matrix[i][j] = 1; } } if (order == 0) { for (int i = 0; i < matrix_size; i++) { for (int j = 0; j < matrix_size; j++) { total_sum = total_sum + matrix[i][j]; } } } else if(order == 1) { for (int i = 0; i < matrix_size; i++) { for (int j = 0; j < matrix_size; j++) { total_sum = total_sum + matrix[j][i]; } } } else if(order == 2) { for (int i = 0; i < sum_number; i++) { for (int j = 0; j < sum_number; j++) { total_sum = total_sum + matrix[rand()%(matrix_size)][rand()%(matrix_size)]; } } } printf("Total sum is %u",total_sum); return (EXIT_SUCCESS); }
C
#include<stdio.h> #include<malloc.h> #include<stdlib.h> struct node { int data; struct node* next; }; struct node* head=NULL; int count=0; void addBeg(int val){ struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); count++; temp->data = val; temp->next = head; head = temp; printf("\nvalue inserted %d ",val ); } void addEnd(int val){ struct node *t, *temp; t = (struct node*)malloc(sizeof(struct node)); count++; if(head == NULL){ head = t; head->data=val; head->next=NULL; return; } temp=head; while(temp->next!=NULL){ temp=temp->next; } temp->next=t; t->data=val; t->next=NULL; } void display(){ struct node *temp; temp= head; if (temp == NULL) { printf("Linked list is empty.\n"); return; } else{ printf("There are %d elements in linked list.\n", count); while (temp!= NULL) { printf("%d\n", temp->data); temp= temp->next; } } printf("%d\n", temp->data); } void delBeg(){ struct node *temp; int n; temp=head; if(head==NULL){ printf("Empty list\n"); } else{ n=head->data; temp=head->next; } free(temp); // head=temp; // count--; printf("%d deleted from beginning successfully \n",n); } void delEnd() { struct node *t, *u; int n; if (head == NULL) { printf("Linked list is already empty.\n"); return; } count--; if (head->next == NULL) { n = head->data; free(head); head = NULL; printf("%d deleted from end successfully.\n", n); return; } t = head; while (t->next != NULL) { u = t; t = t->next; } n = t->data; u->next = NULL; free(t); printf("%d deleted from end successfully.\n", n); } void insAtPos(int data, int position){ struct node *ptr = (struct node*)malloc(sizeof(struct node)); //Creating a new node ptr->data=data; int i; struct node *temp=head; //Do not use the pointer variable head directly. If we use it, the address location of the first node in the linked list will be lost //Pointer variable temp is used to traverse the linked list if(position==1) { //Executed only if position is 1 //If position is 1, it is a special case because we need to modify the head pointer ptr->next=temp; //ptr->next=head is also valid; head=ptr; //Making head point to newly created node ptr return; } //Function to insert node at position n in the linked list //If we have 5nodes in the linked list, we can insert a new a node between any two nodes of the five nodes present in the linked list for(i=1;i<position-1;i++)//Traversing to the (n-1)th position node in the linked list { temp=temp->next; } ptr->next=temp->next; //Making the newly created node point to next node of pointer temp temp->next=ptr; //Making pointer temp point to newly created node in the linked list } void main(){ int input, data; int pos; while(1){ printf("1. Insert an element at beginning of linked list.\n"); printf("2. Insert an element at end of linked list.\n"); printf("3. Display linked list.\n"); printf("4. Delete element from beginning.\n"); printf("5. Delete element from end.\n"); printf("6- At position\n"); printf("7. Exit\n"); printf("Enter choice\n"); scanf("%d", &input); switch (input) { case 1: printf("\nEnter value of element\n"); scanf("%d", &data); addBeg(data); break; case 2: printf("\nEnter value of element\n"); scanf("%d", &data); addEnd(data); break; case 3: display(); break; case 4: delBeg(); break; case 5: delEnd(); break; case 6: printf("Enter value \n "); scanf("%d",&data); printf("Enter data\n"); scanf("%d",&pos); insAtPos(data,pos); break; default: printf("\nInvalid choice\n"); } } }
C
#include <stdio.h> #include <malloc/malloc.h> #include <time.h> #include <sys/time.h> #define BIG_NX 3000 //#define BIG_NX 6 #define BIG_NY 200 #define BIG_NZ 65 #define BIG_NITEMS 10 //#define BIG_NITEMS 5000 double my_time(); main(int argc, char *argv[], char **envp) { float *data; FILE *fid; int i; int buf_size; int total_elems; double tstart; double ttot; // fill up the buffer total_elems = BIG_NX * BIG_NY * BIG_NZ; buf_size = total_elems * sizeof(float); data = (float *) malloc(buf_size); printf("Total elements = %d, size = %d\n", total_elems, buf_size); for (i=0; i<total_elems; i++) { data[i] = i; } fid = fopen("test_big_file", "w"); printf("Writing file:\n"); tstart = my_time(); for (i=0; i<BIG_NITEMS; i++) { fwrite(data, total_elems, sizeof(float), fid); } ttot = my_time() - tstart; fclose(fid); printf("\n"); printf(" Total elapsed time (s): %f, Average time per write (s): %f\n", ttot, (ttot/(double)BIG_NITEMS)); } double my_time() { struct timeval tstruct; // two elements: tv_sec, tv_usec double dbl_time; gettimeofday(&tstruct,NULL); dbl_time = (double)tstruct.tv_sec + ((double)tstruct.tv_usec * 1.0e-6); return dbl_time; }
C
/* * Soubor: htable_clear.c * Datum: 17.4.2011 * Autor: Pavel Fryz, xfryzp00@stud.fit.vutbr.cz, FIT * Projekt: IJC-DU2 * Popis: Funkce pro smazani polozek hashovaci tabulky. */ #include <stdlib.h> #include "htable.h" /** * Funkce maze vsechny polozky tabulky. * @param t Tabulka. */ void htable_clear(htable_t * t) { htable_listitem *item, *next; for (unsigned i = 0; i < t->htable_size; i++) { item = t->UK[i]; while (item != NULL) { next = item->next; free(item->key); free(item); item = next; } } }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> struct card { int card_index; }; struct deck { int size; int current_deck[52]; }; struct table { int table_cards[4]; }; char * cards[13] = {"Crabrador Retriever", "Crabbi", "Jab Crab", "Taxi Crab", "Ab Crab", "Bunny Crabbit", "Shish Crabob", "Crabuccino", "King Crab", "Crabernet Sauvignon", "Low Crab Diet", "Crabaloupe", "Abracrabdabra"}; struct deck * current_game; struct table * current_table; /* Creates a deck that contains 4 instances of each card, randomly scattered throughout the deck. * Deck is stored in struct deck * current_game. */ int make_deck() { srand( time( NULL)); int rand_index = (rand() % 13); current_game = malloc( sizeof(struct deck)); current_game->size = 0; int cards_random[13]; int i; for (i=0; i< 13; i++) { cards_random[i] = 4; } for (i=0; i<52; i++) { while (! cards_random[rand_index] ) rand_index = (rand() % 13); cards_random[ rand_index]--; current_game->current_deck[ current_game->size ] = rand_index; current_game->size++; rand_index = (rand() % 13); } return 0; } /* Acts like a stack - decreases the size of the deck and returns a new card (represented as an integer.) * If the deck is out of cards, returns -1. */ int draw_card() { if (current_game->size == 0) return -1; current_game->size--; int new_card = current_game->current_deck[ current_game->size]; return new_card; } /* Creates the table by drawing 4 cards from the deck. */ int create_table() { current_table = malloc(sizeof( struct table)); for (int i=0; i<4; i++){ current_table->table_cards[i] = draw_card(); } return 0; } /* Prints the contents of the table. */ int print_table() { // if (current_table->table_cards) { printf("---------------------------------------------------------------------------\n|\n|\n"); printf("| Cards on the table: \n| "); for (int i=0; i<3; i++){ printf("[%d] %s, ", i, cards[ current_table->table_cards[i]]); } printf("and [3] %s\n", cards[ current_table->table_cards[3]]); printf("|\n|\n---------------------------------------------------------------------------\n"); return 0; // } return -1; }
C
#include <stdio.h> char upper(char c) { if (c > 96 && c < 123) { c -= 32; } return c; } int main(void) { char letter; printf("Enter a character: "); scanf("%c", &letter); char uc = upper(letter); printf("%c", uc); return 0; }
C
/****************************************************************************** Welcome to GDB Online. GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby, C#, VB, Perl, Swift, Prolog, Javascript, Pascal, HTML, CSS, JS Code, Compile, Run and Debug online from anywhere in world. *******************************************************************************/ #include <stdio.h> int main() { printf("Use 3 numeros para descobrir o maior\n"); float a, b, c; //input printf("Digite os 3 numeros: "); scanf("%f %f %f", &a, &b, &c); //output if((a > b) && (a > c)) { printf("O maior numero é: %f", a); } else if(b > c) { printf("O maior numero é: %f", b); } else { printf("O maior numero é: %f", c); } return 0; }
C
//compile into `child5' int i; main() { i = 10; printf("child: i = %d\n", i); }
C
/* * Nhap vao 1 so nguyen duong n. Sau do thuc hien dem tu 0 den n. Neu nguoi dung nhap mot so am thi cho nhap lai * * De nguoi dung co the nhap lai thi ta se dua phan nhap so nguyen vao vong lap while * (De thuc hien duoc vong lap thi gia tri flag phai thoa man dieu kien flag == 0. * Tuy nhien neu khong thay doi flag thi vong lap while tro thanh vong lap vo han. * De thoai khoi vong lap, hoac bien vong lap while tro thanh vong lap huu han thi * can phai thay doi gia tri cua flag) * * Boi vi chi khi nguoi dung nhap vao mot so nguyen am thi moi thuc hien vong lap. * The nen sau khi nguoi dung nhap vao gia tri n. Ta se kiem tra n co duong hay khong. * Neu n la so am thi flag = 0. Neu n la so duong thi flag = 1. */ #include <stdio.h> int main() { int n; int index; int flag = 0; // if (n <= 0) { // printf("!!!!!!! n nhap vao phai la so nguyen duong\n"); // } while (flag == 0) { printf("Nhap vao so nguyen duong n:\t"); scanf("%d", &n); if (n <= 0) { printf("!!!!!!! n nhap vao PHAI la so nguyen duong\n"); flag = 0; } else { flag = 1; } } for (index = 0; index <= n; index++) { printf("%d\n", index); } return 0; }
C
#include<stdio.h> #include<math.h> #define N 7 int front =0; int a[N]; void insert(){ for (int i = 0; i < N; i++) { /* code */ printf("Enter data "); scanf("%d", &a[i]); } } void display(){ for (int i = 0; i < N; i++) { printf(" %d",a[i]); } printf("\n"); } void merge(int lb,int mid,int ub) { int i=lb; mid=(lb+ub)/2; int j=mid+1; int b[N]; int k=lb; while (i<=mid&&j<=ub) { printf("%d---------------",i); if (a[i]<=a[j]){ b[k]=a[i]; i++; k++; } else { b[k]=a[j]; j++; k++; } } if(i>mid){ while (j<=ub) { b[k]=a[j]; j++; k++; } } else{ while (i<=mid) { b[k]=a[i]; i++; k++; } } for (int k = lb; k < ub; k++) { /* code */a[k]=b[k]; } } void mergesort(int lb,int ub){ if (lb<ub){ int mid=(lb+ub)/2; mergesort(lb,mid); mergesort(mid+1,ub); merge(lb,mid,ub); } } void main(){ insert(); display(); mergesort(0,6); display(); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define NUM_ATHLETES 20 #define MAX_STR_LEN 128 #define DEBUG 0 typedef struct athlete { //add extra space to make sure blank spaces don't overflow data // assume the 128 for name holds true int ID; char* name; char* sex; int age; int height; int weight; char* team; char* noc; char* games; int year; char* season; char* city; /*Worlds longest name of town + 3*/ char* sport; char* event; char* medal; } athlete; int main() { //FILE *file = fopen("C:\\Users\\61422\\Documents\\COMP20003\\filereading\\test.csv", "r"); FILE *file = fopen("C:\\Users\\61422\\Documents\\COMP20003\\assignment1\\test.csv", "r"); if (file == NULL){ printf("error empty or no file"); return 0; } char* buf = malloc(90); char* tmp; if (buf == NULL) { printf("no memory for buf"); return 0; } athlete *athletes = malloc(sizeof(athlete)*NUM_ATHLETES); int i = 0; while (fgets(buf, MAX_STR_LEN-1, file) != NULL) { if ((strlen(buf)>0) && (buf[strlen (buf) - 1] == '\n')) { buf[strlen (buf) - 1] = '\0'; } //printf("%s\n\n", buf); tmp = strtok(buf, ","); athletes[i].ID = atoi(tmp); if (DEBUG) { printf("%s\n",tmp);} tmp = strtok(NULL, ","); athletes[i].name = tmp; if (DEBUG) { printf("%s\n",tmp);} tmp = strtok(NULL, ","); athletes[i].sex = tmp; if (DEBUG) { printf("%s\n",tmp);} tmp = strtok(NULL, ","); athletes[i].age = atoi(tmp); if (DEBUG) { printf("%s\n",tmp);} tmp = strtok(NULL, ","); athletes[i].height = atoi(tmp); if (DEBUG) { printf("%s\n",tmp);} tmp = strtok(NULL, ","); athletes[i].weight = atoi(tmp); if (DEBUG) { printf("%s\n",tmp);} tmp = strtok(NULL, ","); athletes[i].team = tmp; if (DEBUG) { printf("%s\n",tmp);} tmp = strtok(NULL, ","); athletes[i].noc = tmp; if (DEBUG) { printf("%s\n",tmp);} tmp = strtok(NULL, ","); athletes[i].games = tmp; if (DEBUG) { printf("%s\n",tmp);} tmp = strtok(NULL, ","); athletes[i].year = atoi(tmp); if (DEBUG) { printf("%s\n",tmp);} tmp = strtok(NULL, ","); athletes[i].season = tmp; if (DEBUG) { printf("%s\n",tmp);} tmp = strtok(NULL, ","); athletes[i].city = tmp; if (DEBUG) { printf("%s\n",tmp);} tmp = strtok(NULL, ","); athletes[i].sport = tmp; if (DEBUG) { printf("%s\n",tmp);} tmp = strtok(NULL, ","); athletes[i].event = tmp; if (DEBUG) { printf("%s\n",tmp);} tmp = strtok(NULL, ","); athletes[i].medal = tmp; if (DEBUG) { printf("%s\n",tmp);} //printf("%i %i %s %s\n",i, athletes[i].ID , athletes[i].name, athletes[i].season); printf("%i %s %i\n\n", i, athletes[i].name, athletes[i].weight); i++; } fclose(file); free(athletes); return 0; }
C
#include <stdio.h> #include <math.h> int main() { char outroUsuario = 'S'; char letraQuestao; int totalAlunos = 0; float notaAluno = 0; float notaTotalAlunos = 0; float maiorNota = -1 * INFINITY; float menorNota = INFINITY; do { totalAlunos++; for (int questao = 1; questao <= 10; questao++) { printf("Digite a letra marcada para questao %d: \n", questao); scanf("%c", &letraQuestao); fflush(stdin); if(questao == 1 && letraQuestao =='A'){ notaAluno++; } else if(questao == 2 && letraQuestao =='B'){ notaAluno++; } else if(questao == 3 && letraQuestao =='C'){ notaAluno++; } else if(questao == 4 && letraQuestao =='D'){ notaAluno++; } else if(questao == 5 && letraQuestao =='E'){ notaAluno++; } else if(questao == 6 && letraQuestao =='E'){ notaAluno++; } else if(questao == 7 && letraQuestao =='D'){ notaAluno++; } else if(questao == 8 && letraQuestao =='C'){ notaAluno++; } else if(questao == 9 && letraQuestao =='B'){ notaAluno++; } else if(questao == 10 && letraQuestao =='A'){ notaAluno++; } } if( notaAluno > maiorNota ){ maiorNota = notaAluno; } else if( notaAluno < menorNota ){ menorNota = notaAluno; } notaTotalAlunos += notaAluno; printf("Outro aluno usara o sistema? Digite S ou N\n"); scanf("%c", &outroUsuario); fflush(stdin); notaAluno = 0; } while (outroUsuario == 'S'); float mediaNotas = notaTotalAlunos / totalAlunos; printf("Media da turma: %.2f\n Maior Acerto: %.0f\n Menor Acerto: %.0f\n", mediaNotas, maiorNota, menorNota); return 0; } /** switch(questao){ case 1: { if(letraQuestao == 'A') notaAluno; break; } }*/
C
/* * ----------------------------------------------------------------- * $Revision: 4378 $ * $Date: 2015-02-19 10:55:14 -0800 (Thu, 19 Feb 2015) $ * ----------------------------------------------------------------- * Programmer: Carol Woodward @ LLNL, * Daniel R. Reynolds @ SMU. * ----------------------------------------------------------------- * For details, see the LICENSE file. * ----------------------------------------------------------------- * This header file contains definitions and declarations for use by * sparse linear solvers for Ax = b. * ----------------------------------------------------------------- */ #ifndef _SUNDIALS_SPARSE_H #define _SUNDIALS_SPARSE_H #include "sundials_types.h" #include "sundials_direct.h" #ifdef __cplusplus /* wrapper to enable C++ usage */ extern "C" { #endif /* * ================================================================== * Type definitions * ================================================================== */ /* * ----------------------------------------------------------------- * Type : SlsMat * ----------------------------------------------------------------- * The type SlsMat is defined to be a pointer to a structure * with various sizes, a data field, and arrays for the row and * column information for the sparse matrix entries. * The M and N fields indicates the number * of rows and columns, respectively. The data field is a one * dimensional array used for component storage. The NNZ field indicates * the number of nonzero entries in the matrix. The integer array, asub, * holds the row index for each of the matrix entries. The integer * array, xa, holds the index entry for the starting value of each column. * ----------------------------------------------------------------- * The relevant fields in DlsMat are: * M - number of rows * N - number of columns * NNZ - the number of nonzero entries in the matrix * data - pointer to a contiguous block of realtype variables * rowvals - row indices of each nonzero entry * colptrs - starting index of the first entry in data in each column * * The nonzero entries of the matrix are stored in * compressed column format. Row indices of entries in * column j are stored in rowvals[colptrs[j]] through rowvals[colptrs[j+i]-1] * and corresponding numerical values of the matrix are stored * in the same entries of data. * ----------------------------------------------------------------- */ typedef struct _SlsMat { int M; int N; int NNZ; realtype *data; int *rowvals; int *colptrs; } *SlsMat; /* * ================================================================== * Exported function prototypes (functions working on SlsMat) * ================================================================== */ /* * ----------------------------------------------------------------- * Function: NewSparseMat * ----------------------------------------------------------------- * NewSparseMat allocates memory for a compressed column sparse * matrix with M rows, N columns, and NNZ nonzeros. NewSparseMat * returns NULL if the request for matrix storage cannot be * satisfied. See the above documentation for the type SlsMat * for matrix storage details. * ----------------------------------------------------------------- */ SUNDIALS_EXPORT SlsMat NewSparseMat(int M, int N, int NNZ); /* * ----------------------------------------------------------------- * Function: SlsConvertDls * ----------------------------------------------------------------- * SlsConvertDense creates a new sparse matrix from an existing * dense/band matrix by copying all nonzero values into the sparse * matrix structure. SlsConvertDense returns NULL if the request * for matrix storage cannot be satisfied. * ----------------------------------------------------------------- */ SUNDIALS_EXPORT SlsMat SlsConvertDls(DlsMat A); /* * ----------------------------------------------------------------- * Functions: DestroySparseMat * ----------------------------------------------------------------- * DestroySparseMat frees the memory allocated by NewSparseMat * ----------------------------------------------------------------- */ SUNDIALS_EXPORT void DestroySparseMat(SlsMat A); /* * ----------------------------------------------------------------- * Function : SlsSetToZero * ----------------------------------------------------------------- * SetToZero sets all the elements of the sparse matrix A to 0.0. * ----------------------------------------------------------------- */ SUNDIALS_EXPORT void SlsSetToZero(SlsMat A); /* * ----------------------------------------------------------------- * Functions: CopySparseMat * ----------------------------------------------------------------- * This function copies sparse matrix A into sparse matrix B. * ----------------------------------------------------------------- */ SUNDIALS_EXPORT void CopySparseMat(SlsMat A, SlsMat B); /* * ----------------------------------------------------------------- * Functions: ScaleSparseMat * ----------------------------------------------------------------- * This function scales all data entries of a sparse matrix A * by the realtype number in b. * ----------------------------------------------------------------- */ SUNDIALS_EXPORT void ScaleSparseMat(realtype b, SlsMat A); /* * ----------------------------------------------------------------- * Functions: AddIdentitySparseMat * ----------------------------------------------------------------- * This function adds 1 to every diagonal entry of A. * Note that the resulting matrix may have more nonzero entries than * the original. This is accounted for, so that the return matrix * may be larger than the one sent in. * ----------------------------------------------------------------- */ SUNDIALS_EXPORT void AddIdentitySparseMat(SlsMat A); /* * ----------------------------------------------------------------- * Functions: SlsAddMat * ----------------------------------------------------------------- * This function adds two sparse matrices: A = A+B. * Note that the resulting matrix may have more nonzero entries than * either of the original matrices. This is accounted for, so that * the return matrix may be larger than the ones sent in. Upon * successful completion, the return value is zero; otherwise 1 is * returned. * ----------------------------------------------------------------- */ SUNDIALS_EXPORT int SlsAddMat(SlsMat A, SlsMat B); /* * ----------------------------------------------------------------- * Functions: ReallocSparseMat * ----------------------------------------------------------------- * This function reallocs internal arrays so that the resulting matrix * holds colptrs[N] nonzeros. * ----------------------------------------------------------------- */ SUNDIALS_EXPORT void ReallocSparseMat(SlsMat A); /* * ----------------------------------------------------------------- * Functions: SlsMatvec * ----------------------------------------------------------------- * This function computes the matrix-vector product, y=A*x, where A * is a sparse matrix of dimension MxN, x is a realtype array of * length N, and y is a realtype array of length M. Upon successful * completion, the return value is zero; otherwise 1 is returned. * ----------------------------------------------------------------- */ SUNDIALS_EXPORT int SlsMatvec(SlsMat A, realtype *x, realtype *y); /* * ----------------------------------------------------------------- * Functions: PrintSparseMat * ----------------------------------------------------------------- * This function prints the compressed column matrix information for * matrix A to standard output. * It is intended as a debugging tool with small values of NNZ. * The elements are printed using the %g/%lg/%Lg option. * A blank line is printed before and after the matrix. * ----------------------------------------------------------------- */ SUNDIALS_EXPORT void PrintSparseMat(SlsMat A); #ifdef __cplusplus } #endif #endif
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_2__ TYPE_1__ ; /* Type definitions */ struct TYPE_2__ {size_t running_len; int running_bit; size_t literal_words; } ; struct rlw_iterator {scalar_t__ literal_word_start; scalar_t__ buffer; TYPE_1__ rlw; } ; struct ewah_bitmap {int dummy; } ; /* Variables and functions */ int /*<<< orphan*/ ewah_add_dirty_words (struct ewah_bitmap*,scalar_t__,size_t,int) ; int /*<<< orphan*/ ewah_add_empty_words (struct ewah_bitmap*,int,size_t) ; int /*<<< orphan*/ rlwit_discard_first_words (struct rlw_iterator*,size_t) ; scalar_t__ rlwit_word_size (struct rlw_iterator*) ; size_t rlwit_discharge( struct rlw_iterator *it, struct ewah_bitmap *out, size_t max, int negate) { size_t index = 0; while (index < max && rlwit_word_size(it) > 0) { size_t pd, pl = it->rlw.running_len; if (index + pl > max) pl = max - index; ewah_add_empty_words(out, it->rlw.running_bit ^ negate, pl); index += pl; pd = it->rlw.literal_words; if (pd + index > max) pd = max - index; ewah_add_dirty_words(out, it->buffer + it->literal_word_start, pd, negate); rlwit_discard_first_words(it, pd + pl); index += pd; } return index; }
C
#include <stdio.h> #include <string.h> int main() { int i,co; co=0; char str[1000]; while(gets(str)){ for(i=0;str[i]!='\0';i++){ if(co%2==0 && str[i]=='"'){ printf("``"); co++; } else if(co%2==1 && str[i]=='"'){ printf("''"); co++; } else{ printf("%c",str[i]); } } printf("\n"); } return 0; }
C
/** ****************************************************************************** * @file main.c * @author Bahtiyar Bayram * @version V1.0 * @brief SysTick IRQ Example ****************************************************************************** */ #include "stm32f4xx.h" #include "stdint.h" void SysTick_Handler(void) { GPIOA->ODR ^= GPIO_ODR_OD5; } int main(void) { __disable_irq(); // Configure SysTick SysTick->LOAD = 16000000-1; // 1s @16MHz SysTick->VAL = 0; // Clear current value register // Enable SysTick and SysTick Interrupt SysTick->CTRL = SysTick_CTRL_ENABLE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_CLKSOURCE_Msk; __enable_irq(); RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN; // Set PA5 as output GPIOA->MODER |= GPIO_MODER_MODER5_0; while(1) { } }
C
/** * @file OBDeque_Private.h * @brief OBDeque Private Interace * @author theck */ #ifndef OBDEQUE_PRIVATE_H #define OBDEQUE_PRIVATE_H #include "../OBDeque.h" /* OBDequeNode TYPE */ /** * @brief OBDequeNode internal structure, encapsulating the data needed for an * node within a doubly linked list. Internally referenced only */ typedef struct OBDequeNode_struct{ OBObjType base; /**< obj containing reference count and class membership data */ OBTypeRef stored; /**< obj stored within the node in the deque */ struct OBDequeNode_struct *next; /**< Pointer to the next node in the list */ struct OBDequeNode_struct *prev; /**< Pointer to the prev node in the list */ } OBDequeNode; /* OBDequeNode PRIVATE METHODS */ /** * @brief Constructor, creates a new OBDequeNode containing an obj * * @param to_store A non-NULL instance of any Offbrand compatible class * * @return A new instance of OBDeque node storing to_store and with NULL * references to next and prev nodes */ OBDequeNode * OBDequeNodeCreate(OBTypeRef to_store); /** * @brief Destructor for OBDequeNode * @param to_dealloc An obj pointer to an instance of OBDequeNode with reference * count 0 * @warning Do not call manually, release will call automatically when the * instances reference count drops to 0! */ void OBDequeNodeDealloc(OBTypeRef to_dealloc); /* OBDequeIterator type */ /** * @brief OBDequeNodeIterator internal structure, encapsulating the data needed * for an iterator of a doubly linked list. */ struct OBDequeIterator_struct{ OBObjType base; /**< obj containing reference count and class membership data */ const OBDeque *deque; /**< OBDeque that the iterator is bound to */ OBDequeNode *node; /**< The OBDequeNode that the iterator references within deque */ }; /* OBDequeIterator Private Methods */ /** * @brief Constructor, creates an instance of OBDequeIterator bound to an * OBDeque and an OBDequeNode within that deque * * @param deque An instance of OBDeque * @param node An instance of OBDequeNode contained within deque * * @return An instance of OBDequeIterator */ struct OBDequeIterator_struct * OBDequeIteratorCreate(const OBDeque *deque, OBDequeNode *node); /** * @brief Destructor for OBDequeIterator * @param to_dealloc An obj pointer to an instance of OBDequeIterator with * reference count 0 * @warning Do not call manually, release will call automatically when the * instances reference count drops to 0! */ void OBDequeIteratorDealloc(OBTypeRef to_dealloc); /* OBDeque Type */ /** * @brief OBDeque internal structure, encapsulating the data needed for a * doubly linked list */ struct OBDeque_struct{ OBObjType base; /**< obj containing reference count and class membership data */ OBDequeNode *head; /**< pointer to the OBDequeNode at the head of the deque */ OBDequeNode *tail; /**< pointer to the OBDequeNode at the tail of the deque */ uint64_t length; /**< integer length of the deque (or number of elements stored within) */ }; /* OBDeque Private Methods */ /** * @brief Default constructor for OBDeque * * @return An instance of class OBDeque * * @warning All public constructors should call this constructor and initialize * individual members as needed, so that all base data is initialized properly */ OBDeque * OBDequeCreateDefault(void); /** * @brief Internal merge sort implementation for an OBDeque * * @param deque Static OBDeque to be sorted * @param order Accepts OB_LEAST_TO_GREATEST or OB_GREATEST_TO_LEAST as valid * sorting orders * @param funct A compare_fptr to a function that returns an int8_t when given * two obj * arguments * * @return A sorted static deque * * @warning There is little to no parameter checking in this function, all * sorting should use the publicly accessable function which calls this method * internally. */ OBDeque OBDequeSortRecursive(OBDeque deque, int8_t order, obcompare_fptr funct); /** * @brief Hash function for OBDeque * @param to_hash An obj pointer to an instance of OBDeque * @return Key value (hash) for the given obj pointer to a OBDeque */ obhash_t OBDequeHash(OBTypeRef to_hash); /** * @brief Compares two instances of OBDeque * * @param a A non-NULL obj pointer to type OBDeque * @param b A non-NULL obj pointer to type OBDeque * * @retval OB_LESS_THAN obj a is less than b * @retval OB_GREATER_THAN obj a is equivalent to b * @retval OB_EQUAL_TO obj a is greater than b */ int8_t OBDequeCompare(OBTypeRef a, OBTypeRef b); /** * @brief Displays information about an OBDeque to stderr * * @param to_print A non-NULL obj pointer to type OBDeque */ void OBDequeDisplay(OBTypeRef to_print); /** * @brief Destructor for OBDeque * @param to_dealloc An obj pointer to an instance of OBDeque with * reference count 0 * @warning Do not call manually, release will call automatically when the * instances reference count drops to 0! */ void OBDequeDealloc(OBTypeRef to_dealloc); #endif
C
/* *File: radix.c * *Description: Utilizes deque.c to implement a radix sort to sort a series of integers * */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <assert.h> #include <math.h> #include "deque.h" void sort(DEQUE **dp, DEQUE *lp, int digit); int main(void) { DEQUE* storage[10]; DEQUE* input = createDeque(); int i; /* Create the deques that storage will hold*/ for (i = 0; i < 10; i++) { storage[i] = createDeque(); }//end for /*Recieve input data, place them in the right queue, and determine the greatest number of digits*/ int max = 0; int x; while(scanf("%d", &x) == 1) { if (x > max) max = x; /*Last in first out, so add new elements to the front and then take elements out from the rear (removeLast())*/ addFirst(input, x); }//end while /*Rutime is the number of times that the program has to run in order to sort through all digit places of every integer*/ int runtime = (int)(log(max + 1)/log(10)); int count = numItems(input); /* * Go through the deques and sort them back into the input list * Use digit to keep track of what digit place we are sorting */ int digit = 0; for (i = 0; i <= runtime; i++) { sort (storage,input, digit); digit++; }//end for i /* Once the sort has finished, everything should be in the first deque (storage[0]). Sort that back to the input deque and print */ for (i = 0; i < count; i++) { int x = removeLast(input); printf("%d ", x); } /*Free the standalone input deque, then go and free each deque in the array*/ destroyDeque(input); for (i = 0; i < 10; i++) { destroyDeque(storage[i]); } return 0; }//end main /* * Function: sort * * Description: loop through the input deque and sort the data into their individual bins in array of deques, then go and copy the sorted material * back into the input deque. Repeat as necessary. * Rutime: O(n) */ void sort(DEQUE **dp, DEQUE *lp, int digit) { /*dp = the pointer to the array of deques; lp = the pointer to the input deque, and digit is the digit place that we are sorting*/ int i, j; /*Take the data out of the input deque and put them in their respective bins (storage[i])*/ int count = numItems(lp); int power = pow(10, digit); for(i = 0; i <count; i++) { int x = removeLast(lp); /*the program is only allowed to let positive data through, so check to make sure data is positive*/ if (x >= 0) { int index; index =(x/(power))%10; addFirst(dp[index], x); }//end if x > =0 }//end for i /*For each of the ten deques in the array (dp), go through and add them back to the input deque*/ for (i = 0; i < 10; i++) { int count = numItems(dp[i]); for (j = 0; j < count; j++) { int x = removeLast(dp[i]); if (x >= 0) { addFirst(lp, x); }//end if }//end j }//end for i }//end sort
C
#ifndef __SHARED_DATA_TYPE__ #define __SHARED_DATA_TYPE__ #define MAXROW 30 // Stage의 최대 ROW값 #define MAXCOL 30 // Stage의 최대 COL값 // 위치 값을 저장하는 구조체 struct Position{ int x; int y; Position(int _x = 0, int _y = 0) : x(_x), y(_y){} // 연산자 오버로딩 bool operator==(const Position& pos){ return x == pos.x && y == pos.y; } }; #endif
C
#include <linux/kernel.h> #include <linux/module.h> #include <linux/fs.h> #include <asm/io.h> #include <linux/init.h> #include <asm/uaccess.h> #define GPFSEL0 0x3f200000 /* function select register */ #define GPSET0 0x3f20001c /* bit set */ #define GPCLR0 0x3f200028 /* bit clear */ #define GPLEV0 0x3f200034 /* level holder register */ volatile int *gpio_fsel; volatile int *gpio_clr; volatile int *gpio_set; volatile int *gpio_level; ssize_t gpio_read(struct file *fp, char *buff, size_t n, loff_t *f) { int val, i; val = *gpio_level; i = copy_to_user(buff, &val, 4); return 4; } ssize_t gpio_write(struct file *fp, const char *buff, size_t n, loff_t *f) { int val, i; i = copy_from_user(&val, buff, 4); printk("write %d\n", val); val = val & 4; if (val) *gpio_set = val; else *gpio_clr = (~val & 4); return 4; } int gpio_open(struct inode *node, struct file *fp) { int var = *gpio_fsel; var &= ~(7<<6); var |= (1<<6); /* set GPIO2 as output (001) */ printk("GPFSEL = %x\n", var); *gpio_fsel = var; return 0; } int gpio_close(struct inode *node, struct file *fp) { return 0; } struct file_operations gpio = { read: gpio_read, write: gpio_write, open: gpio_open, release: gpio_close, }; int init_module() { int n; n = register_chrdev(123, "gpiogpio", &gpio); if(n==0) { printk("device registered\n"); gpio_fsel = ioremap(GPFSEL0, 4); gpio_set = ioremap(GPSET0, 4); gpio_clr = ioremap(GPCLR0, 4); gpio_level = ioremap(GPLEV0, 4); return 0; } else return -1; } void cleanup_module() { unregister_chrdev(123, "gpiogpio"); iounmap(gpio_fsel); iounmap(gpio_set); iounmap(gpio_clr); iounmap(gpio_level); printk("device removed\n"); }
C
bool isPalindrome(int x){ if (x < 0) return false; else if (x == 0) return true; long f=0; int temp=x; for ( ; x; f = f * 10 + x % 10, x /= 10); if (temp == f) return true; else return false; }
C
/*1070 - Conveyor Belt _ Geometric */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #define DBUGM_Vec1 #define DBUGM_Line1 #define DBUGM_BAB1 #define DBUGM1 #define LargeINT 1000000000 #define errorT 0.00000000001 #define M_PI 3.14159265358979323846 #define MaxcircleNumber 25 typedef struct { double x, y; } Vec; typedef struct Vertex { double x, y; } Point; typedef struct { double x1, x2; double y1, y2; double len; } Segment; typedef struct { Point center; double radius; int direction; /*-1 clockwise, 1 counterclockwise*/ } Circle; typedef struct { int isValid; Segment cutLine; } Edge; int circleNumber; Circle circles[MaxcircleNumber]; int start, end; double limit; Edge edgeTable[MaxcircleNumber][MaxcircleNumber]; int shortestPath[MaxcircleNumber][MaxcircleNumber]; double minLen; void ShowVec(Vec v) { printf(" Vec: (%2.2lf %2.2lf )\n", v.x, v.y); } void ShowCircle(Circle c1) { printf("Circle direction: %d\n", c1.direction); ShowPoint(c1.center); printf(" Radius: %2.2lf\n", c1.radius); } void ShowLine(Segment edgeA) { printf("Line: (%2.2lf, %2.2lf) -> (%2.2lf, %2.2lf): %lf\n", edgeA.x1, edgeA.y1, edgeA.x2, edgeA.y2, edgeA.len); } void ShowPoint(Point v) { printf(" Point: (%2.2lf %2.2lf )\n", v.x, v.y); } int Max(int c1, int c2) { if(circles[c1].radius > circles[c2].radius-errorT) return c1; else return c2; } int Min(int c1, int c2) { if(circles[c1].radius < circles[c2].radius-errorT) return c1; else return c2; } void Read() { int i, j; minLen = LargeINT; for(i = 0; i < circleNumber; i++){ char c[5]; scanf("%lf%lf%lf%s", &circles[i].center.x, &circles[i].center.y, &circles[i].radius, &c); if(strcmp(c, "CC") == 0) circles[i].direction = 1; else if(strcmp(c, "C") == 0) circles[i].direction = -1; else { printf("Input Error\n"); exit(1); } } scanf("%d%d%lf", &start, &end, &limit); /*printf("%d %d %lf\n", start, end, limit);*/ } void FindLine(Point a, Point b, Segment* line) { line->x1 = a.x; line->y1 = a.y; line->x2 = b.x; line->y2 = b.y; line->len = sqrt((b.x-a.x)*(b.x-a.x) + (b.y-a.y)*(b.y-a.y)); } Vec InverseVec(Vec v) { Vec iV; iV.x = -v.x; iV.y = -v.y; return iV; } void RotaeVec(Vec v, double CosTheta, int direction, Vec *rv, double len) { double SinTheta = sqrt(1 - CosTheta*CosTheta) * direction; rv->x = v.x*CosTheta - v.y*SinTheta; rv->y = v.x*SinTheta + v.y*CosTheta; #ifdef DBUGM_Vec printf("\n---- Rotate Vector ----\n"); printf("cos: %2.2lf, sin: %lf, radius: %2.2lf\n", CosTheta, sin(acos(CosTheta)), len); ShowVec(v); ShowVec(*rv); #endif double vlen = sqrt(rv->x*rv->x + rv->y*rv->y); rv->x = len*(rv->x/vlen); rv->y = len*(rv->y/vlen); #ifdef DBUGM_Vec ShowVec(*rv); #endif } void FindPoint(Point p, Vec v, Point* np) { np->x = p.x + v.x; np->y = p.y + v.y; } int CheckCross(Circle c1, Segment s1) { int cross = 0; /*ToDo*/ return cross; } void CheckValid(int r1, int r2) { /*Check Valid*/ int i, j; int valid = 1; if(edgeTable[r1][r2].cutLine.len > limit+errorT) valid = 0; for(i = 0; i < circleNumber && valid == 1; i++){ if(CheckCross(circles[i], edgeTable[r1][r2].cutLine) == 1) valid = 0; } if(valid == 1) { edgeTable[r1][r2].isValid = 1; shortestPath[r1][r2] = edgeTable[r1][r2].cutLine.len; } else { edgeTable[r1][r2].isValid = 0; shortestPath[r1][r2] = 0; } #ifdef DBUGM_Line printf("Find Common Tangent %d -> %d, valid: %d\n", r1, r2, edgeTable[r1][r2].isValid); ShowCircle(circles[r1]); ShowCircle(circles[r2]); ShowLine(edgeTable[r1][r2].cutLine); #endif } double FindCommonTangent(int r1, int r2) { int i, j; /*Radius1 < Radius2*/ double c1c2 = sqrt((circles[r2].center.y - circles[r1].center.y)*(circles[r2].center.y - circles[r1].center.y) + (circles[r2].center.x - circles[r1].center.x)*(circles[r2].center.x - circles[r1].center.x)); Vec oV1, iV2, oV2, iV1; if(circles[r1].direction * circles[r2].direction > 0) { /*Outer Common Tangent */ double CosTheta = (fabs(circles[r2].radius - circles[r1].radius))/c1c2; Vec r2r1; r2r1.x = circles[r1].center.x - circles[r2].center.x; r2r1.y = circles[r1].center.y - circles[r2].center.y; RotaeVec(r2r1, CosTheta, circles[r2].direction, &iV2, circles[r2].radius); RotaeVec(r2r1, CosTheta, circles[r2].direction, &oV1, circles[r1].radius); RotaeVec(r2r1, CosTheta, -circles[r2].direction, &oV2, circles[r2].radius); RotaeVec(r2r1, CosTheta, -circles[r2].direction, &iV1, circles[r1].radius); } else { /*Inner Common Tangent */ double CosTheta = (circles[r2].radius + circles[r1].radius)/c1c2; Vec r2r1; r2r1.x = circles[r1].center.x - circles[r2].center.x; r2r1.y = circles[r1].center.y - circles[r2].center.y; RotaeVec(r2r1, CosTheta, circles[r2].direction, &iV2, circles[r2].radius); RotaeVec(InverseVec(r2r1), CosTheta, -circles[r1].direction, &oV1, circles[r1].radius); RotaeVec(r2r1, CosTheta, -circles[r2].direction, &oV2, circles[r2].radius); RotaeVec(InverseVec(r2r1), CosTheta, circles[r1].direction, &iV1, circles[r1].radius); } Point iP2, oP1, iP1, oP2; FindPoint(circles[r2].center, iV2, &iP2); FindPoint(circles[r1].center, oV1, &oP1); FindLine(oP1, iP2, &edgeTable[r1][r2].cutLine); CheckValid(r1, r2); FindPoint(circles[r2].center, oV2, &oP2); FindPoint(circles[r1].center, iV1, &iP1); FindLine(oP2, iP1, &edgeTable[r2][r1].cutLine); CheckValid(r2, r1); } void FindEdges() { int i, j; for(i = 0; i < circleNumber-1; i++){ for(j = i+1; j < circleNumber; j++){ if(fabs(circles[i].radius - circles[j].radius) < 0) FindCommonTangent(i, j); else FindCommonTangent(Min(i, j), Max(i, j)); } } } int FindIntersection(Segment edgeA, Segment edgeB) { #ifdef DBUGM printf("\n---FindIntersection %2.2lf\n", fabs(((edgeA.y2 - edgeA.y1)*(edgeB.x2 - edgeB.x1) - (edgeA.x2 - edgeA.x1)*(edgeB.y2 - edgeB.y1)))); ShowLine(edgeA); ShowLine(edgeB); #endif if( fabs((edgeA.y2 - edgeA.y1)*(edgeB.x2 - edgeB.x1) - (edgeA.x2 - edgeA.x1)*(edgeB.y2 - edgeB.y1)) < errorT ){ return 0; } /*Compute the proportion from edgeA->P1 to the intersection*/ /*ua = ((x4 - x3)(y1 - y3) - (y4-y3)(x1-x3)) / ((y4 - y3)(x2 - x1) - (x4 - x3)(y2 - y1))*/ double ppB = ((edgeA.x2 - edgeA.x1)*(edgeB.y1 - edgeA.y1) - (edgeA.y2 - edgeA.y1)*(edgeB.x1 - edgeA.x1)) / ((edgeA.y2 - edgeA.y1)*(edgeB.x2 - edgeB.x1) - (edgeA.x2 - edgeA.x1)*(edgeB.y2 - edgeB.y1)); double ppA = ((edgeB.x2 - edgeB.x1)*(edgeA.y1 - edgeB.y1) - (edgeB.y2 - edgeB.y1)*(edgeA.x1 - edgeB.x1)) / ((edgeB.y2 - edgeB.y1)*(edgeA.x2 - edgeA.x1) - (edgeB.x2 - edgeB.x1)*(edgeA.y2 - edgeA.y1)); #ifdef DBUGM printf("ppA, ppB: %2.2lf %2.2lf\n", ppA, ppB); #endif if(ppB > 1+errorT || ppB < 0-errorT || ppA > 1+errorT || ppA < 0-errorT) return 0; else return 1; } double CalculateArc(int c1, Segment s1, Segment s2) { double theta1 = atan2(s1.y2 - circles[c1].center.y, s1.x2 - circles[c1].center.x)*180/M_PI; if(theta1 < 0-errorT) theta1 = theta1+360; double theta2 = atan2(s2.y1 - circles[c1].center.y, s2.x1 - circles[c1].center.x)*180/M_PI; if(theta2 < 0-errorT) theta2 = theta2+360; double delta; if(circles[c1].direction == 1){ delta = theta2 - theta1; if(delta < 0) delta += 360; } else { delta = theta1 - theta2; if(delta < 0) delta += 360; } #ifdef DBUGM printf("%lf %lf\n", s1.x2 - circles[c1].center.x, s1.y2 - circles[c1].center.y); printf("%lf %lf\n", s2.x1 - circles[c1].center.x, s2.y1 - circles[c1].center.y); printf("%lf %lf\n", theta1, theta2); #endif return circles[c1].radius*2*M_PI*((delta)/360); } void BranchAndBound(int nowC, int valid[circleNumber], int edges[circleNumber][2], int chosed, double nowLen) { #ifdef DBUGM_BAB printf("\n---- BranchAndBound: now: %d, target: %d chosed: %d len: %2.2lf\n", nowC, end, chosed, nowLen); #endif if(nowLen >= minLen) return; if(valid[end] == 0) { if(nowLen < minLen) minLen = nowLen; return; } int i, j; for(i = 0; i < circleNumber; i++){ if(valid[i] == 0) continue; if(edgeTable[nowC][i].isValid == 0) continue; if(nowLen + shortestPath[nowC][i] >= minLen) continue; int flag = 1; for(j = 0; j < chosed && flag == 1; j++){ if(FindIntersection(edgeTable[nowC][i].cutLine, edgeTable[edges[j][0]][edges[j][1]].cutLine) == 1) flag = 0; } if(flag == 0) continue; else { edges[chosed][0] = nowC; edges[chosed][1] = i; valid[i] = 0; double arc; if( nowC == start) arc = 0; else arc = CalculateArc(nowC, edgeTable[edges[chosed-1][0]][edges[chosed-1][1]].cutLine, edgeTable[nowC][i].cutLine); BranchAndBound(i, valid, edges, chosed+1, nowLen + edgeTable[nowC][i].cutLine.len + arc); valid[i] = 1; } } } void Round(char output[256], double minLen) { sprintf(output, "%.2lf", minLen); int len = strlen(output); if(output[len-1] == '0'){ output[len-1] = '\0'; output[len-2] = '\0'; output[len-3] = '\0'; } } int main() { #ifndef ONLINE_JUDGE freopen("input.in", "r", stdin); freopen("output.out", "w", stdout); #endif int i, j, k; int caseNumber = 1; while(1){ scanf("%d", &circleNumber); if(circleNumber == 0) break; Read(); #ifdef DBUGM printf("----------- Debug Message %d-----------\n", caseNumber); #endif /*Preprocessing*/ /*Find all edges for circles*/ FindEdges(); /*Calculate APSP*/ for(k = 0; k < circleNumber; k++){ for(i = 0; i < circleNumber; i++){ for(j = 0; j < circleNumber; j++){ if(shortestPath[i][k] + shortestPath[k][j] < shortestPath[i][j]) shortestPath[i][j] = shortestPath[i][k] + shortestPath[k][j]; } } } /*Start Branch and Bound, use APSP to estimate possible cut*/ int valid[circleNumber]; for(i = 0; i < circleNumber; i++) valid[i] = 1; valid[start] = 0; int edges[circleNumber][2]; BranchAndBound(start, valid, edges, 0, 0); if( fabs(minLen - LargeINT) < errorT || fabs(minLen - 0) < errorT ) printf("Case %d: Cannot reach destination shaft\n", caseNumber); else { char output[256] = {'\0'}; Round(output, minLen); printf("Case %d: length = %s\n", caseNumber, output); } caseNumber++; } return 0; }
C
#include <stdio.h> int main(int argc, char *argv[]) { int i; printf("Num of arg ="); printf("%d\n",argc); for(i=1;i<argc;i++) { printf("%s",argv[i]); printf("\n"); } return 0; } /* nd82914@McCartney:~/Dropbox/Git/LINUXProgramingInterface/Chapter2$ ./a.out maccartney lenon harrison Num of arg =4 maccartney lenon harrison nd82914@McCartney:~/Dropbox/Git/LINUXProgramingInterface/Chapter2$ */
C
#include <stdio.h> #include <string.h> char name[10000000][11]; int main(){ int first,last; char str[6]; last = -1; first = 0; while(scanf("%s", str)!=EOF){ if(str[1]=='u'){ last++; scanf("%s", name[last]); } else if(str[1]=='o'){ if(first <= last) first++; } else if(str[1]=='r'){ if(first <= last) printf("%s\n", name[first]); else printf("empty\n"); } } return 0; }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> char map[200011][11]; int comp(const void *a,const void *b) { return strcmp((char *)a,(char *)b); } int main() { char c; char word[11]; int i,j,flag,tmp; int left,right,mid; tmp=-2; while(c=getchar()) { tmp+=2; if(c=='\n') break; else { scanf("%s",word); map[tmp+1][0]=c; for(i=0;word[i]!='\0';i++) map[tmp+1][i+1]=word[i]; map[tmp+1][i+1]='\0'; scanf("%s",word); strcpy(map[tmp],word); c=getchar(); } } qsort(map,tmp/2,22*sizeof(char),comp); while(scanf("%s",word)!=EOF) { flag=1; for(left=0,right=tmp/2;left<=right;) { mid=(left+right)/2; if(strcmp(word,map[2*mid])>0) left=mid+1; else if(strcmp(word,map[2*mid])<0) right=mid-1; else { flag=0; printf("%s\n",map[2*mid+1]); break; } } if(flag) printf("eh\n"); } }
C
#include<GL/glut.h> #include<stdio.h> int xc, yc, r; void draw_circle(int xc, int yc, int x, int y) { glBegin(GL_POINTS); glVertex2i(xc + x, yc + y); glVertex2i(xc - x, yc + y); glVertex2i(xc + x, yc - y); glVertex2i(xc - x, yc - y); glVertex2i(xc + y, yc + x); glVertex2i(xc - y, yc + x); glVertex2i(xc + y, yc - x); glVertex2i(xc - y, yc - x); glEnd(); } void circlebres() { glClear(GL_COLOR_BUFFER_BIT); int x = 0, y = r; int d = 3 - 2 * r; while (x <= y) { draw_circle(xc, yc, x, y); x++; if (d<0) d = d + 4 * x + 6; else { y--; d = d + 4 * (x - y) + 10; } draw_circle(xc, yc, x, y); } glFlush(); } void minit() { glClearColor(1, 1, 1, 1); glColor3f(1.0, 0.0, 0.0); glPointSize(3.0); gluOrtho2D(10, 500, 10, 500); } void main(int argc, char *argv[]) { printf("Enter the coordinates of the center and the radius\n"); scanf("%d%d%d", &xc, &yc, &r); glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(300, 300); glutInitWindowPosition(5, 5); glutCreateWindow("CSE"); glutDisplayFunc(circlebres); minit(); glutMainLoop(); }
C
#include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include "sha256.h" #include "sha256_constants.h" #define DEBUG 0 /** * Must be called on hash_t before it is used * Not calling this will cause segfaults */ void init_hash(struct hash_t * target) { target->message = (uint32_t*) malloc(INITIAL_MESSAGE_SIZE); target->c_message = (unsigned char*)target->message; target->message_container_length = INITIAL_MESSAGE_SIZE; target->c_hash = (unsigned char*)target->hash; reinit_hash(target); } void reinit_hash(struct hash_t * target) { target->message_length = 0; target->c_message_length = 0; //Set initial hash values: int i; for(i=0;i<8;++i) { target->hash[i] = sha256_initial_values[i]; } } /** * Doubles the message size of the hash * Calling this on an uninitialized och finalized hash will cause segfault resp. do nothing */ void resize_hash(struct hash_t * target) { target->message_container_length*=2; target->message = (uint32_t*) realloc(target->message, target->message_container_length); target->c_message = (unsigned char*)target->message; } /** * Frees memory allocated by init and resize. Sets all internal size counters to 0 */ void finalize_hash(struct hash_t * target) { free(target->message); target->message_length = 0; target->c_message_length = 0; target->message_container_length = 0; } /** * Fills hash from stdin */ int from_stdin(struct hash_t * target) { char c[2]; unsigned int l; do { c[0] = getchar(); if(c[0] == '\n') { return 1; } else if(c[0] != EOF) { c[1] = getchar(); sscanf(c, "%2x", &l); if(target->c_message_length == target->message_container_length) resize_hash(target); target->c_message[target->c_message_length++] = (unsigned char)l; } } while(c[0] != EOF); return 0; } /** * Fills hash from string */ void from_string(const char * input, struct hash_t * target) { unsigned int l; unsigned int r; unsigned int pos=0; do { r = sscanf(input+pos,"%2x", &l); pos+=2; if(r == 1) { //Filled one variable if(target->c_message_length == target->message_container_length) resize_hash(target); target->c_message[target->c_message_length++] = (unsigned char)l; } } while(r == 1 && pos < strlen(input)); } /** * fills target with the hash in hex representation */ void to_string(const struct hash_t * hash, char target[65]) { return data_to_string(hash->hash, 8, target); } void data_to_string(const uint32_t * data, unsigned int len, char * target) { int i; for(i=0; i<len;++i) { sprintf(target+(i*8), "%08x", data[i]); } } void to_stdout(const struct hash_t * hash) { int i; for(i=0; i<8;++i) { printf("%08x", hash->hash[i]); } printf("\n"); } /************************* * Here begins the actual functions for sha256 ************************/ /** * Rotate word (a, b, c, d) to (b, c, d, a) with n positions */ uint32_t rotr(uint32_t word, int n) { return ( word >> n ) | (word << (32-n)); } void sha256_compute(struct hash_t * hash) { //sha256_padd_message(hash); int i; int N=hash->message_length/16; for(i=0;i<N;++i) { sha256_compute_round(hash, i); } } /** * Performs padding */ void sha256_padd_message(struct hash_t * hash) { uint64_t l_in_binary = (uint64_t) hash->c_message_length*8; //Get a 64-bit binary representation of message_length unsigned char * l = (unsigned char *)&l_in_binary; //Char pointer to l, to be able to get the msb order int k = (56-(hash->c_message_length+1))%64; //Bytes to padd //Check if we need to resize the container: if(hash->c_message_length+k+9 > hash->message_container_length) { //+3(bytes) comes from +1 (1000 0000) and then 8 bytes in the 64-bit representation of l hash->message_container_length = hash->c_message_length+k+3; hash->message = (uint32_t*) realloc(hash->message, hash->message_container_length); hash->c_message = (unsigned char*)hash->message; } //Append 1000 0000 = 0x80 hash->c_message[hash->c_message_length++] = 0x80; bzero(hash->c_message+hash->c_message_length, k); //Add k bytes of 0 hash->c_message_length+=k; //Add reversed byte order of l_in_binary int i=0; for(i=0;i<8;++i) { hash->c_message[hash->c_message_length++] = l[7-i]; } hash->message_length = hash->c_message_length/4; //Set message length (in number of uint32_t) //Reverse the *@(#&*@$ byte order. GAAAH for(i=0; i<hash->message_length;++i) { hash->message[i] = ntohl(hash->message[i]); } } void sha256_compute_round(struct hash_t * hash, int n) { uint32_t T[2]; uint32_t tmp[8]; uint32_t W[64]; int i; memcpy(W, hash->message+n*16, 64); //Copy the 16 words for this message block into W #if DEBUG printf("\n=============== ROUND %d =================\n", n+1); printf("Initial hash values:\n"); for(i=0;i<8;++i) { printf("H[%d] = %08x\n", i, hash->hash[i]); } printf("\nBlock contents:\n"); #endif #if DEBUG for(i=0;i<16;++i) printf("W[%d] = %08x\n", i, W[i]); #endif for(i=16; i<64;++i) { W[i] = SHA256_LITTLE_SIGMA1(W[i-2]) + W[i-7] + SHA256_LITTLE_SIGMA0(W[i-15]) + W[i-16]; } //Initialize the tmp variables: memcpy(tmp, hash->hash, 32); #if DEBUG printf("\n\n"); #endif for(i=0;i<64;++i) { T[0] = (tmp[7] + SHA256_BIG_SIGMA1(tmp[4]) + SHA256_CH(tmp[4], tmp[5], tmp[6]) + sha256_round_constants[i] + W[i]); T[1] = (SHA256_BIG_SIGMA0(tmp[0]) + SHA256_MAJ(tmp[0], tmp[1], tmp[2])); tmp[7] = tmp[6]; tmp[6] = tmp[5]; tmp[5] = tmp[4]; tmp[4] = (tmp[3]+T[0]); tmp[3] = tmp[2]; tmp[2] = tmp[1]; tmp[1] = tmp[0]; tmp[0] = (T[0] + T[1]); #if DEBUG printf("t=%2d: %08x %08x %08x %08x %08x %08x %08x %08x\n", i, tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], tmp[5], tmp[6], tmp[7]); #endif } #if DEBUG printf("\n\n"); #endif for(i=0;i<8; ++i) { #if DEBUG printf("H[%d] = %08x + %08x = ", i, hash->hash[i], tmp[i]); #endif hash->hash[i] += tmp[i]; #if DEBUG printf("%08x\n", hash->hash[i]); #endif } }
C
/* Nombre y Matrícula: Jaime Orlando López Ramos, A01374696 Fecha de Creación: 15/09/2020 Descripción: Implemente una función de cantidad de parámetros variable (variadic) que recibe parámetros enteros sin signo de 16 bits y retorna un entero sin signo de 32 bits. La salida de la función contiene los dos bits menos significativos del primer parámetro variable, luego el par de bits de las posiciones 2 y 3 del siguiente parámetro variable y así sucesivamente. */ #include <stdio.h> #include <stdarg.h> # define TRUE 1 # define FALSE 0 #include "headerExamen.h" unsigned long codificandoParesDeBits(unsigned int arr[50], int size){ if(size == 0){ return 0; } int masc = 3; unsigned long resultado = 0; int limite = size; if(limite > 16){ limite = 16; } for(int i = 0; i < limite; i++){ resultado += (masc << 2*i) & arr[i]; } return resultado; } unsigned long pairBits(unsigned int n, ...){ if(n == 0){ return 0; } va_list args; va_start(args, n); int limite = n; int masc = 3; unsigned long resultado = 0; if(limite > 16){ limite = 16; } for(unsigned int i = 0; i < n && i < 16; i++){ unsigned int aux = (unsigned int)va_arg(args, int); // printf("Representación en bits de %u: ", aux); // imprimirBinarioDe16BitsSinSigno(aux); resultado += (masc << 2*i) & aux; } va_end(args); // printf("Resultado en representación de 32 bits: "); // imprimirBinarioDe32BitsSinSigno(resultado); return resultado; } void imprimirBinarioDe16BitsSinSigno(unsigned int n){ unsigned int masc = 0x8000; for (int i = 0; i < 16; i++) { if((masc >> i)& n){ printf("1"); } else{ printf("0"); } } printf("\n"); } void imprimirBinarioDe32BitsSinSigno(unsigned long n){ unsigned long masc = 0x80000000; for (int i = 0; i < 32; i++) { if((masc >> i)& n){ printf("1"); } else{ printf("0"); } } printf("\n"); } int prueba0(){ if(pairBits(0) == 0){ return TRUE; } return FALSE; } int prueba3(){ unsigned long int esperado = 25; if(esperado == pairBits(3, 1, 8, 16)){ return TRUE; } return FALSE; } int prueba18(){ unsigned long int esperado = 65535; if(esperado == pairBits(18, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 0, 0)){ return TRUE; } return FALSE; } int main(int argc, char const *argv[]) { printf("%d\n", prueba0()); printf("%d\n", prueba3()); printf("%d\n", prueba18()); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <assert.h> #include <ctype.h> #include <string.h> #include "sort.h" #include <sys/stat.h> #include <limits.h> void usage(char *prog) { fprintf(stderr, "usage: %s <-i inputfile> <-o outputfile> <-l lowvalue> <-h highvalue>\n", prog); exit(1); } int compare (const void * a, const void * b) { rec_t *elemA = (rec_t *)a; rec_t *elemB = (rec_t *)b; return ( elemB->key - elemA->key ); } int main(int argc, char *argv[]) { // program assumes a 4-byte key in a 100-byte record assert(sizeof(rec_t) == 100); long long int lowvalue, highvalue; char *inFile = "/no/such/file"; char *outFile = "/no/such/file"; // input params int c; opterr = 0; while ((c = getopt(argc, argv, "i:o:l:h:")) != -1) { switch (c) { case 'i': inFile = strdup(optarg); break; case 'o': outFile = strdup(optarg); break; case 'l': lowvalue = atoll(optarg); if (lowvalue > UINT_MAX || lowvalue < 0){ fperror(stderr, "Error: Invalid range value"); exit(1); } else if(strlen(optarg) > lowvalue+1){ fprintf(stderr, "Error: Invalid range value"); exit(1); } break; case 'h': highvalue = atoll(optarg); if (highvalue > UINT_MAX || highvalue <0){ fprintf(stderr, "Error: Invalid range value"); exit(1); } else if(strlen(optarg) > highvalue+1){ fprintf(stderr, "Error: Invalid range value"); exit(1); } break; default: usage(argv[0]); } } printf("#########\n"); printf("%lld \n",lowvalue); printf("%lld \n",highvalue); printf("##########\n"); if (lowvalue > highvalue){ fprintf(stderr, "Error: Invalid range value"); exit(1); } // open and create output file int fd = open(inFile, O_RDONLY); if (fd < 0) { fprintf(stderr, "File Open Error"); exit(1); } struct stat buf; stat(inFile, &buf); int size = buf.st_size; rec_t * inputData; inputData = (rec_t *) malloc(size); int numElements = 0; while (1) { rec_t r; int rc; rc = read(fd, &r, sizeof(rec_t)); if (rc == 0) // 0 indicates EOF break; if (rc < 0) { perror("read"); exit(1); } if (r.key >= lowvalue && r.key <= highvalue) { inputData[numElements] = r; numElements++; } } //Apply quick sort here .... qsort(inputData, numElements, sizeof(rec_t), compare); int k; for(k = (numElements - 1);k>=0;k--) { printf("%u ", inputData[k].key); printf("\n"); } //Write in output file int fp = open(outFile, O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU); if (fp < 0) { perror("open"); exit(1); } int w; for (w=(numElements-1);w>=0;w--){ int x = write(fp, &inputData[w], sizeof(rec_t)); if (x != sizeof(rec_t)) { perror("write"); exit(1); } } (void) close(fd); (void) close(fp); free(inputData); return 0; }
C
#include <stdlib.h> #include <unistd.h> #include <signal.h> #include <stdio.h> // count for number of times buttons pressed static int interrupt = 0; static int quit = 0; static int count = 0; // handler function void init_signal_handlers(int signum){ //SIGINT (CTRL + C) //SIGQUIT (CTRL + Z) //SIGTSTP (CTRL + \) //print the letter for each signal, increase count, and exit after 3 stops switch(signum){ case SIGINT: printf("I"); fflush(stdout); interrupt += 1; break; case SIGQUIT: printf("Q"); fflush(stdout); quit += 1; break; case SIGTSTP: printf("S"); fflush(stdout); count += 1; if (count == 3){ printf("\nInterrupt: %d\nStop: %d\nQuit: %d\n", interrupt, quit, count); exit(signum); } break; default: return; } } int main(){ // sigaction struct struct sigaction Handler; // sigaction assigning handler Handler.sa_handler = init_signal_handlers; sigemptyset(&Handler.sa_mask); Handler.sa_flags = 0; sigaction(SIGINT, &Handler, NULL); sigaction(SIGQUIT, &Handler, NULL); sigaction(SIGTSTP, &Handler, NULL); // signal(SIGINT, init_signal_handlers); // signal(SIGQUIT, init_signal_handlers); while(1) sleep(1); }
C
#include <stdio.h> #include <stdlib.h> #include <conio.h> struct Node { int item; struct Node *pre; struct Node *next; }; int menu(void); void printMetaData(struct Node *); struct Node * searchItem(struct Node*, int); void deleteParticularNode(struct Node**, int); void deleteLastItemAtNode(struct Node**); void deleteFistItemAtNode(struct Node**); void addItemAfterNode(struct Node*, int); void addItemAtStart(struct Node**, int); void viewList(struct Node*); void addNode(struct Node**, int); int countItem(struct Node*); int main() { struct Node *start = NULL, *p=NULL; int item; while(1) { system("cls"); printMetaData(start); switch(menu()) { case 1: input(&item); addNode(&start, item); break; case 2: printf("Check item in the list or not\n"); scanf("%d",&item); if(p = searchItem(start,item)) { printf("Item has in the list\n"); input(&item); addItemAfterNode(p, item); } else printf("Item Not found"); break; case 3: addItemAtStart(&start, item); printf("Add Item at start"); break; case 4: printf("Check item in the list or not\n"); scanf("%d",&item); if(p = searchItem(start,item)) { deleteParticularNode(&p,item); } else printf("Item Not found"); break; case 5: deleteFistItemAtNode(&start); printf("First item deleted"); break; case 6: deleteLastItemAtNode(&start); printf("Deleted last item"); break; case 7: exit(0); break; default: printf("Invalid choice"); } getch(); } return 0; } void input(int *item) { printf("Enter your item -> "); scanf("%d", item); } void printMetaData(struct Node *n) { printf("List is empty -> %s\n",n != NULL ? "No": "Yes"); printf("You have %d items in list\n", countItem(n)); viewList(n); } int menu() { int choice; printf("\n\n1. Add item"); printf("\n2. Add item after item"); printf("\n3. Add item at first"); printf("\n4. Delete item"); printf("\n5. Delete first item"); printf("\n6. Delete last item"); printf("\n7. Exit"); printf("\nEnter your choice -> "); scanf("%d",&choice); return choice; }
C
/***************************************** DESCRIPTION: Implemet string functions: StrLen, StrCmp, StrCpy, StrNCpy, StrCaseCmp,StrChr, StrDup, StrCat, StrNCat, StrStr, StrSpn. Athor: Gal Dahan *****************************************/ #include <assert.h> /*for asserts*/ #include <stdio.h> /* for printf,size_t type */ #include <string.h> /* for compare string functions: strlen, strcpy, strchr, ... */ #include <strings.h> /* required for the strcasecmp function */ #include <stdlib.h> /* for the malloc, free functions */ #include <ctype.h> /* for the tolower function */ size_t StrLen(const char *str); int StrCmp(const char *str1, const char *str2); char *StrCpy(char *dest, const char *src); char *StrNCpy(char *dest, const char *src, size_t n); int StrCaseCmp(const char *s1, const char *s2); char *StrChr(const char *str, int c); char *StrDup(const char *src); char *StrCat(char *dest, const char *src); char *StrNCat(char *dest, const char *src, size_t n); char *StrStr(const char *haystack, const char *needle); size_t StrSpn(const char *s, const char *accept); /*return the lenght of string*/ size_t StrLen(const char *str) { size_t len = 0; assert(NULL != str); while ('\0' != *(str + len)) { ++len; } return len; } /*compare two string and return the difference in int*/ int StrCmp(const char *str1, const char *str2) { int i = 0; assert(NULL != str1); assert(NULL != str2); while (('\0' != *(str1 + i)) && (*(str1 + i) == *(str2 + i))) { ++i; } return str1[i] - str2[i]; } /*copy src to dest*/ char *StrCpy(char *dest, const char *src) { size_t size = StrLen(src); StrNCpy(dest, src, size); *(dest + size) = '\0'; return dest; } /*copy n chars from src to dest*/ char *StrNCpy(char *dest, const char *src, size_t n) { size_t i; assert(NULL != dest); assert(NULL != src); for (i = 0; (i < n) && (*(src + i) != '\0'); i++) { *(dest + i) = *(src + i); } /*Fill the rest of dest with '\0'*/ while (i < n) { *(dest + i) = '\0'; ++i; } return dest; } /*compare two string with no sensitive to capital letters return the difference in int*/ int StrCaseCmp(const char *s1, const char *s2) { int i = 0; int cmp = 0; assert(NULL != s1); assert(NULL != s2); while ('\0' != *(s1 + i)) { cmp = tolower((int) *(s1 + i)) - tolower((int) *(s2 + i)); if (0 != cmp) { return cmp; } ++i; } return cmp; } /*find char in string and return index char* to there*/ char *StrChr(const char *str, int c) { int i = 0; char* ptr = NULL; assert(NULL != str); for (i = 0; i < (int) StrLen(str); i++) { if ( *(str + i) == c ) { ptr = (char *) (str + i); } } return ptr; } /*creats new string with the same value and return pointer to there*/ char *StrDup(const char *src) { /*Space for length plus nul*/ char *dst = NULL; assert(NULL != src); dst = (char *) malloc(StrLen (src) + 1); /*No memory*/ if (NULL == dst) { return NULL; } StrCpy(dst, src); return dst; } char *StrCat(char *dest, const char *src) { StrCpy(dest + StrLen(dest), src); return dest; } char *StrNCat(char *dest, const char *src, size_t n) { size_t size = StrLen(dest); StrNCpy(dest + size, src, n); *(dest + size + n) = '\0'; return dest; } /*finds the first occurrence of the substring needle in the string haystack. The terminating null bytes ('\0') are not compared.*/ char *StrStr(const char *haystack, const char *needle) { int i = 0; int n_i = 0; int flag = 1; assert(NULL != haystack); assert(NULL != needle); /*while have enough space for needle*/ while ((StrLen(haystack) - i) >= StrLen(needle)) { n_i = 0; flag = 1; while (n_i < (int) StrLen(needle)) { if (*(haystack +i + n_i) != *(needle + n_i)) { flag = 0; } ++n_i; } if (1 == flag) { return (char *) (haystack +i); } ++i; } return NULL; } /*calculates the length of the initial segment of s which consists entirely of bytes in accept.*/ size_t StrSpn(const char *s, const char *accept) { size_t val = 0; int s_i = 0; assert(NULL != s); assert(NULL != accept); while ('\0' != *(s + s_i)) { if (NULL == StrChr(accept, *(s + s_i))) { return val; } ++val; ++s_i; } return val; }
C
#include<stdio.h> int array[500]; /************************* Binary Search ***************************/ int binary_search( int number , int size ) { int first=0 , last=size-1 , mid=size/2 , flag=0 ; // printf("%d %d " , first , last ); if( number < array[first] || number > array[last] ) printf("The number does not exist !\n "); //This eliminates one possibility of the worst case scenario of binary search //i.e. when the number to be searched is out of bound of numbers entered else { for( ; ; ) { //before checking any middle idex or anything //check wether the number is present at the first or last index if( number == array[first] ) { printf("Number found at %d position " , first + 1 ); flag=1 ; break; } if( number == array[last] ) { printf("Number found at %d position " , last + 1 ); flag=1 ; break; } //then check the middle index if( number == array[mid] ) { printf("Number found at %d position " , mid + 1 ); flag=1 ; break; } //shift to the later half if( number > array[mid] ) { //before going to the middle index for checking , check the index where the first and last currently are if( number == array[first] ) { printf("Number found at %d position " , first + 1 ); flag=1 ; break; } if( number == array[last] ) { printf("Number found at %d position " , last + 1 ); flag=1 ; break; } //increments the first to one index ahead and decrements the last index by one index first = mid + 1 ; last = last - 1 ; //before checking the middle check the first and last index if( number == array[first] ) { printf("Number found at %d position " , first + 1 ); flag=1 ; break; } if( number == array[last] ) { printf("Number found at %d position " , last + 1 ); flag=1 ; break; } //place the middle mid = (first + last) / 2 ; } //shift to the first half of the array else if( number < array[mid] ) { //checks the number at first and last index before checking the middle element if( number == array[first] ) { printf("Number found at %d position " , first + 1 ); flag=1 ; break; } if( number == array[last] ) { printf("Number found at %d position " , last + 1 ); flag=1 ; break; } last = mid - 1 ; first = first + 1 ; //checks the number at first and last index after incrementing first(to next place) and decrementing last(just before middle index) if( number == array[first] ) { printf("Number found at %d position " , first + 1 ); flag=1 ; break; } if( number == array[last] ) { printf("Number found at %d position " , last + 1 ); flag=1 ; break; } //placing middle at the index between the incremented first and decremented last index mid = (first + last) / 2 ; } if( mid == first || mid == last ) //if number is not present in the list break; } // if value of flag does not change after incrementing the loop , the number is not present if(flag != 1) printf("Number not found ! \n"); } } /***********************************************************************/ int *input(int size_array) { int i = 0 , j , num ; printf("(Enter the numbers in ascending order) \n "); for( i=0 ; i < size_array ; ++i ) { printf("Enter [%d] element :" , i+1 ); scanf( "%d" , &array[i] ) ; } for( j=0 ; j<size_array ; ++j) printf("%d\n", array[j]); return array; } int main() { int *address , number = 0 , size ; //will contain address of the array returned by input() printf("\nEnter the number of elements to be entered :"); scanf("%d" , &size) ; address = input(size) ; printf("\nEnter the number to be searched : "); scanf("%d", &number ) ; binary_search( number , size ); return 0; }
C
#include "main.h" /** * read_textfile- function that reads a text file and prints it to the stout. * @filename: pointer to name of the file * @letters: number of bytes to saved * Return: number of bytes print */ ssize_t read_textfile(const char *filename, size_t letters) { ssize_t count = 0; char *buff = malloc(letters); int fd = open(filename, O_RDONLY); if (buff == NULL) return (0); if (fd == -1 || filename == NULL) { free(buff); return (0); } count = read(fd, buff, letters); if (count == -1) { free(buff); return (0); } buff[count] = '\0'; if ((write(STDIN_FILENO, buff, count)) < 0) { free(buff); return (0); } close(fd); return (count); }
C
#include "ref.h" arm_status ref_mat_add_f32(const arm_matrix_instance_f32* pSrcA, const arm_matrix_instance_f32* pSrcB, arm_matrix_instance_f32* pDst) { uint32_t i; uint32_t numSamples; /* total number of elements in the matrix */ /* Total number of samples in the input matrix */ numSamples = (uint32_t)pSrcA->numRows * pSrcA->numCols; for (i = 0; i < numSamples; i++) { pDst->pData[i] = pSrcA->pData[i] + pSrcB->pData[i]; } return ARM_MATH_SUCCESS; } arm_status ref_mat_add_q31(const arm_matrix_instance_q31* pSrcA, const arm_matrix_instance_q31* pSrcB, arm_matrix_instance_q31* pDst) { uint32_t i; uint32_t numSamples; /* total number of elements in the matrix */ /* Total number of samples in the input matrix */ numSamples = (uint32_t)pSrcA->numRows * pSrcA->numCols; for (i = 0; i < numSamples; i++) { pDst->pData[i] = ref_sat_q31((q63_t)pSrcA->pData[i] + pSrcB->pData[i]); } return ARM_MATH_SUCCESS; } arm_status ref_mat_add_q15(const arm_matrix_instance_q15* pSrcA, const arm_matrix_instance_q15* pSrcB, arm_matrix_instance_q15* pDst) { uint32_t i; uint32_t numSamples; /* total number of elements in the matrix */ /* Total number of samples in the input matrix */ numSamples = (uint32_t)pSrcA->numRows * pSrcA->numCols; for (i = 0; i < numSamples; i++) { pDst->pData[i] = ref_sat_q15((q31_t)pSrcA->pData[i] + pSrcB->pData[i]); } return ARM_MATH_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> void dynamicAction() { //堆区开辟空间 malloc int *arr = malloc(10 * 1024); printf("arr 地址=%p, arr 地址=%p \n", &arr, arr); //释放堆区空间 free free(arr); } /** * 动态分配 * 在堆区开辟空间 malloc * 在栈区声明内存地址 * @return */ int main6(void) { while (9) { sleep(4); dynamicAction(); } return 0; }
C
#include <stdint.h> // Taken from stackoverflow (see http://stackoverflow.com/questions/3830883/cpu-cycle-count-based-profiling-in-c-c-linux-x86-64) // Can give nonsensical results on multi-core AMD processors. static inline uint64_t rdtsc() { uint32_t lo, hi; asm volatile ( "cpuid \n" /* serializing */ "rdtsc" : "=a"(lo), "=d"(hi) /* outputs */ : "a"(0) /* inputs */ : "%ebx", "%ecx"); /* clobbers*/ return ((uint64_t) lo) | (((uint64_t) hi) << 32); }
C
#include <stdio.h> #include <conio.h> void main() { int i,num,rev=0,sum,ini; printf("Enter a number:\n"); scanf("%d",&num); ini=num; loop: if(num>0){ sum=num%10; rev=rev*10+sum; num=num/10; if(num>0){ goto loop; } else{ printf("\nreverse of %d is %d",ini,rev); printf("\n"); if(ini==rev){ printf("\n%d is a palindrome",ini);} else{ printf("\n%d is not a palindrome",ini);} getch(); } } else printf("Enter a positive number."); }
C
/* University of Warwick -- CO904 Statistical Mechanics 2013 */ /* Ising model simulation based on code by Charo del Genio -- 2012 */ /* compile using: gcc Ising2d.c -o Ising2d */ /* run using: ./Ising2d [size] [initprob] [temperature] [number of sweeps] [seed] [output filename] */ /* BEGIN HEADER */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> /* global variables */ unsigned int STATE[32]; unsigned long int seed; /* prototypes */ void parameters(int nump, char *param[], int *size, double *initprob, double *temperature, int *sweeps, FILE **p_f_output); inline int DeltaIndex(const int x, const int y, const int size, int **spin); /* END HEADER */ //============================= int main(int argc, char *argv[]) { char outputfile[80]; int size, sweeps, DeltaE, x, y, diff, square, **spin; register int i, j, E=0, M=0; double initprob, temperature, Factors[5]; FILE *p_f_output; FILE *spin_output; // computing |m| during simulation (bad practice -- demonstration only) double abs_av_m=0.0; int t_av; /* Check parameters */ parameters(argc, argv, &size, &initprob, &temperature, &sweeps, &p_f_output); square = size*size; // square lattice only spin = malloc(size*sizeof(int*)); // allocate lattice spin[0] = malloc(square*sizeof(int)); for (i=1; i<size; i++) spin[i] = spin[i-1] + size; for (i=0; i<size; i++) for (j=0; j<size; j++) spin[i][j] = initprob > drand48() ? 1 : -1; // Create initial state /* Boltzmann factors */ Factors[0]=exp(-8.0/temperature); // All spins are equal to the one seeded DeltaE = 8 Factors[1]=exp(-4.0/temperature); // 1 spin is different DeltaE = 4 Factors[2]=1.0; // 2 spins are different DeltaE = 0 Factors[3]=exp(4.0/temperature); // 3 spins are different DeltaE = -4 Factors[4]=exp(8.0/temperature); // All spins are different DeltaE = -8 /* record initial state */ for (x=0; x<size; x++) for (y=0; y<size; y++) M += spin[x][y]; // Initial value of M /* print to file |m| */ // initial state // fprintf(p_f_output, "%.10f\t",fabs(((double) M)/square)); for (x=0; x<size; x++) for (y=0; y<size; y++) { // Initial value of E E -= spin[x][y] * spin[x==size-1 ? 0 : x+1][y]; E -= spin[x][y] * spin[x][y==size-1 ? 0 : y+1]; } /* print to file E */ // initial state // fprintf(p_f_output, "%d\n",E); /* Simulate using Metropolis */ for (i=1; i<=sweeps; i++) { // for each sweep for (j=1; j<=square; j++) { // run over the lattice size x = size * drand48(); // choose a spin at random y = size * drand48(); diff = DeltaIndex(x,y,size,spin); // look at the neighbours if ( drand48() < Factors[diff] ) { // if it flips spin[x][y] *= -1; // update it M += (2*spin[x][y]); // update M E += 4*(2-diff); // update E } } // end run over lattice size /* print to file |m| */ // calculate the average magnetisation (absolute value) -- bad practice, demonstration only if (i>10000) { // discard initialisation -- equilibration time t_av = i-10000; abs_av_m = abs_av_m * (((double) (t_av-1))/((double) t_av)) + fabs(((double) M)/square)/((double) t_av); } } // end sweep fprintf(p_f_output, "%.10f\t%.10f\n",temperature,abs_av_m); printf("Average |m| is: %.10f\n",abs_av_m); // output the final spin configuration for visualisation spin_output = fopen("spins.dat","w"); for (x=0; x<size; x++) { for (y=0; y<size; y++) { fprintf(spin_output, "%d\t",(spin[x][y] + 1)/2); } fprintf(spin_output,"\n"); } fclose(spin_output); // close file free(spin[0]); // free memory free(spin); fclose(p_f_output); // close file return EXIT_SUCCESS; } // end main //============================== /* Count how many spins point in a direction different from the one the spin at x,y points towards. Inlined for efficiency */ inline int DeltaIndex(const int x, const int y, const int size, int **spin) { int centre, diff=0; centre = spin[x][y]; if ( spin[x==0 ? size-1 : x-1][y] != centre ) diff++; if ( spin[x==size-1 ? 0 : x+1][y] != centre ) diff++; if ( spin[x][y==0 ? size-1 : y-1] != centre ) diff++; if ( spin[x][y==size-1 ? 0 : y+1] != centre ) diff++; return diff; } // end DeltaIndex /* Check user-provided parameters */ void parameters(int nump, char *param[], int *size, double *initprob, double *temperature, int *sweeps, FILE **p_f_output) { if (nump<7) { printf("\nUsage: %s [size] [prob] [temp] [sweeps] [seed] [output]\n\n",param[0]); printf("\t[size] is the dimension of each side of the 2d Ising lattice.\n"); printf("\t[prob] is the probability for each spin to initially point up.\n"); printf("\t[temp] is the temperature to simulate.\n"); printf("\t[sweeps] is the number of sweeps to run.\n"); printf("\t[seed] is the random number generator seed (positive integer).\n"); printf("\t[output] is the output file name.\n\n"); exit(EXIT_FAILURE); } *size = atoi(param[1]); if (*size<2) { printf("\nThe size of the model must be at least 2x2.\n\n"); exit(EXIT_FAILURE); } *initprob = atof(param[2]); if (*initprob<0.0 || *initprob>1.0) { printf("\nThe probability for each spin to initially point up must be between 0 and 1.\n\n"); exit(EXIT_FAILURE); } *temperature = atof(param[3]); *sweeps = atoi(param[4]); if (*sweeps<1) { printf("\nYou must run at least 1 sweep.\n\n"); exit(EXIT_FAILURE); } seed=strtoul(param[5],NULL,10); if (seed<=0) { printf("\nThe random number seed must be a positive integer.\n\n"); exit(EXIT_FAILURE); } // seedrng(); srand48(seed); /* if ( (*p_f_output = fopen(param[6],"r") ) != NULL ) { printf("\nError!\nOutput file %s already exists!\n\n",param[6]); exit(EXIT_FAILURE); } if ( (*p_f_output = fopen(param[6],"w") ) == NULL ) { printf("\nError creating output file %s.\n\n",param[6]); exit(EXIT_FAILURE); } */ if ( (*p_f_output = fopen(param[6],"a") ) == NULL ) { // currently I want to append to the file printf("\nError creating output file %s.\n\n",param[6]); exit(EXIT_FAILURE); } return; } // end parameters
C
#include "source.h" #include "error.h" #include "stringtab.h" #include "../../libponyrt/mem/pool.h" #include <stdlib.h> #include <string.h> #include <stdio.h> source_t* source_open(const char* file) { FILE* fp = fopen(file, "rb"); if(fp == NULL) { errorf(file, "can't open file"); return NULL; } fseek(fp, 0, SEEK_END); ssize_t size = ftell(fp); if(size < 0) { errorf(file, "can't determine length of file"); fclose(fp); return NULL; } fseek(fp, 0, SEEK_SET); source_t* source = POOL_ALLOC(source_t); source->file = stringtab(file); source->m = (char*)pool_alloc_size(size); source->len = size; ssize_t read = fread(source->m, sizeof(char), size, fp); if(read < size) { errorf(file, "failed to read entire file"); pool_free_size(source->len, source->m); POOL_FREE(source_t, source); fclose(fp); return NULL; } fclose(fp); return source; } source_t* source_open_string(const char* source_code) { source_t* source = POOL_ALLOC(source_t); source->file = NULL; source->len = strlen(source_code); source->m = (char*)pool_alloc_size(source->len); memcpy(source->m, source_code, source->len); return source; } void source_close(source_t* source) { if(source == NULL) return; if(source->m != NULL) pool_free_size(source->len, source->m); POOL_FREE(source_t, source); }
C
#include <stdlib.h> /** * _strdup - copy string * @str: original string * * Return: pointer to the copied string */ char *_strdup(char *str) { int l = 0; int i; char *copy; if (str == NULL) return (NULL); while (str[l] != '\0') l++; copy = malloc(l); if (!copy) return (NULL); for (i = 0; i < l; i++) copy[i] = str[i]; return (copy); }
C
#include<stdio.h> int main(){ int number; int x=2,y=3,z=3,k=1; printf("Enter the number => "); scanf("%d",&number); if(number%97==0){ printf("The number is divisible by 97\n"); } else{ printf("The number is not divisible\n"); } float result = 3*x/y-z+k; printf("The result is => %f",result); }
C
#pragma once typedef long long GameState; #define STATE_BIT(n) ((GameState)1 << n) #define BOARD_WIDTH 6 #define BOARD_HEIGHT 6 #define BOARD_CELLS (BOARD_WIDTH * BOARD_HEIGHT) #define SQUARE_SIZE 80 #define START_X 0 #define START_Y 0 enum Player { PLAYER_NONE = 0, PLAYER_BLACK, PLAYER_WHITE }; const GameState TopRowMask = STATE_BIT(BOARD_WIDTH) - 1; const GameState BottomRowMask = TopRowMask << (BOARD_WIDTH * (BOARD_HEIGHT - 1)); GameState PerformSwap(GameState s, int sp1, bool vertical); void GetScreenPos(int pos, int& x, int& y); bool GetMoveFromPos(int mx, int my, int& swapPos, bool& vertical); Player GetWinner(GameState s); Player OtherPlayer(Player p);
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> void run(); void help(); double square(double a); double rectangle(double a, double b); double triangle(double a, double b, double c); double circle(double r); void runSquare(); void runRectangle(); void runTriangle(); void runCircle(); int main(int argc, char **argv) { help(); run(); return 0; } void run() { char cmd[256]; while (1) { printf("> "); scanf("%s", cmd); if (strcasecmp(cmd, "square") == 0 || strcasecmp(cmd, "s") == 0) { runSquare(); } else if (strcasecmp(cmd, "rectangle") == 0 || strcasecmp(cmd, "r") == 0) { runRectangle(); } else if (strcasecmp(cmd, "triangle") == 0 || strcasecmp(cmd, "t") == 0) { runTriangle(); } else if (strcasecmp(cmd, "circle") == 0 || strcasecmp(cmd, "c") == 0) { runCircle(); } else if (strcasecmp(cmd, "help") == 0) { help(); } else if (strcasecmp(cmd, "exit") == 0) { break; } else { printf("Unknown command. Enter help to see list of commands\n"); } } printf("Have a good day!\n"); } void runSquare() { float a; printf("Enter variables: a\n"); printf("a = "); scanf("%f", &a); if (a < 0) { printf("Invalid data\n"); return; } printf("S = %.2f\n", (float)square(a)); } void runRectangle() { float a, b; printf("Enter variables: a, b\n"); printf("a = "); scanf("%f", &a); printf("b = "); scanf("%f", &b); if (a < 0 || b < 0) { printf("Invalid data\n"); return; } printf("S = %.2f\n", (float)rectangle(a, b)); } void runTriangle() { float a, b, c; printf("Enter variables: a, b, c\n"); printf("a = "); scanf("%f", &a); printf("b = "); scanf("%f", &b); printf("c = "); scanf("%f", &c); if (a < 0 || b < 0 || c < 0) { printf("Invalid data\n"); return; } printf("S = %.2f\n", (float)triangle(a, b, c)); } void runCircle() { float r; printf("Enter variables: r\n"); printf("r = "); scanf("%f", &r); if (r < 0) { printf("Invalid data\n"); return; } printf("S = %.2f\n", (float)circle(r)); } double square(double a) { return a * a; } double rectangle(double a, double b) { return a * b; } double triangle(double a, double b, double c) { const double p = (a + b + c) / 2; return sqrt(p * (p - a) * (p - b) * (p - c)); } double circle(double r) { const double PI = 3.14159265; return PI * r * r; } void help() { printf("Find the area of some figures \n"); printf("> square (s)\n"); printf("> rectangle (r)\n"); printf("> triangle (t)\n"); printf("> circle (c)\n"); printf("\n"); printf("> help \n"); printf("> exit \n"); printf("- - -\n\n"); }
C
#include<stdio.h> int main() { FILE *fptr1;FILE *fptr2; char ch; fptr1=fopen("myfile1.txt","r"); if(fptr1==NULL) { puts("Unable to open the file"); exit(1); } fptr2=fopen("myfile2.txt","w"); if(fptr2==NULL) { puts("Unable to open the file"); exit(2); } while(1) { ch=fgets(fptr1); if(ch==EOF) break; else fputs(ch,fptr2); } fclose(fptr1); fclose(fptr2); return 0; }
C
#include "spe_epoll.h" #include "spe_sock.h" #include "spe_util.h" #include "spe_log.h" #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/epoll.h> #include <sys/eventfd.h> #include <errno.h> struct spe_epoll_s { SpeTask_t* readTask; SpeTask_t* writeTask; unsigned mask:2; // mask set in epoll }; typedef struct spe_epoll_s spe_epoll_t; static int epfd; static int epoll_eventfd; static spe_epoll_t all_epoll[MAX_FD]; /* =================================================================================================== epollChange =================================================================================================== */ static bool epollChange(unsigned fd, spe_epoll_t* epoll_t, unsigned newmask) { if (epoll_t->mask == newmask) return true; // set epoll_event struct epoll_event ee; ee.data.u64 = 0; ee.data.fd = fd; ee.events = 0; if (newmask & SPE_EPOLL_READ) ee.events |= EPOLLIN; if (newmask & SPE_EPOLL_WRITE) ee.events |= EPOLLOUT; // set op type int op = EPOLL_CTL_MOD; if (epoll_t->mask == SPE_EPOLL_NONE) { op = EPOLL_CTL_ADD; } else if (newmask == SPE_EPOLL_NONE) { op = EPOLL_CTL_DEL; } if (epoll_ctl(epfd, op, fd, &ee) == -1) { SPE_LOG_ERR("epoll_ctl error: fd %d, %s", fd, strerror(errno)); return false; } epoll_t->mask = newmask; return true; } /* =================================================================================================== epollEnable =================================================================================================== */ bool epollEnable(unsigned fd, unsigned mask, SpeTask_t* task) { ASSERT(task); if (fd >= MAX_FD) return false; spe_epoll_t* epoll_t = &all_epoll[fd]; if (mask & SPE_EPOLL_READ) epoll_t->readTask = task; if (mask & SPE_EPOLL_WRITE) epoll_t->writeTask = task; return epollChange(fd, epoll_t, epoll_t->mask | mask); } /* =================================================================================================== epollDisable =================================================================================================== */ bool epollDisable(unsigned fd, unsigned mask) { if (fd >= MAX_FD) return false; spe_epoll_t* epoll_t = &all_epoll[fd]; if (mask & SPE_EPOLL_READ) epoll_t->readTask = NULL; if (mask & SPE_EPOLL_WRITE) epoll_t->writeTask = NULL; return epollChange(fd, epoll_t, epoll_t->mask & (~mask)); } static struct epoll_event epEvents[MAX_FD]; /* =================================================================================================== epollProcess =================================================================================================== */ void epollProcess(int timeout) { int events_n = epoll_wait(epfd, epEvents, MAX_FD, timeout); if (unlikely(events_n < 0)) { if (errno == EINTR) return; SPE_LOG_ERR("epoll_wait error: %s", strerror(errno)); return; } if (events_n == 0) return; // check events for (int i=0; i<events_n; i++) { struct epoll_event* e = &epEvents[i]; if (e->data.fd == epoll_eventfd) { uint64_t u; read(epoll_eventfd, &u, sizeof(uint64_t)); continue; } spe_epoll_t* epoll_t = &all_epoll[e->data.fd]; if ((e->events & EPOLLIN) && (epoll_t->mask & SPE_EPOLL_READ)) { SpeTaskEnqueue(epoll_t->readTask); } if ((e->events & EPOLLOUT) && (epoll_t->mask & SPE_EPOLL_WRITE)) { SpeTaskEnqueue(epoll_t->writeTask); } } } /* =================================================================================================== epollWakeup =================================================================================================== */ void epollWakeup(void) { uint64_t u = 1; if (write(epoll_eventfd, &u, sizeof(uint64_t)) <= 0) { SPE_LOG_ERR("epollWakeup error"); } } /* =================================================================================================== epollInit =================================================================================================== */ static bool epollInit(void) { epfd = epoll_create(1024); if (epfd < 0) { return false; } // create eventfd epoll_eventfd = eventfd(0, 0); SpeSockSetBlock(epoll_eventfd, 0); // set eventfd struct epoll_event ee; ee.data.u64 = 0; ee.data.fd = epoll_eventfd; ee.events = EPOLLIN; epoll_ctl(epfd, EPOLL_CTL_ADD, epoll_eventfd, &ee); return true; } /* =================================================================================================== epollFork =================================================================================================== */ void epollFork(void) { close(epoll_eventfd); close(epfd); epollInit(); } __attribute__((constructor)) static void epoll_init(void) { epollInit(); fprintf(stderr, "[ERROR] epoll init error\n"); exit(0); }
C
/* do_txbinary.c - do_txbinary */ #include <sys/types.h> #include <stdio.h> #include "telnet.h" char rcvbinary; /* non-zero if remote TRANSMIT-BINARY */ extern u_char option_cmd; /*------------------------------------------------------------------------ * do_txbinary - handle TELNET WILL/WON'T TRANSMIT-BINARY option *------------------------------------------------------------------------ */ /*ARGSUSED*/ int do_txbinary(rfp, tfp, c) FILE *rfp, *tfp; int c; { if (rcvbinary) { if (option_cmd == TCWILL) return 0; } else if (option_cmd == TCWONT) return 0; rcvbinary = !rcvbinary; (void) putc(TCIAC, rfp); if (rcvbinary) (void) putc(TCDO, rfp); else (void) putc(TCDONT, rfp); (void) putc((char)c, rfp); return 0; }
C
#include<stdio.h> #include<string.h> #include<ctype.h> //baekjoon 10824 void re(char arr[], int len) { char temp; for (int i = 0;i < len / 2;i++) { temp = arr[i]; arr[i] = arr[len - i - 1]; arr[len - i - 1] = temp; } } int main() { char num[8]; char com_num1[16] = { 0 }, com_num2[16] = { 0 }; char sum[16] = { 0 }; int carry = 0; int j = 0, len, a, b, c, d; for (int i = 0;i < 4;i++) { scanf("%s", num); len = strlen(num); if (i == 0) { for (a = 0;a < len;a++) com_num1[a] = num[a]; } if (i == 1) { for (b = a;b < a + len;b++) com_num1[b] = num[j++]; j = 0; } if (i == 2) { for (c = 0;c < len;c++) com_num2[c] = num[c]; } if (i == 3) { for (d = c;d < c+len;d++) com_num2[d] = num[j++]; j = 0; } } len = strlen(com_num1) > strlen(com_num2) ? strlen(com_num1) : strlen(com_num2); re(com_num1, strlen(com_num1)); re(com_num2, strlen(com_num2)); for (int i = 0;i < len;i++) { sum[i] = com_num1[i] + com_num2[i] + carry - '0'; if (com_num1[i] == NULL) sum[i] = com_num2[i] + carry ; else if (com_num2[i] == NULL) sum[i] = com_num1[i] + carry ; if (sum[i] > '9') { carry = 1; sum[i]-= 10; } else carry = 0; } if (carry == 1) sum[len] = '1'; re(sum, strlen(sum)); printf("%s", sum); return 0; } #include<stdio.h> //baekjoon 10824 int main() { long long a, b, c, d; char str[20]; long long A, B; scanf("%lld %lld %lld %lld", &a, &b, &c, &d); sprintf(str, "%lld%lld %lld%lld", a, b, c, d); sscanf(str, "%lld %lld", &A, &B); printf("%lld", A + B); return 0; }
C
// This is an example file for fsm2array %! 2 34 // The above defines two different states (0 and 1) and 34 different inputs (0...33) // To improve readability, we use the C-preprocessor to substitute numbers for named states // Run this file through `gcc -E -P' before handing it to fsm2array #define STATE1 0 #define STATE2 1 // A transition is specified as <state>, <input> => { actions... } STATE1, 31 => { 1, 1 } // Actions can be any number of comma-separated byte-values // The result will be a charater string composed of all action-values STATE1, 32 => { 1, 2 } // We can match `all other inputs' by a double asterisk // Other wildcards are also available: // *a matches all lower case letters // *A matches all upper case letters // *d matches all digits // *s matches all whitespace // They can be combined, e.g. *aA STATE1, ** => { 0, 0 } // The transition with the largest amount of actions // defines the length of each string in the output array STATE2, ** => { 0, 0, 1 } // We can also use an ASCII character as input ('!' has value 33) STATE2, '!' => { 1, 4 }
C
//--------------------------------------------------------- // file: Camera.c // author: Garry Chen // brief: Basic camera system // course: GAM100F18 // Copyright 2018 DigiPen, All rights reserved. //--------------------------------------------------------- #include<stdio.h> #include<stdlib.h> #include "C_Processing.h" #include "Physics.h" #include "Map.h" #include "Camera.h" #include "Player.h" //--------------------------------------------------------- // Private Consts: //--------------------------------------------------------- //--------------------------------------------------------- // Private Structures: //--------------------------------------------------------- //--------------------------------------------------------- // Public Variables: //--------------------------------------------------------- //--------------------------------------------------------- // Private Variables: //--------------------------------------------------------- //--------------------------------------------------------- // Private Function Declarations: //--------------------------------------------------------- //--------------------------------------------------------- // Public Functions: //--------------------------------------------------------- //--------------------------------------------------------- /************************************************************************** Function: createCamera Description: Create a new CAMERA sturct and initialize it with the parameterspassed by the caller. Inputs: window_left_edge Camera's detection box's left edge's x coordinate in the actual map. window_right_edge Camera's detection box's right edge's x coordinate in the actual map. screen_width Width of the game's window screen. Will be use as camera's collideBox's width. screen_height Height of the game's window screen. Will be use as camera's collideBox's height. map_left_edge Actual map's left edge x coordinate. map_right_edge Actual map's right edge x coordinate. Outputs: Pointer to the new CAMERA sturct. **************************************************************************/ CAMERA *createCamera(float window_left_edge, float window_right_edge, float screen_width, float screen_height, float map_left_edge, float map_right_edge) { CAMERA * new_c = (CAMERA *)malloc(sizeof(CAMERA)); /* Camera position start at (0, 0) */ new_c->position.x = 0; new_c->position.y = 0; new_c->collBox.position.x = 0; new_c->collBox.position.y = 0; new_c->collBox.size.x = screen_width; new_c->collBox.size.y = screen_height; new_c->map_left_edge = map_left_edge; new_c->map_right_edge = map_right_edge; new_c->window_left_edge = window_left_edge; new_c->window_right_edge = window_right_edge; return new_c; } /************************************************************************** Function: setCameraPosition Description: Change camera's position when player reach to its detection box. Inputs: cam Camera needed to change position. p Player's movement which may resualt camera change. Outputs: None. **************************************************************************/ void setCameraPosition(CAMERA * cam, player * p) { /* If player reach at the left edge of the camera detection box and there is still room left for camera to move left. */ if(p->collBox.position.x < cam->window_left_edge && cam->collBox.position.x > cam->map_left_edge) { /* dist1 = player and camera's distance difference. */ float dist1 = cam->window_left_edge - p->collBox.position.x; /* dist2 = camera edge and map edge's distance difference. */ float dist2 = cam->position.x - cam->map_left_edge; /* Check if there's enough room for camera to move left, if not just move as close as it can. */ if (dist2 < dist1) { dist1 = dist2; } if (dist1 < 0) dist1 = 0; /* Set new camera data to new position. */ cam->position.x -= dist1; cam->collBox.position.x -= dist1; cam->window_left_edge -= dist1; cam->window_right_edge -= dist1; } /* If player reach at the right edge of the camera detection box and there is still room left for camera to move right. */ else if ((p->collBox.position.x + p->collBox.size.x) > cam->window_right_edge && (cam->collBox.position.x + cam->collBox.size.x) < cam->map_right_edge) { /* dist1 = player and camera's distance difference. */ float dist1 = (p->collBox.position.x + p->collBox.size.x) - cam->window_right_edge; /* dist2 = camera edge and map edge's distance difference. */ float dist2 = cam->map_right_edge - (cam->collBox.position.x + cam->collBox.size.x); /* Check if there's enough room for camera to move left, if not just move as close as it can. */ if (dist2 < dist1) { dist1 = dist2; } if (dist1 < 0) dist1 = 0; /* Set new camera data to new position. */ cam->position.x += dist1; cam->collBox.position.x += dist1; cam->window_left_edge += dist1; cam->window_right_edge += dist1; } } /************************************************************************** Function: drawObj Description: Tanslate map coordinate of an object to screen coordinate and draw them on the screen. Inputs: cam Camera use to translate the coordinate. p Player needed to be draw. map Map contain tiles needed to be draw. Outputs: None. **************************************************************************/ void drawObj(CAMERA * cam, player * p, MAP *map) { int i, j; /* Draw all the tiles inside the camera range. */ for (i = 0; i < map->height; i++) { for (j = 0; j < map->width; j++) { /* Use collision to decide a tile is inside the camera screen. */ if (isCollide(((TILE*)map->bitmap + j + i * map->width)->collBox, cam->collBox)) { /* Draw green rectangle for the floor and wall. */ if (((TILE*)map->bitmap + j + i * map->width)->type == WALL || ((TILE*)map->bitmap + j + i * map->width)->type == FLOOR) { fill(0, 255, 0, 255); rect(j * map->tile_width - cam->position.x, i * map->tile_height - cam->position.y, map->tile_width, map->tile_height); } /* Draw orange circle for the goal. */ if (((TILE*)map->bitmap + j + i * map->width)->type == GOAL) { fill(255, 140, 0, 255); circleMode(CORNER); circle(j * map->tile_width - cam->position.x, i * map->tile_height - cam->position.y, map->tile_width / 2); } /* Draw cyan rectangle for the program exit block. */ if (((TILE*)map->bitmap + j + i * map->width)->type == EXIT) { fill(0, 255, 255, 255); rect(j * map->tile_width - cam->position.x, i * map->tile_height - cam->position.y, map->tile_width, map->tile_height); } /* Draw yellow rectangle for minus time collectibles. */ if (((TILE*)map->bitmap + j + i * map->width)->type == TIME) { fill(255, 255, 0, 255); rect(j * map->tile_width - cam->position.x +10, i * map->tile_height - cam->position.y + 10, map->tile_width - 20, map->tile_height - 20); } } } } /* Draw the player. */ fill(255, 0, 0, 255); rect(p->collBox.position.x - cam->position.x, p->collBox.position.y - cam->position.y, p->collBox.size.x, p->collBox.size.y); } //--------------------------------------------------------- //--------------------------------------------------------- // Private Functions: //---------------------------------------------------------
C
/* * Last modified: Fri, 15 Mar 2013 23:39:23 +0900 */ #include <stdio.h> #include "mycommon.h" int main(int argc, char* argv[]) { int r; printf("1問目: expected 0\n"); r = mystrncmp("abc", "abc", 3); printf(" Your answer %d\n\n", r); printf("2問目: expected 1\n"); r = mystrncmp("zyy", "zwy", 2); printf(" Your answer %d\n\n", r); printf("3問目: expected -1\n"); r = mystrncmp("ab", "aba", 3); printf(" Your answer %d\n\n", r); printf("4問目: expected 1\n"); r = mystrncmp("abc", "ab", 3); printf(" Your answer %d\n\n", r); printf("5問目: expected -1\n"); r = mystrncmp("", "abc", 3); printf(" Your answer %d\n\n", r); printf("6問目: expected 1\n"); r = mystrncmp("abc", "", 3); printf(" Your answer %d\n\n", r); printf("7問目: expected 1\n"); r = mystrncmp("abc", "", 4); printf(" Your answer %d\n\n", r); printf("8問目: expected -1\n"); r = mystrncmp("", "abc", 4); printf(" Your answer %d\n", r); return 0; }
C
char *ft_strncat(char *dest, char *src, unsigned int nb) { unsigned int a; unsigned int x; a = 0; x = 0; while (dest[a] != '\0') { a++; } while (x < nb && src[x]) { dest[a] = src[x]; a++; x++; } dest[a] = '\0'; return (dest); } #include <stdio.h> int main() { char a[20] = "1234"; char b[20] = "6789"; char *t = ft_strncat(a, b, 5); printf("%s\n", t); return (0); }
C
#include "pebble_os.h" #include "pebble_app.h" #include "pebble_fonts.h" #define MY_UUID {0x69, 0x5C, 0xE6, 0xFE, 0x5D, 0xC1, 0x43, 0x81, 0x85, 0x29, 0x9A, 0x82, 0xDB, 0x09, 0xA0, 0x69 } PBL_APP_INFO(MY_UUID, "Deprive Me", "Beshr Kayali", 0, 1, RESOURCE_ID_APP_ICON , APP_INFO_STANDARD_APP); Window window; TextLayer titleLayer; TextLayer minutesLayer; AppTimerHandle timer_handle; char *itoa(int num) { static char buff[20] = {}; int i = 0, temp_num = num, length = 0; char *string = buff; if(num >= 0) { // count how many characters in the number while(temp_num) { temp_num /= 10; length++; } // assign the number to the buffer starting at the end of the // number and going to the begining since we are doing the // integer to character conversion on the last number in the // sequence for(i = 0; i < length; i++) { buff[(length-1)-i] = '0' + (num % 10); num /= 10; } buff[i] = '\0'; // can't forget the null byte to properly end our string } else return "Unsupported Number"; return string; } // Decrease / Increase Minutes function + some other vars const int MoveMinutesBy = 5; const int MaxTopMin = 60; const int MaxLowMin = 5; static int TIMER = 25; static int AppStatus = 1; // 1: app main menu // 2: app timer // ----- // Pulsing Function const VibePattern custom_pattern = { .durations = (uint32_t []) {100, 700, 100, 200, 700, 100, 300, 100, 1000}, .num_segments = 9 }; // Timer Vars and Functions int pulseTimer = 5; void handle_timer(AppContextRef ctx, AppTimerHandle handle, uint32_t cookie) { if (cookie == 1) { // Timer-set checker if (AppStatus == 2){ text_layer_set_text(&titleLayer, "Timer Set"); text_layer_set_font(&minutesLayer, fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD)); text_layer_set_text(&minutesLayer, "Do Some Work!"); timer_handle = app_timer_send_event(ctx, TIMER * 60000, 2); }else{ timer_handle = app_timer_send_event(ctx, 1000, 1); } } if (cookie == 2) { // Timer Buzzed timer_handle = app_timer_send_event(ctx, 500, 3); } if (cookie == 3){ // Pulser if(pulseTimer > 1){ text_layer_set_text(&titleLayer, "STAY UP!"); vibes_enqueue_custom_pattern(custom_pattern); pulseTimer = pulseTimer - 1; timer_handle = app_timer_send_event(ctx, 500, 3); text_layer_set_text(&minutesLayer, itoa(pulseTimer)); }else{ text_layer_set_text(&titleLayer, "Timer Reset"); text_layer_set_text(&minutesLayer, ""); timer_handle = app_timer_send_event(ctx, TIMER * 60000, 2); pulseTimer = 5; } } // If you want the timer to run again you need to call `app_timer_send_event()` // again here. } // Modify these common button handlers void up_single_click_handler(ClickRecognizerRef recognizer, Window *window) { if (TIMER < MaxTopMin && AppStatus == 1){ TIMER = TIMER + MoveMinutesBy; text_layer_set_text(&minutesLayer, itoa(TIMER)); } } void down_single_click_handler(ClickRecognizerRef recognizer, Window *window) { if (TIMER > MaxLowMin && AppStatus == 1){ TIMER = TIMER - MoveMinutesBy; text_layer_set_text(&minutesLayer, itoa(TIMER)); } } void select_single_click_handler(ClickRecognizerRef recognizer, Window *window) { if(AppStatus == 1){ AppStatus = 2; text_layer_set_text(&titleLayer, "Done. I'll keep you up." ); } } void select_long_click_handler(ClickRecognizerRef recognizer, Window *window) { } // This usually won't need to be modified void click_config_provider(ClickConfig **config, Window *window) { config[BUTTON_ID_SELECT]->click.handler = (ClickHandler) select_single_click_handler; config[BUTTON_ID_SELECT]->long_click.handler = (ClickHandler) select_long_click_handler; config[BUTTON_ID_UP]->click.handler = (ClickHandler) up_single_click_handler; config[BUTTON_ID_UP]->click.repeat_interval_ms = 100; config[BUTTON_ID_DOWN]->click.handler = (ClickHandler) down_single_click_handler; config[BUTTON_ID_DOWN]->click.repeat_interval_ms = 100; } // Standard app initialisation void handle_init(AppContextRef ctx) { window_init(&window, "Deprive Me"); window_stack_push(&window, true /* Animated */); // Title text_layer_init(&titleLayer, GRect(0, 20, 140 /* width */, 50 /* height */)); text_layer_set_text_alignment(&titleLayer, GTextAlignmentCenter); text_layer_set_text(&titleLayer, "Use Up/Down Buttons to Set Deprivation Timer (minutes):"); text_layer_set_font(&titleLayer, fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD)); layer_add_child(&window.layer, &titleLayer.layer); text_layer_init(&minutesLayer, GRect(0, 70, 144 /* width */, 85 /* height */)); text_layer_set_text_alignment(&minutesLayer, GTextAlignmentCenter); text_layer_set_text(&minutesLayer, itoa(TIMER)); text_layer_set_font(&minutesLayer, fonts_get_system_font(FONT_KEY_BITHAM_42_BOLD)); text_layer_set_text_color(&minutesLayer, GColorWhite); text_layer_set_background_color(&minutesLayer, GColorBlack); layer_add_child(&window.layer, &minutesLayer.layer); // Attach our desired button functionality window_set_click_config_provider(&window, (ClickConfigProvider) click_config_provider); // Start status check timer timer_handle = app_timer_send_event(ctx, 1000, 1); } void pbl_main(void *params) { PebbleAppHandlers handlers = { .init_handler = &handle_init, .timer_handler = &handle_timer }; app_event_loop(params, &handlers); }
C
#include "dominion.h" #include "dominion_helpers.h" #include "rngs.h" #include <string.h> #include <stdio.h> #include <stdlib.h> int main(){ printf("Unit Test 4\n"); printf("Testing the getCost function\n"); int cardCost[27] = {0,2,5,8,0,3,6,6,5,4,4,5,4,4,3,4,3,5,3,5,3,4,2,5,4,4,4}; int cardNum[30] = {curse, estate, duchy, province, copper, silver, gold, adventurer, council_room, feast, gardens, mine, remodel, smithy, village, baron, great_hall, minion, steward, tribute, ambassador, cutpurse, embargo, outpost, salvager, sea_hag, treasure_map}; char *cardNames[27] = {"curse", "estate", "duchy", "province", "copper", "silver", "gold", "adventurer", "council_room", "feast", "gardens", "mine", "remodel", "smithy", "village", "baron", "great_hall", "minion", "steward", "tribute", "ambassador", "cutpurse", "embargo", "outpost", "salvager", "sea_hag", "treasure_map"}; int count = 0; int i; for(i = 0; i < 27; i++){ if(cardCost[i] == getCost(cardNum[i])){ count++; } else{ printf("%s is wrong\n", cardNames[i]); } } if(count == 27){ printf("\nAll cards passed\n"); }else{ printf("\nFailed\n"); } return 0; }
C
#include "fractol.h" #include "mlx.h" #include <stdio.h> #include <unistd.h> #include <math.h> #include <stdlib.h> #include "mandelbrot.h" #include "julia.h" static int reset_motin_vars(t_controler *c, int x, int y) { c->ml = 0; c->mr = 0; c->mu = 0; c->md = 0; if (x < 0 || y < 0 || x > c->mlx->x || y > c->mlx->y) return (0); return (1); } int motion_notify(int x, int y, void *data) { t_controler *c; c = (t_controler *)data; mlx_mouse_get_pos(c->mlx->window, &x, &y); if (!reset_motin_vars(c, x, y)) return (1); if (c->mlx->x / 5 > x) c->ml = 1; else if (c->mlx->x / 5 * 4 < x) c->mr = 1; if (c->mlx->y / 5 > y) c->mu = 1; else if (c->mlx->y / 5 * 4 < y) c->md = 1; if (x < 0 || x > c->mlx->x) { c->ml = 0; c->mr = 0; } if (y < 0 || y > c->mlx->y) { c->mu = 0; c->md = 0; } return (1); }
C
/* yuv4mpeg2.c */ #include <jd_pretty.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "colour.h" #include "yuv4mpeg2.h" static const char *tag[] = {"YUV4MPEG2", "FRAME"}; uint8_t y4m2_fill[Y4M2_N_PLANE] = {16, 128, 128}; uint8_t y4m2_min[Y4M2_N_PLANE] = {16, 16, 16}; uint8_t y4m2_max[Y4M2_N_PLANE] = {235, 240, 240}; y4m2_parameters *y4m2_new_parms(void) { return jd_alloc(sizeof(y4m2_parameters)); } void y4m2_free_parms(y4m2_parameters *parms) { int i; if (parms) { for (i = 0; i < Y4M2_PARMS; i++) jd_free(parms->parm[i]); jd_free(parms); } } static void y4m2__set(char **slot, const char *value) { if (*slot) jd_free(*slot); if (value) { size_t l = strlen(value); *slot = jd_alloc(l + 1); memcpy(*slot, value, l + 1); } else { *slot = NULL; } } y4m2_parameters *y4m2_merge_parms(y4m2_parameters *parms, const y4m2_parameters *merge) { if (merge) for (int i = 0; i < Y4M2_PARMS; i++) if (merge->parm[i]) y4m2__set(&(parms->parm[i]), merge->parm[i]); return parms; } y4m2_parameters *y4m2_clone_parms(const y4m2_parameters *orig) { return y4m2_merge_parms(y4m2_new_parms(), orig); } int y4m2__get_index(const char *name) { if (!name) return -1; if (strlen(name) != 1 || name[0] < Y4M2_FIRST || name[0] > Y4M2_LAST) return -1; return name[0] - Y4M2_FIRST; } const char *y4m2_get_parm(const y4m2_parameters *parms, const char *name) { int idx = y4m2__get_index(name); return idx >= 0 ? parms->parm[idx] : NULL; } void y4m2_set_parm(y4m2_parameters *parms, const char *name, const char *value) { int idx = y4m2__get_index(name); if (idx < 0) { fprintf(stderr, "Bad parameter name: %s\n", name); exit(1); } y4m2__set(&(parms->parm[idx]), value); } int y4m2_equal_parms(const y4m2_parameters *this, const y4m2_parameters *that) { if (this == NULL && that == NULL) return 1; if (this == NULL || that == NULL) return 0; for (unsigned i = 0; i < Y4M2_PARMS; i++) { if (this->parm[i] == NULL && that->parm[i] == NULL) continue; if (this->parm[i] == NULL || that->parm[i] == NULL) return 0; if (strcmp(this->parm[i], that->parm[i])) return 0; } return 1; } static unsigned parse_num(const char *s) { if (s) { char *ep; unsigned n = (unsigned)strtoul(s, &ep, 10); if (ep > s && *ep == '\0') return n; } fprintf(stderr, "Bad number"); exit(1); } static void set_planes(y4m2_frame_info *info, unsigned xsY, unsigned ysY, unsigned xsCb, unsigned ysCb, unsigned xsCr, unsigned ysCr) { size_t pix_size = info->width * info->height; info->plane[Y4M2_Y_PLANE].xs = xsY; info->plane[Y4M2_Y_PLANE].ys = ysY; info->plane[Y4M2_Y_PLANE].size = pix_size / (xsY * ysY); info->plane[Y4M2_Cb_PLANE].xs = xsCb; info->plane[Y4M2_Cb_PLANE].ys = ysCb; info->plane[Y4M2_Cb_PLANE].size = pix_size / (xsCb * ysCb); info->plane[Y4M2_Cr_PLANE].xs = xsCr; info->plane[Y4M2_Cr_PLANE].ys = ysCr; info->plane[Y4M2_Cr_PLANE].size = pix_size / (xsCr * ysCr); info->size = info->plane[Y4M2_Y_PLANE].size + info->plane[Y4M2_Cb_PLANE].size + info->plane[Y4M2_Cr_PLANE].size; } void y4m2_parse_frame_info(y4m2_frame_info *info, const y4m2_parameters *parms) { info->width = parse_num(y4m2_get_parm(parms, "W")); info->height = parse_num(y4m2_get_parm(parms, "H")); const char *cs = y4m2_get_parm(parms, "C"); if (!cs) cs = "420"; if (!strcmp("420", cs) || !strcmp("420jpeg", cs) || !strcmp("420mpeg2", cs) || !strcmp("420paldv", cs)) { set_planes(info, 1, 1, 2, 2, 2, 2); } else if (!strcmp("422", cs)) { set_planes(info, 1, 1, 2, 1, 2, 1); } else if (!strcmp("444", cs)) { set_planes(info, 1, 1, 1, 1, 1, 1); } else { fprintf(stderr, "Unknown colourspace %s\n", cs); exit(1); } } static void y4m2__set_plane_pointers(y4m2_frame *frame) { uint8_t *buf = frame->buf; for (int i = 0; i < Y4M2_N_PLANE; i++) { frame->plane[i] = buf; buf += frame->i.plane[i].size; } } y4m2_frame *y4m2_new_frame_info(const y4m2_frame_info *info) { y4m2_frame *frame = jd_alloc(sizeof(y4m2_frame)); frame->i = *info; frame->buf = jd_alloc(info->size); y4m2__set_plane_pointers(frame); return y4m2_retain_frame(frame); } y4m2_frame *y4m2_new_frame(const y4m2_parameters *parms) { y4m2_frame_info info; y4m2_parse_frame_info(&info, parms); return y4m2_new_frame_info(&info); } y4m2_frame *y4m2_like_frame(const y4m2_frame *frame) { y4m2_frame *nf = jd_alloc(sizeof(y4m2_frame)); *nf = *frame; nf->buf = jd_alloc(frame->i.size); nf->refcnt = 0; y4m2__set_plane_pointers(nf); return y4m2_retain_frame(nf); } y4m2_frame *y4m2_clone_frame(const y4m2_frame *frame) { y4m2_frame *nf = y4m2_like_frame(frame); memcpy(nf->buf, frame->buf, frame->i.size); return nf; } void y4m2_free_frame(y4m2_frame *frame) { if (frame) { jd_free(frame->buf); jd_free(frame); } } y4m2_frame *y4m2_retain_frame(y4m2_frame *frame) { if (frame) frame->refcnt++; return frame; } void y4m2_release_frame(y4m2_frame *frame) { if (frame && --frame->refcnt == 0) y4m2_free_frame(frame); } static char *is_word(char *buf, const char *match) { size_t l = strlen(match); if (strlen(buf) >= l && memcmp(buf, match, l) == 0 && buf[l] <= ' ') return buf + l; return NULL; } void y4m2__parse_parms(y4m2_parameters *parms, char *buf) { char name[2]; for (;;) { while (*buf == ' ') buf++; if (*buf < ' ') break; name[0] = *buf++; name[1] = '\0'; char *vp = buf; while (*buf > ' ') buf++; char t = *buf; *buf = '\0'; /* fprintf(stderr,"%s=%s\n",name,vp);*/ y4m2_set_parm(parms, name, vp); *buf = t; } } void y4m2__format_parms(FILE *out, const y4m2_parameters *parms) { for (int i = 0; i < Y4M2_PARMS; i++) if (parms->parm[i]) fprintf(out, " %c%s", Y4M2_FIRST + i, parms->parm[i]); } int y4m2_parse(FILE *in, y4m2_output *out) { size_t buf_size = 0; char *buf = NULL; y4m2_parameters *global = NULL; uint64_t sequence = 0; for (;;) { int c = getc(in); unsigned pos = 0; for (;;) { if (pos == buf_size) { buf_size *= 2; if (buf_size < 1024) buf_size = 1024; char *nb = realloc(buf, buf_size); if (NULL == nb) abort(); buf = nb; } if (c == EOF) goto done; if (c < ' ') { buf[pos++] = '\0'; break; } buf[pos++] = c; c = getc(in); } if (c == EOF) break; char *tail; if (tail = is_word(buf, tag[Y4M2_START]), tail) { if (global) y4m2_free_parms(global); global = y4m2_new_parms(); y4m2__parse_parms(global, tail); y4m2_emit_start(out, global); } else if (tail = is_word(buf, tag[Y4M2_FRAME]), tail) { y4m2_parameters *parms = y4m2_new_parms(); y4m2__parse_parms(parms, tail); y4m2_parameters *merged = y4m2_clone_parms(global); y4m2_merge_parms(merged, parms); y4m2_frame *frame = y4m2_new_frame(merged); frame->sequence = sequence++; size_t got = fread(frame->buf, 1, frame->i.size, in); if (got != frame->i.size) { fprintf(stderr, "Short read"); exit(1); } y4m2_emit_frame(out, parms, frame); y4m2_release_frame(frame); y4m2_free_parms(parms); y4m2_free_parms(merged); } else { fprintf(stderr, "Bad stream"); exit(1); } } done: y4m2_emit_end(out); return 0; } int y4m2_emit_start(y4m2_output *out, const y4m2_parameters *parms) { switch (out->type) { case Y4M2_OUTPUT_FILE: fputs(tag[Y4M2_START], out->o.f); y4m2__format_parms(out->o.f, parms); fputc(0x0A, out->o.f); break; case Y4M2_OUTPUT_NEXT: out->o.n.cb(Y4M2_START, parms, NULL, out->o.n.ctx); break; } return 0; } int y4m2_emit_frame(y4m2_output *out, const y4m2_parameters *parms, y4m2_frame *frame) { switch (out->type) { case Y4M2_OUTPUT_FILE: fputs(tag[Y4M2_FRAME], out->o.f); y4m2__format_parms(out->o.f, parms); fputc(0x0A, out->o.f); fwrite(frame->buf, 1, frame->i.size, out->o.f); break; case Y4M2_OUTPUT_NEXT: out->o.n.cb(Y4M2_FRAME, parms, frame, out->o.n.ctx); break; } return 0; } int y4m2_emit_end(y4m2_output *out) { switch (out->type) { case Y4M2_OUTPUT_FILE: break; case Y4M2_OUTPUT_NEXT: out->o.n.cb(Y4M2_END, NULL, NULL, out->o.n.ctx); y4m2_free_output(out); break; } return 0; } y4m2_output *y4m2_output_file(FILE *out) { y4m2_output *o = jd_alloc(sizeof(y4m2_output)); o->type = Y4M2_OUTPUT_FILE; o->o.f = out; return o; } y4m2_output *y4m2_output_next(y4m2_callback cb, void *ctx) { y4m2_output *o = jd_alloc(sizeof(y4m2_output)); o->type = Y4M2_OUTPUT_NEXT; o->o.n.cb = cb; o->o.n.ctx = ctx; return o; } void y4m2_free_output(y4m2_output *out) { jd_free(out); } static unsigned y4m2__log2(unsigned x) { unsigned shift = 0; while (x > (1u << shift)) shift++; return shift; } static void y4m2__plane_map(const y4m2_frame *in, uint8_t *plane[Y4M2_N_PLANE], unsigned xs[Y4M2_N_PLANE], unsigned ys[Y4M2_N_PLANE]) { uint8_t *bp = in->buf; for (unsigned p = 0; p < Y4M2_N_PLANE; p++) { plane[p] = bp; xs[p] = y4m2__log2(in->i.plane[p].xs); ys[p] = y4m2__log2(in->i.plane[p].ys); bp += in->i.plane[p].size; } } /* colourspace */ size_t y4m2_frame_to_float(const y4m2_frame *in, colour_floats *out) { uint8_t *plane[Y4M2_N_PLANE]; unsigned xs[Y4M2_N_PLANE], ys[Y4M2_N_PLANE]; unsigned width = in->i.width; unsigned height = in->i.height; y4m2__plane_map(in, plane, xs, ys); for (unsigned p = 0; p < Y4M2_N_PLANE; p++) { for (unsigned y = 0; y < height; y++) { for (unsigned x = 0; x < width; x++) { out[y * width + x].c[p] = plane[p][(y >> ys[p]) * (width >> xs[p]) + (x >> xs[p])]; } } } return width * height; } void y4m2_float_to_frame(const colour_floats *in, y4m2_frame *out) { uint8_t *plane[Y4M2_N_PLANE]; unsigned xs[Y4M2_N_PLANE], ys[Y4M2_N_PLANE]; unsigned width = out->i.width; unsigned height = out->i.height; y4m2__plane_map(out, plane, xs, ys); for (unsigned p = 0; p < Y4M2_N_PLANE; p++) { unsigned plw = width >> xs[p]; unsigned plh = height >> ys[p]; unsigned pxw = out->i.plane[p].xs; unsigned pxh = out->i.plane[p].ys; double area = pxw * pxh; for (unsigned y = 0; y < plh; y++) { for (unsigned x = 0; x < plw; x++) { double sum = 0; for (unsigned yy = 0; yy < pxh; yy++) for (unsigned xx = 0; xx < pxw; xx++) sum += in[((y << ys[p]) + yy) * width + (x << xs[p]) + xx].c[p]; double sample = sum / area; if (sample < 0) sample = 0; if (sample > 255) sample = 255; plane[p][y * plw + x] = (uint8_t)sample; } } } } /* vim:ts=2:sw=2:sts=2:et:ft=c */
C
#include<stdio.h> int main() { int i,table,count; printf("Enter table number&count\n"); scanf("%d",&table,&count); printf("The table is\n\n"); for(i=1;i<=count;i++) printf("%d*%d=%d\n",i,table,i*table); return 0; }
C
#ifndef __CSEARCHBUFFER_IMPL_H__ #define __CSEARCHBUFFER_IMPL_H__ //construct - create internal buffer CSearchBuffer::CSearchBuffer() { this->init(FILECONTENT_BUFLEN); } //construct - create internal buffer CSearchBuffer::CSearchBuffer(DWORD dwBufSize) { this->init(dwBufSize); } //release ALL the buffered memory! CSearchBuffer::~CSearchBuffer() { delete[] this->_lpszBuf; } // void CSearchBuffer::CopyBuffer(LPCTSTR lpszBuffer) { size_t x = 0; size_t y = 0; this->_dwLineSize = 0; this->_dwLineCount = 0; size_t nLineIndex = 0; //get the standardized max size (number of chars) that is present in each line of text this->_dwLineSize = this->getMaxLineSize(lpszBuffer); TCHAR c = lpszBuffer[x]; this->_lpszBuf[y] = NULL; while (c != NULL) { //reached end of the string buffer (null terminator) if (c == NULL) { this->_lpszBuf[y] = NULL; break; } //reached end of the line else if (c == 10 || c == 13) { if (y > 0 && (this->_lpszBuf[y-1] != NULL)) { //advance to next line this->_lpszBuf[y] = NULL; while(nLineIndex < this->_dwLineSize) { this->_lpszBuf[y++] = NULL; nLineIndex++; } this->_dwLineCount++; } nLineIndex = 0; } else if (ISWHITESPACE(c)) { //do nothing } else { this->_lpszBuf[y++] = c; this->_lpszBuf[y] = NULL; nLineIndex++; } c = toLowerCase(lpszBuffer[++x]); } } //search! the purpose of this class is to search efficiently for a string in a bigger string. BOOL CSearchBuffer::Search(CSafeString* pSearch) { DWORD dwLineIndex = 0; DWORD dwBufIndex = 0; BOOL bFound = FALSE; DWORD dwPrimaryIndex = 0; DWORD dwSecondaryIndex = 4; LPTSTR lpszBuf; /* get a primary search character to match; if this one doesn't match then the pointer will move to the next line. */ TCHAR cPrimary = toLowerCase(pSearch->GetChar(dwPrimaryIndex)); if (cPrimary != NULL) { /* get a secondary search character to match; if the first one matches, and the second one matches, the entire line can be searched. */ TCHAR cSecondary = toLowerCase(pSearch->GetChar(dwSecondaryIndex)); while(cSecondary == NULL) { dwSecondaryIndex--; cSecondary = toLowerCase(pSearch->GetChar(dwSecondaryIndex)); } //loop through 'lines' of buffer while (dwBufIndex < this->_dwBufSize) { lpszBuf = (this->_lpszBuf + dwBufIndex); if (lpszBuf[0] == NULL) break; //try to match the line if (lpszBuf[dwSecondaryIndex] == cSecondary) { if (lpszBuf[dwPrimaryIndex] == cPrimary) { if (pSearch->Equals(lpszBuf, FALSE)) { bFound = TRUE; break; } } } dwBufIndex += this->_dwLineSize; } } return bFound; } void CSearchBuffer::init(DWORD dwBufSize) { this->_dwLineSize = 0; this->_dwLineCount = 0; this->_dwBufSize = dwBufSize; this->_lpszBuf = new TCHAR[this->_dwBufSize]; memset(this->_lpszBuf, NULL, sizeof(TCHAR) * this->_dwBufSize); } DWORD CSearchBuffer::getMaxLineSize(LPCTSTR lpszBuffer) { TCHAR c = lpszBuffer[0]; size_t nIndex = 0; size_t nLineSize = 0; size_t nMaxLine = 0; while (c != NULL) { nLineSize++; if (nLineSize > nMaxLine) nMaxLine = nLineSize; if (c == 13 || c == 10) { nLineSize = 0; } c = lpszBuffer[++nIndex]; } return nMaxLine + 5; } #endif
C
/*****************************************************/ /*Author : Mahmoud Hamdy */ /*Version : V01 */ /*Date :2020-03-18 */ /*****************************************************/ #include "SYSTICK_interface.h" #include "SYSTICK_config.h" /*Registers*/ #define SYSTICK_BASE_ADDRESS (u32)(0xE000E010) #define SYSTICK_CTRL_ADDRESS (u32*)(SYSTICK_BASE_ADDRESS + 0x00) #define SYSTICK_LOAD_ADDRESS (u32*)(SYSTICK_BASE_ADDRESS + 0x04) #define SYSTICK_VAL_ADDRESS (u32*)(SYSTICK_BASE_ADDRESS + 0x08) #define SYSTICK_CALIB_ADDRESS (u32*)(SYSTICK_BASE_ADDRESS + 0x0C) /*This macro is a dummy value that will be written to the current value register to reset the timer*/ #define SYSTICK_RESET_DUMMY (u32)0xFFFFFFFF /*This pointer will hold the address of callback function passed using Set Callback Method*/ static SYSTICK_CallBackFunction_t CallbackFunction = NULL; /*APIs*/ /*Description: This API will be used to initialize the SYSTICK using configurations from SYSTICKconfig.h * Parameters: None * Return: None*/ void SYSTICK_voidInit(void) { /*Check clock configuration that the user entered, if he entered one of the valid * choices, then write them directly to the register * If a wrong configuration was entered, use the default which is SYSTICK_CLK_AHB8*/ if (SYSTICK_SOURCE_CLK_CONFIG == SYSTICK_CLK_AHB8) { *SYSTICK_CTRL_ADDRESS &= (u32)SYSTICK_CLK_AHB8; } else if (SYSTICK_SOURCE_CLK_CONFIG == SYSTICK_CLK_AHB) { *SYSTICK_CTRL_ADDRESS |= (u32)SYSTICK_CLK_AHB; } else { *SYSTICK_CTRL_ADDRESS &= (u32)SYSTICK_CLK_AHB8; } /*Check interrupt configuration that the user entered, if he entered one of the valid * choices, then write them directly to the register * If a wrong configuration was entered, use the default which is SYSTICK_INTERRUPT_DISABLE*/ if (SYSTICK_INTERRUPT_CONFIG == SYSTICK_INTERRUPT_DISABLE) { *SYSTICK_CTRL_ADDRESS &= (u32)SYSTICK_INTERRUPT_DISABLE; } else if (SYSTICK_INTERRUPT_CONFIG == SYSTICK_INTERRUPT_ENABLE) { *SYSTICK_CTRL_ADDRESS |= (u32)SYSTICK_INTERRUPT_ENABLE; } else { *SYSTICK_CTRL_ADDRESS &= (u32)SYSTICK_INTERRUPT_DISABLE; } /*Add threshold value to Reload register*/ *SYSTICK_LOAD_ADDRESS |= SYSTICK_RELOAD_VALUE; } /*Description: This API will be used to either enable or disable the SYSTICK timer * Parameters: Desired State (u32) * Return: Error Status (u8)*/ u8 SYSTICK_u8SetSYSTICKStatus(u32 Copy_u32Status) { /*This variable will hold the error status*/ u8 Local_u8ErrorStatus = STATUS_NOK; /*For enabling, the enable value will be ORed with the enable mask*/ if (Copy_u32Status == SYSTICK_ENABLE) { *SYSTICK_CTRL_ADDRESS |= SYSTICK_ENABLE; Local_u8ErrorStatus = STATUS_OK; } /*For disabling, the value will be AND with the complement of enable mask*/ else if (Copy_u32Status == SYSTICK_DISABLE) { *SYSTICK_CTRL_ADDRESS &= SYSTICK_DISABLE; Local_u8ErrorStatus = STATUS_OK; } return Local_u8ErrorStatus; } /*Description: This API will be used to either set callback function for SYSTICK Interrupt * Parameters: Pointer to desired function (u32) * Return: Error Status (u8)*/ u8 SYSTICK_u8SetCallBack(SYSTICK_CallBackFunction_t Copy_CallbackFunction) { /*This variable will hold the error status that will be returned at the end of the function*/ u8 Local_u8ErrorStatus=STATUS_NOK; /*If function doesn't equal null, then set call back function to passed function*/ if (Copy_CallbackFunction) { CallbackFunction = Copy_CallbackFunction; Local_u8ErrorStatus=STATUS_OK; } return Local_u8ErrorStatus; } /*Description: This handler will be executed when interrupt of systick is called * Parameters: None * Return: None*/ void SysTick_Handler (void) { /*Check if pointer to callback function is not null, if it is not null then call it*/ if (CallbackFunction) { CallbackFunction(); } } /*Description: This API will be used to either reset the SYSTICK timer * Parameters: None * Return: None*/ void SYSTICK_u8Reset(void) { /*Reset will be done by writing any value to current value register*/ *SYSTICK_VAL_ADDRESS |= SYSTICK_RESET_DUMMY; }
C
#include <stdio.h> int main() //Indicates start { int rec_area, radi, area, wid, leng, hei; float circ_area, trian_area; const double PI = 3.14; int rec_area = wid * leng; printf("enter 1 for the radious circle"); //Outputting to screen printf("Enter 2 for the width of the rectangle"); //Outputting to screen printf("Enter 3 for the length of the triangle"); //outputting to screen printf("Enter 4 for the program to quit"); //Outputting to screen while (1 == 1) { printf("Choose Your option : "); scanf("%i", &area); switch (area) { case 1: printf("enter the radious of a circle\n"); scanf("%i", &radi); printf(" enter the area of a circle. \n"); circ_area = PI * radi * radi; printf("area of the circle is %f", &circ_area); break; case 2: printf("enter the width of a rectangle"); scanf("%i", &wid); printf("enter the length of the rectangle"); scanf("%i", &leng); printf("enter the area of the rectangl"); printf("Rectangular Area =%d", &trian_area); break; case 3: printf("enter the length of a triangle"); scanf("%i", &leng); printf("enter the height of a triangle"); printf("%i", &hei); trian_area = leng * hei / 2; printf("Triangle Area=%5.2f", &trian_area); break; case 4: printf("program quit"); return 0; } } }
C
/************************************************************************* > File Name: 13.c > Author: > Mail: > Created Time: 2019年11月26日 星期二 20时56分50秒 ************************************************************************/ #include<stdio.h> int main() { int n,a=1; scanf("%d",&n); for(int i = 0;i < n;i ++) { int temp; scanf("%d",&temp); a = a * temp; } printf("%d",a); return 0; }
C
// 3) Escreva um algoritmo que receba um número e imprima uma das mensagens: “é múltiplo de 3” ou “não é múltiplo de 3”. // // Início // Inteiro: n; // Leia(n); // Se n mod 3 = 0 Então // Escreva("é múltiplo de 3"); // Senão // Escreva("não é múltiplo de 3"); // Fim // #include <stdio.h> #include <wchar.h> #include <locale.h> int main(){ setlocale(LC_ALL, ""); long n; printf("%ls", L"Informe um número: "); scanf("%ld", &n); if (n % 3 == 0) printf("%ls", L"é múltiplo de 3"); else printf("%ls", L"Não é múltiplo de 3"); return 0; }
C
#pragma once #ifndef _HUFFMAN_H #define _HUFFMAN_H //huffman树树节点结构 typedef struct _htNode { char symbol; struct _htNode *left, *right; }htNode; //huffman树 根结点 typedef struct _htTree { htNode *root; }htTree; //label结点 typedef struct _hlNode { char symbol; char *code; struct _hlNode *next; }hlNode; //label表 typedef struct _hlTable { hlNode *first; hlNode *last; }hlTable; //使用指定字符串inputString,创建huffman树 htTree *buildTree(char *inputString); //使用创建的huffmanTree树,创建hlTable表 hlTable *buildTable(htTree *huffmanTree); //使用table表,对指定字符串stringToEncode进行编码压缩(逐字符编码成二进制数) void encode(hlTable *table, char *stringToEncode); //使用huffman tree,解压指定的编码stringToDecode void decode(htTree *tree, char *stringToDecode); #endif
C
#pragma once #include <stdint.h> struct mp_uint128_t { mp_uint128_t() { w[0]=w[1]=0; } mp_uint128_t(uint64_t a) { w[0]=a; w[1]=0; } mp_uint128_t(uint64_t w0, uint64_t w1) { w[0]=w0; w[1]=w1; } mp_uint128_t(const uint64_t a[2]) { w[0]=a[0]; w[1]=a[1]; } mp_uint128_t& operator+=(const mp_uint128_t& a) { return add(a); } mp_uint128_t& operator-=(const mp_uint128_t& a) { return sub(a); } mp_uint128_t& operator*=(const mp_uint128_t& a) { return mul(a); } mp_uint128_t& operator*=(uint64_t a) { return mul(a); } mp_uint128_t& operator+=(uint64_t a) { return add(a); } mp_uint128_t& operator-=(uint64_t a) { return sub(a); } mp_uint128_t& add(const mp_uint128_t& a); mp_uint128_t& sub(const mp_uint128_t& a); mp_uint128_t& mul(uint64_t a); mp_uint128_t& mul(const mp_uint128_t& a); mp_uint128_t half() const; uint64_t w[2]; }; mp_uint128_t double2uint128(double a); static inline int cmp(const mp_uint128_t& a, const mp_uint128_t& b) { if (a.w[1] > b.w[1]) return 1; if (a.w[1] < b.w[1]) return -1; if (a.w[0] > b.w[0]) return 1; if (a.w[0] < b.w[0]) return -1; return 0; } struct mp_uint256_t { mp_uint256_t() { w[0]=w[1]=w[2]=w[3]=0; } mp_uint256_t(uint64_t a) { w[0]=a; w[1]=w[2]=w[3]=0; } mp_uint256_t(uint64_t w0,uint64_t w1,uint64_t w2,uint64_t w3) { w[0]=w0; w[1]=w1; w[2]= w2; w[3]=w3; } mp_uint256_t(const mp_uint128_t& a) { w[0]=a.w[0]; w[1]=a.w[1]; w[2]=w[3]=0; } mp_uint256_t(const uint64_t a[3]) { w[0]=a[0]; w[1]=a[1]; w[2]=a[2]; w[3]=a[3]; } uint64_t w[4]; }; mp_uint256_t mulx(const mp_uint128_t& a, const mp_uint128_t& b); mp_uint256_t add(const mp_uint256_t& a, const mp_uint256_t& b); mp_uint256_t sub(const mp_uint256_t& a, const mp_uint256_t& b); mp_uint128_t mulu(const mp_uint128_t& a, const mp_uint128_t& b);
C
/* * opt - three pass optimiser for small-C compiler * (Small C compiler is Z80 version on CP/M UG UK Vol 15) * * usage: optimise source-file * sources-file is assumed to have extension .zsm * output file has extension .opt * * Program written by: R M Yorston * 147a Evesham Road * Headless Cross * Redditch * Worcs B97 4LJ * * This program is completely and utterly in the public domain: * do whatever you like with it except sell it. * */ #include crun2.lib #include conio2.lib #include file2.lib #include string.lib #include numio2.lib #define TRUE 1 #define FALSE 0 #define NULL 0 #define TAB 9 #define LF 10 #define CR 13 #define EOF 26 #define SPACE 32 int Ichan, Ochan ; char Line1[256], Line2[256], Line3[256], Line[256] ; char *Lastline, *Thisline, *Nextline, *Temp, *Tail ; int Saved[9] ; #asm ;/* ; * match - match token against string ; * returns NULL if no match ; * else returns pointer to Tail of string ; */ ;match( token, input ) ;char *token, *input ; ;{ ; while ( *input++ == *token++ ) ; ; --token ; ; if ( *token == NULL ) ; return --input ; ; else ; return NULL ; ;} ; match: POP BC POP HL ;HL is input POP DE ;DE is token PUSH DE PUSH HL PUSH BC match1: LD A,(DE) ;fetch *token CP (HL) JP NZ,match2 ;return if *token != *input INC HL INC DE JP match1 match2: OR A RET Z ;return input if *token == NULL LD HL,0 ;else return 0 RET #endasm main( argc,argv ) int argc,argv[] ; { char file1[20], file2[20] ; char *pin ; if (argc==1) { puts("\nNo input file\n\n") ; exit(); } if (argc>=3) { puts("\nCommand line error\n\n") ; exit(); } pin = argv[1] ; strcpy( file1, pin ) ; strcat( file1, ".ZSM") ; strcpy( file2, pin ) ; strcat( file2, ".OPT") ; open( file1, file2 ) ; pass1() ; open( file2, file1 ) ; pass2() ; open( file1, file2 ) ; pass3() ; exit() ; } /* * open - open f1 for reading, f2 for writing * Ichan is input channel number * Ochan is output channel number */ open( f1, f2 ) char *f1, *f2 ; { Ichan = fopen( f1, "r") ; if ( Ichan == 0 ) { puts("Cannot open file") ; exit() ; } Ochan = fopen( f2, "w") ; if ( Ochan == 0 ) { puts ("Cannot open file") ; exit() ; } } /* * getline - fetch line from input channel * puts line at pointer, returns FALSE on end of file * returns TRUE for successful get */ getline( pointer ) char *pointer ; { char ch ; while ( ((ch=getc(Ichan)) != EOF) & (eof()==0) ) { if( ch == CR ) { *pointer = NULL ; getc(Ichan) ; return TRUE ; } else *pointer++ = ch ; } return FALSE ; } /* * putline - send line to output file */ putline( pointer ) char *pointer ; { while ( *pointer ) { putc( *pointer++, Ochan ) ; } putc( CR, Ochan ) ; putc( LF, Ochan ) ; } /* * allnum - checks if string consists entirely of decimal numbers * returns TRUE if it does */ allnum( string ) char *string ; { while ( *string ) { if ( (*string<'0') | (*string>'9') ) { return FALSE ; } ++string ; } return TRUE ; } pass1() { int i ; Saved[0] = Saved[1] = Saved[2] = Saved[3] = Saved[4] = 0 ; Saved[5] = Saved[6] = Saved[7] = 0 ; getline( Line1 ) ; getline( Line2 ) ; Lastline = Line1 ; Thisline = Line2 ; Nextline = Line3 ; while ( getline( Nextline ) ) { /* negative constant */ if (strcmp(" CALL ccneg", Nextline) == 0) { if ( (Tail=match(" LD HL,",Thisline)) != NULL ) { if ( allnum( Tail ) ) { strcpy( Line, " LD HL,0-") ; strcat( Line, Tail ) ; strcpy( Thisline, Line ) ; getline( Nextline ) ; ++Saved[0] ; } } } /* double constant */ if ( strcmp(" ADD HL,HL",Nextline) == 0 ) { if( (Tail=match(" LD HL,",Thisline)) != NULL ) { if( allnum( Tail ) ) { strcpy( Line, " LD HL,2*") ; strcat( Line, Tail ) ; strcpy( Thisline, Line ) ; getline( Nextline ) ; ++Saved[4] ; } } } /* push and pop round ld hl */ if ( (strcmp(" PUSH HL", Lastline) == 0) ) { if ( (strcmp(" POP DE", Nextline) == 0) ) { if ( match(" LD HL,",Thisline) != NULL ) { strcpy( Lastline, " EX DE,HL") ; getline(Nextline) ; ++Saved[1] ; } } } /* zero subscript */ if ( strcmp(" EX DE,HL",Lastline) == 0 ) { if ( (strcmp(" LD HL,0",Thisline) == 0) | (strcmp(" LD HL,2*0",Thisline) == 0) ) { if ( strcmp(" ADD HL,DE",Nextline) == 0 ) { strcpy(Lastline," LD D,H") ; strcpy(Thisline," LD E,L") ; getline(Nextline) ; ++Saved[2] ; } } } /* one subscript */ if ( strcmp(" EX DE,HL",Lastline) == 0 ) { if ( strcmp(" LD HL,1",Thisline) == 0 ) { if ( strcmp(" ADD HL,DE",Nextline) == 0 ) { strcpy(Lastline," LD D,H") ; strcpy(Thisline," LD E,L") ; strcpy(Nextline," INC HL") ; ++Saved[3] ; } } } /* two subscript */ if ( strcmp(" EX DE,HL",Lastline) == 0 ) { if ( (strcmp(" LD HL,2",Thisline) == 0) | (strcmp(" LD HL,2*1",Thisline) == 0) ) { if ( strcmp(" ADD HL,DE",Nextline) == 0 ) { putline(" LD D,H") ; strcpy(Lastline," LD E,L") ; strcpy( Thisline, " INC HL") ; strcpy( Nextline, " INC HL") ; ++Saved[6] ; } } } /* fetch int from top of stack */ if ( strcmp(" LD HL,0", Lastline) == 0 ) { if ( strcmp(" ADD HL,SP", Thisline) == 0 ) { if ( strcmp(" CALL ccgint", Nextline ) == 0 ) { strcpy( Lastline, " POP HL") ; strcpy( Thisline, " PUSH HL") ; getline( Nextline ) ; ++Saved[7] ; } } } /* fetch second int from top of stack */ if ( strcmp(" LD HL,2", Lastline) == 0 ) { if ( strcmp(" ADD HL,SP", Thisline) == 0 ) { if ( strcmp(" CALL ccgint", Nextline ) == 0 ) { putline(" POP BC") ; strcpy( Lastline, " POP HL") ; strcpy( Thisline, " PUSH HL") ; strcpy( Nextline, " PUSH BC ") ; ++Saved[5] ; } } } putline( Lastline ) ; Temp = Lastline ; Lastline = Thisline ; Thisline = Nextline ; Nextline = Temp ; } putline( Lastline ) ; putline( Thisline ) ; puts("Negative constants: "); putdec(Saved[0]) ; crlf() ; puts("Double constants: "); putdec(Saved[4]) ; crlf() ; puts("PUSH HL, POP DE round LD HL: "); putdec(Saved[1]) ; crlf() ; puts("Zero subscript: "); putdec(Saved[2]) ; crlf() ; puts("One subscript: "); putdec(Saved[3]) ; crlf() ; puts("Two subscript: "); putdec(Saved[6]) ; crlf() ; puts("Fetch top of stack: "); putdec(Saved[7]) ; crlf() ; puts("Fetch 2nd top of stack: "); putdec(Saved[5]) ; crlf() ; crlf() ; i = Saved[0]*3 + Saved[1] + Saved[2]*3 + Saved[3]*2 + Saved[4] ; i = i + Saved[5]*3 + Saved[6] + Saved[7]*5 ; puts("Total bytes saved: ") ; putdec( i ) ; crlf() ; fclose( Ichan ) ; fclose( Ochan ) ; } pass2() { int i ; Saved[0] = Saved[1] = Saved[2] = Saved[3] = Saved[4] = 0 ; Saved[5] = Saved[6] = Saved[7] = Saved[8] = 0 ; getline( Line1 ) ; getline( Line2 ) ; Lastline = Line1 ; Thisline = Line2 ; Nextline = Line3 ; while ( getline( Nextline ) ) { /* double EX DE,HL */ if ( strcmp(" EX DE,HL",Lastline) == 0 ) { if ( strcmp(" EX DE,HL",Thisline) == 0 ) { Temp = Lastline ; Lastline = Nextline ; Nextline = Temp ; getline( Thisline ) ; getline( Nextline ) ; ++Saved[0] ; } } /* DE<-HL followed by EX DE,HL */ if ( strcmp(" LD D,H",Lastline) == 0 ) { if ( strcmp(" LD E,L",Thisline) == 0 ) { if ( strcmp(" EX DE,HL",Nextline) == 0 ) { getline(Nextline) ; ++Saved[1] ; } } } /* DE<-HL followed by LD HL */ if ( strcmp(" LD D,H",Lastline) == 0 ) { if ( strcmp(" LD E,L",Thisline) == 0 ) { if ( match(" LD HL,",Nextline) != 0 ) { strcpy( Lastline, " EX DE,HL") ; Temp = Thisline ; Thisline = Nextline ; Nextline = Temp ; getline(Nextline) ; ++Saved[2] ; } } } /* expand ccpchar */ if ( strcmp(" CALL ccpchar",Lastline) == 0 ) { putline(" LD A,L") ; strcpy( Lastline, " LD (DE),A") ; ++Saved[8] ; } /* ccgint to DE expanded */ if ( strcmp(" CALL ccgint",Lastline) == 0 ) { if ( strcmp(" EX DE,HL",Thisline) == 0 ) { if ( match(" LD HL,",Nextline) != NULL ) { putline(" LD E,(HL)") ; strcpy( Lastline, " INC HL") ; strcpy( Thisline, " LD D,(HL)") ; ++Saved[3] ; } } } /* expand ccgint */ if( strcmp(" CALL ccgint", Lastline) == 0 ) { putline(" LD A,(HL)") ; putline(" INC HL") ; putline(" LD H,(HL)") ; strcpy( Lastline, " LD L,A") ; ++Saved[4] ; } /* expand ccpint */ if ( strcmp(" CALL ccpint", Lastline) == 0 ) { putline(" LD A,L") ; putline(" LD (DE),A") ; putline(" INC DE ") ; putline(" LD A,H") ; strcpy( Lastline, " LD (DE),A") ; ++Saved[5] ; } /* expand ccgchar to DE */ if ( strcmp(" CALL ccgchar",Lastline) == 0 ) { if ( strcmp(" EX DE,HL",Thisline) == 0 ) { if ( match(" LD HL,",Nextline) != NULL ) { putline(" LD A,(HL)") ; putline(" LD E,A") ; putline(" RLCA") ; strcpy( Lastline, " SBC A,A") ; strcpy( Thisline, " LD D,A") ; ++Saved[6] ; } } } /* expand ccgchar */ if ( strcmp(" CALL ccgchar",Lastline) == 0 ) { putline(" LD A,(HL)") ; putline(" LD L,A") ; putline(" RLCA") ; putline(" SBC A,A" ) ; strcpy( Lastline, " LD H,A" ) ; ++Saved[7] ; } putline( Lastline ) ; Temp = Lastline ; Lastline = Thisline ; Thisline = Nextline ; Nextline = Temp ; } putline( Lastline ) ; putline( Thisline ) ; puts("Double EX DE,HL: "); putdec(Saved[0]) ; crlf() ; puts("DE<-HL, followed by EX DE,HL: "); putdec(Saved[1]) ; crlf() ; puts("DE<-HL, followed by LD HL: "); putdec(Saved[2]) ; crlf() ; puts("Expand ccpchar: "); putdec(Saved[8]) ; crlf() ; puts("Expand ccgint to DE: "); putdec(Saved[3]) ; crlf() ; puts("Expand ccgint: "); putdec(Saved[4]) ; crlf() ; puts("Expand ccpint: "); putdec(Saved[5]) ; crlf() ; puts("Expand ccgchar to DE: "); putdec(Saved[6]) ; crlf() ; puts("Expand ccgchar: "); putdec(Saved[7]) ; crlf() ; crlf() ; i = Saved[0]*2 + Saved[1] + Saved[2] + Saved[3] - Saved[4] ; i = i - Saved[5]*2 - Saved[6] - Saved[7]*2 + Saved[8] ; puts("Total bytes saved: ") ; putdec( i ) ; crlf() ; fclose( Ichan ) ; fclose( Ochan ) ; } /* * islower - returns TRUE if character is lower case, else FALSE */ islower( ch ) char ch ; { return ((ch >= 'a') & (ch <= 'z')) ; } /* * uncomma - split string with two tokens separated by commas */ uncomma( string, token1, token2 ) char *string, *token1, *token2 ; { while ( *string != ',' ) *token1++ = *string++ ; *token1 = 0 ; ++string ; strcpy( token2, string ) ; } pass3() { char source1[20], source2[20], dest1[20], dest2[20] ; char *tail2 ; int i ; Saved[0] = Saved[1] = Saved[2] = Saved[3] = Saved[4] = 0 ; Saved[5] = Saved[6] = 0 ; getline( Line1 ) ; getline( Line2 ) ; Lastline = Line1 ; Thisline = Line2 ; Nextline = Line3 ; while ( getline( Nextline ) ) { /* ld hl, ex, ld hl -> ld de, ld hl */ if ( (Tail=match(" LD HL,",Lastline)) != NULL ) { if ( strcmp(" EX DE,HL",Thisline) == 0 ) { if ( match(" LD HL,",Nextline) != NULL ) { if ( *Tail != '(' ) { strcpy( Line, " LD DE," ) ; strcat( Line, Tail ) ; strcpy( Lastline, Line ) ; Temp = Thisline ; Thisline = Nextline ; Nextline = Temp ; getline( Nextline ) ; ++Saved[0] ; } } } } /* jump on zero round unconditional jump */ if ( (Tail=match(" JP Z,",Lastline)) != NULL ) { if ( match(Tail,Nextline) != NULL ) { if ( (Tail=match(" JP ",Thisline)) != NULL ) { if ( islower( *Tail ) ) { strcpy( Line, " JP NZ," ) ; strcat( Line, Tail ) ; strcpy( Lastline, Line ) ; Temp = Thisline ; Thisline = Nextline ; Nextline = Temp ; getline( Nextline ) ; ++Saved[1] ; } } } } /* store followed by load */ if ( (Tail=match(" LD ",Thisline)) != NULL ) { if ( (tail2=match(" LD ",Nextline)) != NULL ) { uncomma( Tail, dest1, source1 ) ; uncomma( tail2, dest2, source2 ) ; if ( strcmp(dest1,source2) == 0 ) { if ( strcmp(dest2,source1) == 0 ) { getline( Nextline ) ; ++Saved[2] ; } } } } putline( Lastline ) ; Temp = Lastline ; Lastline = Thisline ; Thisline = Nextline ; Nextline = Temp ; } putline( Lastline ) ; putline( Thisline ) ; puts("LD HL;EX;LD HL > LD DE;LD HL: "); putdec(Saved[0]) ; crlf() ; puts("JP Z round JP: "); putdec(Saved[1]) ; crlf() ; puts("Store followed by load: "); putdec(Saved[2]) ; crlf() ; crlf() ; i = Saved[0] + Saved[1]*3 + Saved[2]*2 ; puts("Total bytes saved: ") ; putdec( i ) ; crlf() ; fclose( Ichan ) ; fclose( Ochan ) ; } Saved[1]*3
C
#include <stdio.h> int div16(int x) { int sign = (x >> 31); return (x + (sign & 0x0F )) >> 4; } int main() { printf("%d = %d / 16\n", div16(238), 238); printf("%d = %d / 16\n", div16(-238), 238); }
C
/************************************************************************* > File Name: 20.c > Author: > Mail: > Created Time: 2019年08月14日 星期三 16时40分30秒 ************************************************************************/ #include<stdio.h> #define max_n 100 int num[10000 + 5] = {0}; int main() { num[0] = 1; num[1] = 1; for (int i = 1; i <= max_n; i++) { for (int j = 1; j <= num[0]; j++) { num[j] *= i; } for (int k = 1; k <= num[0]; k++) { if (num[k] < 10) continue; num[k + 1] += num[k] / 10; num[k] %= 10; num[0] += (num[0] == k); } } long long sum = 0; for (int i = 1; i <= num[0]; i++) { sum += num[i]; } printf("%lld\n", sum); }
C
#include <phase1.h> #include <phase1Int.h> #include <assert.h> #include <stdio.h> static void Output(void *arg) { char *msg = (char *) arg; USLOSS_Console("%s", msg); USLOSS_Halt(0); } void startup(int argc, char **argv) { int cids[51]; int rcs[51]; char str[10]; P1ContextInit(); int i; for (i = 0; i < 51; ++i) { sprintf(str, "%d", i); rcs[i] = P1ContextCreate(Output, str, USLOSS_MIN_STACK,&cids[i]); if(i==50){ assert(rcs[i] == P1_TOO_MANY_CONTEXTS); } else { assert(rcs[i] == P1_SUCCESS); } } for (i = 0; i < 50; ++i) { P1ContextFree(cids[i]); } USLOSS_Halt(0); // should not return assert(0); } void test_setup(int argc, char **argv) {} void test_cleanup(int argc, char **argv) {} void finish(int argc, char **argv) {}
C
/* * File: timer.c * Authors: Andres D. Rebeil * * Created on Feb 16, 2016 */ #include <xc.h> #include "timer.h" #include <math.h> #define prescalar_8 3 #define prescalar_256 3 void initTimer1(){ TMR1 = 0; T1CONbits.ON = 0; //TURN TIMER ON T1CONbits.TCKPS = prescalar_256; T1CONbits.TCS = 0; IFS0bits.T1IF = 0; } void delaySec(unsigned int delay){ TMR1 = 0; //RESET TIME PR1 = delay*19530; //set PR IFS0bits.T1IF = 0; // SETS FLAG T1CONbits.ON = 1; //ENABLE CN while(IFS0bits.T1IF == 0); //DELAY TILL FLAG IS RAISED T1CONbits.ON = 0; //DISABLE CN } void initTimer2(){ TMR2 = 0; T2CONbits.ON = 0; //TURN TIMER ON T2CONbits.TCKPS = prescalar_8; T2CONbits.TCS = 0; IFS0bits.T2IF = 0; } void delayMs(unsigned int delay){ IFS0bits.T2IF = 0; // SETS FLAG TMR2 = 0; //RESET TIME PR2 = delay*624; T2CONbits.ON = 1; //ENABLE CN while(IFS0bits.T2IF == 0); //DELAY TILL FLAG IS RAISED T2CONbits.ON = 0; //DISABLE CN } void delayUs(unsigned int delay){ //TODO: Create a delay for "delay" micro seconds using timer 2 IFS0bits.T2IF = 0; // SETS FLAG TMR2 = 0; //RESET TIME PR2 = delay; //SET PRESCALAR T2CONbits.ON = 1; //ENABLE CN while(IFS0bits.T2IF == 0); //DELAY TILL FLAG IS RAISED T2CONbits.ON = 0; //DISABLE CN }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_decimal.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mhwangbo <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/04/17 19:28:59 by mhwangbo #+# #+# */ /* Updated: 2018/05/09 16:41:54 by mhwangbo ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void ft_d_width(t_numbers *n, t_flag flags, int len) { if (flags.precision > len) while (flags.width-- > flags.precision) n->return_i += (flags.zero == 1 ? write(n->fd, "0", 1) : write(n->fd, " ", 1)); else while (flags.width-- > len) n->return_i += (flags.zero == 1 ? write(n->fd, "0", 1) : write(n->fd, " ", 1)); } void ft_d_put(char *str, int len, t_numbers *n, t_flag flags) { int i; i = flags.precision; if (flags.sign) n->return_i += write(n->fd, "-", 1); else if (flags.plus && !flags.sign) n->return_i += write(n->fd, "+", 1); else if (flags.space && !flags.sign) n->return_i += write(n->fd, " ", 1); if (flags.zero) ft_d_width(n, flags, len); while (i-- > len) n->return_i += write(n->fd, "0", 1); if (str[0] == '0' && flags.pre_e == 1 && flags.precision == 0) flags.width > 0 ? n->return_i += write(n->fd, " ", 1) : 0; else ft_str_put(str, len, n); if (flags.minus) ft_d_width(n, flags, len); } void ft_d_precision(t_flag *flags) { if ((flags->plus || flags->space) && !flags->sign) flags->width -= 1; else if (flags->sign) flags->width -= 1; if (flags->minus) flags->zero = 0; if (flags->zero && flags->precision < flags->width && flags->pre_e) flags->zero = 0; } void ft_d_sign(int *len, char *str, t_flag *flags) { if (str[0] == '-') { flags->sign = 1; *len -= 1; } } int ft_decimal(va_list args, const char *format, t_numbers *n) { t_flag flags; int form; char *str; long long i; int len; form = 0; flags = ft_flags(format, 3, args, &form); i = ft_d_cv(flags, args); str = ft_itoa(i, flags); len = ft_strlen(str); ft_d_sign(&len, str, &flags); ft_d_precision(&flags); if (flags.minus || flags.zero) flags.sign == 1 ? ft_d_put(str + 1, len, n, flags) : ft_d_put(str, len, n, flags); else { ft_d_width(n, flags, len); flags.sign == 1 ? ft_d_put(str + 1, len, n, flags) : ft_d_put(str, len, n, flags); } free(str); return (form + 1); }
C
#include "stdio.h" #include "stdlib.h" #include "string.h" typedef int datatype; typedef struct node { datatype data; struct node *next; }Qnode,*Qlink; typedef struct { Qnode *front,*rear; }linkqueue; void Lcreatequeue(linkqueue *q) { q->front=(Qlink)malloc(sizeof(Qnode)); q->front->next=NULL; q->rear=q->front; } void Clearqueue(linkqueue *q) { q->front=q->rear=0; } int Lemptyqueue(linkqueue *q) { if (q->front==q->rear) return (1); else return (0); } void Lenqueue(linkqueue *q,datatype e) { Qlink p; p=(Qlink)malloc(sizeof(Qnode)); p->data=e; p->next=NULL; q->rear->next=p;q->rear=p; } datatype Ldequeue(linkqueue *q) { Qlink p; if (Lemptyqueue(q)) return NULL; else{ p=q->front; q->front=p->next; free(p); return (q->front->data); } } void main() { char a,b;int c = 0; linkqueue q; Lcreatequeue(&q); do { a=getchar(); switch (a) { case ' ':break;c=1; case '0': {if (Lemptyqueue(&q)) { printf("队列为空\n"); printf("请继续输入\n");c=1; } else { b=Ldequeue(&q); printf("%c已出队\n",b); printf("请继续输入\n"); } }break; case '@':{ if (Lemptyqueue(&q)) { printf("队列为空\n");return;} else { printf("所有元素出队:\n"); while (Lemptyqueue(&q)!=1) { b=Ldequeue(&q); printf("%c",b); } printf("\n"); return; } }break; case '\n':break; default :{Lenqueue(&q,a);c=1;}break; } } while (c); }
C
//#include<stdio.h> // // //int main(void) //{ // int a[1001], b[1001]; // int n; // scanf("%d", &n);// // for (int i = 0; i < n; i++) // { // scanf("%d", &a[i]);//ÿ̵һļ۸ // } // b[0] = (a[0] + a[1]) / 2;//һҵڶļ۸ // b[n - 1] = (a[n - 1] + a[n-2]) / 2;//һҵڶļ۸ // for (int j = 1; j < n-1; j++) // { // b[j] = (a[j - 1] + a[j] + a[j + 1]) / 3;//һҵҵڶļ۸ // } // for (int i = 0; i < n; i++) // { // printf("%d ", b[i]); // } // system("pause"); // return 0; //}
C
#include <stdio.h> int main(void) { int nCur = 0, nPro = 0; nCur = 2; nPro = 1; while(1) { if((nCur - 1) % 3 == 0) { nCur = (nCur - 1) / 3; } else { nCur *= 2; } nPro += 1; printf("%d: %d\n", nPro, nCur); if(nCur > 1000000) { break; } } return 0; }
C
#include<stdio.h> struct complex{ int r,i; }; struct complex add(struct complex,struct complex); struct complex sub(struct complex,struct complex); struct complex mul(struct complex,struct complex); struct complex getComplex(); void main(){ int opt; struct complex c1,c2,res; c1 = getComplex(); c2 = getComplex(); do{ printf("\n\n\n1) Add\t\t2) Subtract\n3) Multiply\t4) Change Nos.\n5) Exit"); printf("\nEnter your Choice: "); scanf("%d",&opt); switch(opt){ case 1: res = add(c1,c2); printf("\n\nSum of the Given Complex Number: (%d%s%di)",res.r,res.i<0?" \b":"+",res.i); break; case 2: res = sub(c1,c2); printf("\n\nDifference of the Given Complex Number: (%d%s%di)\n\n",res.r,res.i<0?" \b":"+",res.i); break; case 3: res = mul(c1,c2); printf("\n\nProduct of the Given Complex Number: (%d%s%di)\n\n",res.r,res.i<0?" \b":"+",res.i); break; case 4: c1 = getComplex(); c2 = getComplex(); break; case 5: break; default: printf("Kindly Enter Options 1-4.\n\n"); } }while(opt!=5); } struct complex add(struct complex cf1, struct complex cf2){ struct complex sum; sum.r = cf1.r + cf2.r; sum.i = cf1.i + cf2.i; return(sum); } struct complex getComplex(){ struct complex cmp; printf("Enter Real Part: "); scanf("%d",&cmp.r); printf("Enter Imaginary Part: "); scanf("%d",&cmp.i); return(cmp); } struct complex sub(struct complex cf1,struct complex cf2){ struct complex diff; diff.r = cf1.r - cf2.r; diff.i = cf1.i - cf2.i; return(diff); } struct complex mul(struct complex cf1,struct complex cf2){ struct complex prod; prod.i = cf1.i*cf2.r + cf2.i*cf1.r; prod.r = -cf1.i*cf2.i + cf1.r*cf2.r; return(prod); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> int main() { int iptr = NULL; float * fptr = NULL; char *cptr = NULL; double * dp = NULL; int i; float f; double d; printf("\nSize of Integer Pointer : %d Bytes",sizeof(iptr)); printf("\nSize of Character Pointer : %d Bytes",sizeof(&cptr)); printf("\nSize of Float Pointer : %d Bytes",sizeof(fptr)); printf("\nSize of Double Pointer : %d Bytes",sizeof(dp)); printf("\nSize of Int : %d Bytes",sizeof(i)); printf("\nSize of Float : %d Bytes",sizeof(f)); printf("\nSize of Double : %d Bytes",sizeof(d)); printf("\n"); printf("\n"); printf("\n"); return 0; }
C
#include<stdio.h> #include<ctype.h> double power(double , int); int main(void) { double num = 0; double ret = 0; int time = 0; char ch = 0; while(1){ printf("please enter a number to power:\n"); scanf("%lf",&num); printf("please enter a power time:\n"); scanf("%d", &time); ret = power(num, time); printf("the resule is %f\nPress q to quie:\n", ret); scanf("%c",&ch); if(ch == 'q' || ch == 'Q') break; } return 0; } double power(double inter, int times) { double result = inter; int i; if(times > 0) for(i = 1; i < times; i++) result *= inter; else if(times == 0) result = 1; else for(i = -1; i < -times; i++) result *= 1 / inter; return result; }
C
#include<stdio.h> //#include<conio.h> int w[20],x[20],d; void subset(int cs,int k,int r) { int i; x[k]=1; if((cs+w[k])==d) { for(i=0;i<=k;i++) if(x[i]==1) printf("%d ",w[i]); printf("\n"); } else { if(cs+w[k]+w[k+1]<=d) subset(cs+w[k],k+1,r-w[k]); if((cs+r-w[k]>=d)&&(cs+w[k+1]<=d)) { x[k]=0; subset(cs,k+1,r-w[k]); } } } main() { int i,n,sum=0; printf("Enter the no. of elements: "); scanf("%d",&n); printf("Enter the elements in increasing order:\n"); for(i=1;i<=n;i++) scanf("%d",&w[i]); printf("Enter the required sum(d): "); scanf("%d",&d); for(i=1;i<=n;i++) sum+=w[i]; if(sum<d || w[1]>d) printf("Subset not possible!!\n"); else { printf("The possible subsets are:\n"); subset(0,1,sum); } }
C
/* selfReference-bugs.c */ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <conio.h> int main() { struct student { char name[20]; int score; struct student *next; }; struct student *p, *q, *r; p = (struct student*) malloc(sizeof(struct student *)); p->name = "Bright"; p->score = 98; q = (struct student*) malloc(sizeof(struct student *)); q->name = "Linda"; q->score = 95; r = (struct student*) malloc(sizeof(struct student *)); r->name = "Jennifer"; r->score = 95; p->next = q; q->next = r; /* ϥpШӦLXoTӸ`I */ printf("There are three students in my class\n"); printf("%s %d\n", p->name, p->score); printf("%s %d\n", p->name, p->score); printf("%s %d\n", p->name, p->score); _getch(); return 0; }
C
/* demonstration of parent child data segment sharing after fork */ #include<stdio.h> #include<unistd.h> //global and static vars stores into data segment of process int i = 11; //Non-BSS static int j = 21; //Non-BSS block started with value int y; //BSS block started with symbol int main() { pid_t pid; static int x =10; //Non-BSS pid = fork(); //child process creation call if(pid == 0) //child process runs in block { printf("\nchild process copy for data section\n"); printf("i : %d\n",++i); printf("j : %d\n",j); printf("x : %d\n",x); printf("parent pid : %d\n",getpid()); } else //parent process runs { printf("\nparent process copy for data section\n"); printf("i : %d\n",i); printf("j : %d\n",++j); printf("x : %d\n",++x); printf("parent pid : %d\n",getpid()); } printf("Hello work\n"); return 0; }
C
/* pthread_self() gives current thread ID pthread_detach() - when a thread creatd one of its attributes defines whether it is joinable or detached - if NULL as second argument it is joinable - only threads created as joinable can be join()ed - detached cant be joined - 2 common cases when you want to detach - cancellation handler for pthread_join() - essential to have pthread_detach in order to detatch the thread pthread_join waiting on - to detach initial thread (desirable in processes that set up server threads) - can detach thread that was created as joinable pthread_attr_get/setstacksize(attr, stacksize) - POSIX doesn't dictate size of a threads stack - exceeding stack limit is often easy to do - safe/portable programs don't depend upon default stack limit - better to explicitly allocate enough stack for each thread pthread_equal(thread1, thread2) - if 2 ID's are different the 0 returned otherwise non-zero returned - dont use == to check pthread_once(once_control, init_routine) - initialization routine - once_contorl is a synchronization control structure that requries intialization prior to calling pthread_once - pthead_once_t once_control = PTHREAD_ONCE_INIT pthread_cancel(pthread_id) - sends cancellation request to thread ID */ #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <pthread.h> // //alter 25/38 to see differnece // void *threadFn (void *arg){ // pthread_detach(pthread_self);//main will not wait for thread to be done; // sleep(1); // printf("Thread Fn\n"); // pthread_exit(NULL); // } // int main(int argc, char *argv[]){ // pthread_t tid; // int ret = pthread_create(&tid, NULL, threadFn, NULL); // if (ret !=0){ // perror("Thread creation error\n"); // exit(1); // } // //pthread_join(tid, NULL); // printf("After thread created in main\n"); // pthread_exit(NULL); // } pthread_attr_t attr; void *dowork(void *threadid){ long tid; size_t mystacksize; tid = (long)threadid; pthread_attr_getstacksize(&attr, &mystacksize);//size stored in latter printf("Thread %ld: with stacksize = %li bytes \n", tid, mystacksize);//should be 9000000 pthread_exit(NULL); } int main(){ pthread_t myThread; size_t stacksize; int myID; long t = 5; pthread_attr_init(&attr);//initalize attr global variable pthread_attr_getstacksize(&attr, &stacksize);//get stacksize for thread ID printf("default stack size is %li\n", stacksize); stacksize = 9000000; printf("Amount of stack needed per thread = %li\n", stacksize); pthread_attr_setstacksize(&attr, stacksize);//set attr to 9MB //QUESTION: to verify if this works I want to print attr's attributes so how do i do that printf("Creating thread with stacksize %li\n", stacksize); //attr.__opaque myID = pthread_create(&myThread, &attr, dowork, (void *) t); if (myID){ printf("Error; return code from thread creation is %d\n",myID ); exit(-1); } pthread_exit(NULL); }
C
#include <stdbool.h> #include <stdio.h> #include <string.h> /* * O(n*m) in time * O(2*n) in size * * Not optimal */ #define LEN_MAX 4000 bool dyn[2][LEN_MAX]; bool isMatch(const char* string, const char* pattern) { const char *temp_str; size_t i, j; size_t pattern_len, string_len, tmp_len; int l1, l2; pattern_len = strlen(pattern); string_len = strlen(string); /* Initialize */ l1 = 0; l2 = 1; dyn[0][0] = true; for (j = 0 ; j < pattern_len ; j++) { if (pattern[j] == '*' && dyn[0][j] == true) { dyn[0][j + 1] = true; continue; } dyn[0][j + 1] = false; } /* Fill the array */ for (i = 0 ; i < string_len; i++) { dyn[l2][0] = false; for (j = 0 ; j < pattern_len; j++) { if (pattern[j] == string[i] || pattern[j] == '?') { dyn[l2][j + 1] = dyn[l1][j]; } else if (pattern[j] == '*' && (dyn[l2][j] || dyn[l1][j + 1])) { dyn[l2][j + 1] = true; } else { dyn[l2][j + 1] = false; } } l1 = l2; l2 ^= 1; } return dyn[l1][pattern_len]; } void test_case(const char * string, const char * pattern) { printf("==============================\n"); printf("str=%s pat=%s match=%d\n", string, pattern, isMatch(string, pattern)); } int main(int argc, char ** argv) { test_case("", ""); test_case("", "*"); test_case("a", "*"); test_case("t", "*t"); test_case("t", "t*"); test_case("abc", "*"); test_case("a", "?"); test_case("aa", "a"); test_case("atubic", "a*b?c"); test_case("atubic", "*"); test_case("atubic", "a*?c"); test_case("atubicdkdal", "a*bkjfalsdkf?casdlfja"); test_case("ho", "**ho"); test_case("ho", "t**ho"); return 0; }
C
/* * Copyright (c) 2020-2021 Krzysztof Sobolewski <krzysztof.sobolewski@gmail.com> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <limits.h> #include "curl/curl.h" #include "soborequest/request.h" #include "soborequest/request_methods.h" #include "soborequest/request_cb_functions.h" #ifndef PATH_MAX #define PATH_MAX 1024 #endif /** * @brief mass-testing * @note * @param *url: * @param port: * @param m: * @param num: * @param *test_contents: * @param *test_ct: * @retval None */ void test_mass(char *url, long port, enum METHOD m, int num, char *test_contents, char *test_ct) { CURLcode res; char *data = "abcd"; int i = 0; struct ResponseData *resp; int num_errors = 0; /* * C89 compatibility - looks weird (can't use function * vars at struct initialization) */ struct ConnData cd; cd.url = url; cd.port = port; cd.method = m; for (i = 0; i < num; i++) { printf("\nMaking request %d/%d to: %s port: %lu method: %d (%s)...", i + 1, num, cd.url, cd.port, cd.method, methodName(cd.method)); res = make_request(&cd, data, NULL, NULL, NULL, &resp); /* * I don't want to use assert here, because I don't want the program to quit on the * first failed conneciton. I'd rather like to gather the info about how often it happens. */ if (res == CURLE_OK) { printf(" - OK!\n"); } else { printf(" - FAILED! Error Code: %d. \n", res); num_errors++; continue; } printf("\n\n TEST=> RESP CODE %lu size: %lu CONTENTS: %s " "CONTENT-TYPE: %s\n", (unsigned long)resp->status_code, (unsigned long)resp->size, resp->contents, resp->content_type ); if (test_contents != NULL) { printf("\nTESTING: RESP cnt: '%s'\nTEST cnt: '%s'. Is equal?", resp->contents, test_contents); if (strcmp(resp->contents, test_contents) == 0) { printf(" -- YES, OK! \n"); } else { printf(" -- FAILED! \n"); num_errors++; continue; } } if (test_ct != NULL) { printf("\nTESTING: RESP ct: '%s'\nTEST ct: '%s'. Is equal?", resp->content_type, test_ct); if (strcmp(resp->content_type, test_ct) == 0) { printf(" -- YES, OK! \n"); } else { printf(" -- FAILED! \n"); num_errors++; continue; } } } if (num_errors > 0) { printf("\nThere were %d error(s) out of %d tests.\n", num_errors, num); } else { printf("\nAll %d tests have been performed successfully.\n", num); } printf("================================================\n\n"); } int main(int argc, char **argv) { int status = 0; char *url = (argc > 0 && argv[1]) ? argv[1] : "http://127.0.0.1"; long port = 5000; int num = 10; printf("\ntest_request testing has been started... \n\n"); test_mass(url, port, METHOD_GET, num, "\"GET IS OK\"\n", NULL); test_mass(url, port, METHOD_POST, num, "\"POST IS OK\"\n", NULL); test_mass(url, port, METHOD_DELETE, num, "\"DELETE IS OK\"\n", NULL); test_mass(url, port, METHOD_PATCH, num, "\"PATCH IS OK\"\n", NULL); printf("\ntest_request testing has been finished... \n\n"); return status; }
C
#include <stdio.h> int main() { char s1[100], s2[50], i, j, l; printf("\n Enter any string:"); gets(s1); printf("\n Enter another string:"); gets(s2); while(s1[i]!='\0') i++; l=i; while(s2[j]!='\0') { s1[i]=s2[j]; i++; j++; } l=i; printf("Length of string=%d\n", l); s1[i]='\0'; printf("After copying the string = "); puts(s1); return 0; }
C
#include <stdio.h> struct node { char* data; struct node* next; // 带 ʵ }; typedef struct node Node; Node* head = NULL; // ḮƮ ù° ּҸ //**ptr_head : head ּҸ Ű ޴´ void add_first(Node **ptr_head, char* item) { Node* temp = (Node*)malloc(sizeof(Node)); temp->data = item; temp->next = *ptr_head; *ptr_head = temp; }
C
#include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <math.h> #include <huffman.h> #include <jpeg_writer.h> struct jpeg_desc; /* Fonction prenant en entrée tous les paramètres à mettre dans le Header du jpeg * et appelant toutes les fonctions de jpeg_writer pour mettre à jour tous les * paramètres de la structure jpeg_desc. * Entrée : Tous les paramètres nécessaires à l'écriture du Header * Sortie : La structure jpeg_desc correspondante */ struct jpeg_desc *entete(char *ppm_filename, char *jpeg_filename, uint32_t image_height, uint32_t image_width, uint8_t nb_components, uint8_t sampling_factor[nb_components*2], struct huff_table *table_y_ac, struct huff_table *table_y_dc, struct huff_table *table_cb_ac, struct huff_table *table_cb_dc, struct huff_table *table_cr_ac, struct huff_table *table_cr_dc, uint8_t *qtable_y, uint8_t *qtable_c){ struct jpeg_desc *jpeg = jpeg_desc_create(); jpeg_desc_set_ppm_filename(jpeg, ppm_filename); jpeg_desc_set_jpeg_filename(jpeg, jpeg_filename); jpeg_desc_set_image_height(jpeg, image_height); jpeg_desc_set_image_width(jpeg, image_width); jpeg_desc_set_nb_components(jpeg, nb_components); jpeg_desc_set_sampling_factor(jpeg, Y, H, sampling_factor[0]); jpeg_desc_set_sampling_factor(jpeg, Y, V, sampling_factor[1]); jpeg_desc_set_huffman_table(jpeg, AC, Y, table_y_ac) ; jpeg_desc_set_huffman_table(jpeg, DC, Y, table_y_dc) ; jpeg_desc_set_quantization_table(jpeg, Y, qtable_y); if(nb_components == 3){ jpeg_desc_set_huffman_table(jpeg, AC, Cb, table_cb_ac); jpeg_desc_set_huffman_table(jpeg, AC, Cr, table_cr_ac) ; jpeg_desc_set_huffman_table(jpeg, DC, Cb, table_cb_dc); jpeg_desc_set_huffman_table(jpeg, DC, Cr, table_cr_dc) ; jpeg_desc_set_quantization_table(jpeg, Cb, qtable_c); jpeg_desc_set_quantization_table(jpeg, Cr, qtable_c); jpeg_desc_set_sampling_factor(jpeg, Cb, H, sampling_factor[2]); jpeg_desc_set_sampling_factor(jpeg, Cb, V, sampling_factor[3]); jpeg_desc_set_sampling_factor(jpeg, Cr, H, sampling_factor[4]); jpeg_desc_set_sampling_factor(jpeg, Cr, V, sampling_factor[5]); } return jpeg; }
C
#include "pgs_crypto.h" #include <assert.h> /* AES */ pgs_aes_cryptor_t *pgs_aes_cryptor_new(const EVP_CIPHER *cipher, const pgs_buf_t *key, const pgs_buf_t *iv, pgs_cryptor_direction_t dir) { pgs_aes_cryptor_t *ptr = pgs_malloc(sizeof(pgs_aes_cryptor_t)); ptr->key = key; ptr->iv = iv; switch (dir) { case PGS_ENCRYPT: { if (!(ptr->ctx = EVP_CIPHER_CTX_new())) goto error; if (1 != EVP_EncryptInit_ex(ptr->ctx, cipher, NULL, key, iv)) goto error; break; } case PGS_DECRYPT: { if (!(ptr->ctx = EVP_CIPHER_CTX_new())) goto error; if (1 != EVP_DecryptInit_ex(ptr->ctx, cipher, NULL, key, iv)) goto error; break; } default: goto error; } return ptr; error: perror("pgs_aes_cryptor_new"); pgs_aes_cryptor_free(ptr); return NULL; } void pgs_aes_cryptor_free(pgs_aes_cryptor_t *ptr) { if (ptr->ctx) EVP_CIPHER_CTX_free(ptr->ctx); pgs_free(ptr); ptr = NULL; } bool pgs_aes_cryptor_encrypt(pgs_aes_cryptor_t *ptr, const pgs_buf_t *plaintext, int plaintext_len, pgs_buf_t *ciphertext) { int len = 0; if (1 != EVP_EncryptUpdate(ptr->ctx, ciphertext, &len, plaintext, plaintext_len)) return false; assert(len == plaintext_len); return true; } bool pgs_aes_cryptor_encrypt_final(pgs_aes_cryptor_t *ptr, const pgs_buf_t *plaintext, int plaintext_len, pgs_buf_t *ciphertext) { int len = 0; if (1 != EVP_EncryptFinal_ex(ptr->ctx, ciphertext, &len)) return false; return true; } bool pgs_aes_cryptor_decrypt(pgs_aes_cryptor_t *ptr, const pgs_buf_t *ciphertext, int ciphertext_len, pgs_buf_t *plaintext) { int len = 0; if (1 != EVP_DecryptUpdate(ptr->ctx, plaintext, &len, ciphertext, ciphertext_len)) return false; return true; } bool pgs_aes_cryptor_decrypt_final(pgs_aes_cryptor_t *ptr, const pgs_buf_t *ciphertext, int ciphertext_len, pgs_buf_t *plaintext) { int len = 0; if (1 != EVP_DecryptFinal_ex(ptr->ctx, plaintext, &len)) return false; return true; } /* AEAD */ pgs_aead_cryptor_t *pgs_aead_cryptor_new(const EVP_CIPHER *cipher, const pgs_buf_t *key, const pgs_buf_t *iv, pgs_cryptor_direction_t dir) { pgs_aead_cryptor_t *ptr = pgs_malloc(sizeof(pgs_aead_cryptor_t)); ptr->key = key; ptr->counter = 0; // vmess using 12 bytes iv aead cipher ptr->iv = pgs_malloc(sizeof(pgs_buf_t) * 12); ptr->dir = dir; pgs_memzero(ptr->iv, 12); pgs_memcpy(ptr->iv + 2, iv + 2, 10); switch (dir) { case PGS_ENCRYPT: { if (!(ptr->ctx = EVP_CIPHER_CTX_new())) goto error; if (1 != EVP_EncryptInit_ex(ptr->ctx, EVP_aes_128_gcm(), NULL, NULL, NULL)) goto error; if (1 != EVP_CIPHER_CTX_ctrl(ptr->ctx, EVP_CTRL_GCM_SET_IVLEN, 12, NULL)) goto error; if (1 != EVP_EncryptInit_ex(ptr->ctx, NULL, NULL, ptr->key, ptr->iv)) goto error; break; } case PGS_DECRYPT: { if (!(ptr->ctx = EVP_CIPHER_CTX_new())) goto error; if (1 != EVP_DecryptInit_ex(ptr->ctx, EVP_aes_128_gcm(), NULL, NULL, NULL)) goto error; if (1 != EVP_CIPHER_CTX_ctrl(ptr->ctx, EVP_CTRL_GCM_SET_IVLEN, 12, NULL)) goto error; if (1 != EVP_DecryptInit_ex(ptr->ctx, NULL, NULL, ptr->key, ptr->iv)) goto error; break; } default: goto error; } return ptr; error: perror("pgs_aead_cryptor_new"); pgs_aead_cryptor_free(ptr); return NULL; } void pgs_aead_cryptor_free(pgs_aead_cryptor_t *ptr) { if (ptr->ctx) EVP_CIPHER_CTX_free(ptr->ctx); if (ptr->iv) pgs_free(ptr->iv); pgs_free(ptr); ptr = NULL; } bool pgs_aead_cryptor_encrypt(pgs_aead_cryptor_t *ptr, const pgs_buf_t *plaintext, int plaintext_len, pgs_buf_t *tag, pgs_buf_t *ciphertext, int *ciphertext_len) { int len; if (1 != EVP_EncryptUpdate(ptr->ctx, ciphertext, &len, plaintext, plaintext_len)) return false; *ciphertext_len = len; if (1 != EVP_EncryptFinal_ex(ptr->ctx, ciphertext + len, &len)) return false; *ciphertext_len += len; if (1 != EVP_CIPHER_CTX_ctrl(ptr->ctx, EVP_CTRL_GCM_GET_TAG, 16, tag)) return false; // increase iv pgs_aead_cryptor_increase_iv(ptr); return true; } bool pgs_aead_cryptor_decrypt(pgs_aead_cryptor_t *ptr, const pgs_buf_t *ciphertext, int ciphertext_len, const pgs_buf_t *tag, pgs_buf_t *plaintext, int *plaintext_len) { int len = 0; if (!EVP_DecryptUpdate(ptr->ctx, plaintext, &len, ciphertext, ciphertext_len)) return false; *plaintext_len = len; if (!EVP_CIPHER_CTX_ctrl(ptr->ctx, EVP_CTRL_GCM_SET_TAG, 16, (void *)tag)) return false; if (!EVP_DecryptFinal_ex(ptr->ctx, plaintext + len, &len)) return false; *plaintext_len += len; pgs_aead_cryptor_increase_iv(ptr); return true; } void pgs_aead_cryptor_increase_iv(pgs_aead_cryptor_t *ptr) { ptr->counter += 1; ptr->iv[0] = ptr->counter >> 8; ptr->iv[1] = ptr->counter; switch (ptr->dir) { case PGS_ENCRYPT: { EVP_EncryptInit_ex(ptr->ctx, NULL, NULL, ptr->key, ptr->iv); break; } case PGS_DECRYPT: { EVP_DecryptInit_ex(ptr->ctx, NULL, NULL, ptr->key, ptr->iv); break; } default: break; } }
C
#include <stdio.h> int main(void) { printf("Ƃ\n"); printf("29\n"); printf("AeB[NDł\n"); printf("29+29̌vZ܂B\n"); printf("%d\n", 29 + 29); int x; x = 6; printf("%d\n", x * x * 3); return 0; }
C
/* examples/play_file.c: File-playing example for audio-utsl. * Copyright (c) 2018 Chris White (cxw/Incline). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <limits.h> #include "audio_utsl.h" extern unsigned int AU_PAPC_Count; extern unsigned int AU_SFFR_Count; int main(int argc, char **argv) { HAU hau; int samplerate, channels; Au_SampleFormat format; long int len = -1; int idx; int maxidx; double time; if(argc<2) return 1; if(!Au_Startup()) return 2; if(!Au_InspectFile(argv[1], &samplerate, &channels, &format, &len)) return 3; printf("File %s: %d channels @ %d Hz, len %ld, format ", argv[1], channels, samplerate, len); switch(format) { case AUSF_F32: printf("float32\n"); break; case AUSF_I32: printf("int32\n"); break; case AUSF_I24: printf("int24\n"); break; case AUSF_I16: printf("int16\n"); break; case AUSF_I8: printf("int8\n"); break; case AUSF_UI8: printf("uint8\n"); break; default: printf("unknown\n"); return 4; break; } /* create an output */ if(!(hau=Au_New(format, samplerate, channels, NULL))) return 5; if(!Au_Play(hau, argv[1])) return 6; if(len < 0.0) { /* if we don't know how long it is, play for ~7 sec. */ maxidx = 15; } else { maxidx = 2*(len/samplerate+1); } /* If given a second parameter, play until the file is done. */ if(argc>2) maxidx = INT_MAX; for(idx=0; idx < maxidx; ++idx) { time = Au_GetTimeInPlayback(hau); printf("Time %f\tpapc %d\tsffr %d\n", time, AU_PAPC_Count, AU_SFFR_Count); if(time>0 && !Au_IsPlaying(hau)) break; /* Check time>0 because IsPlaying is not necessarily true * just after an Au_Play() call, at which point time=0.*/ Au_msleep(500); } Au_Stop(hau); if(!Au_Delete(hau)) return 7; if(!Au_Shutdown()) return 8; return 0; } /* vi: set ts=4 sts=4 sw=4 et ai: */
C
#pragma once typedef struct { int id, quantity; char *manufacturer, *name; } Medication; Medication* createMedication(int id, char *name, char *manufacturer, int quantity); int getId(Medication *medication); char* getName(Medication *medication); char* getManufacturer(Medication *medication); int getQuantity(Medication *medication); void displayMedication(Medication *medication); void destroyMedication(Medication *medication);
C
include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <sys/types.h> #include <signal.h> #include <string.h> #include <wiringPi.h> pid_t scanner; #define LedPin 0 #define Rele 2 void mataDsreader(); void le_strings(char *matriz_string); void extraiCodigo(char *str, char *codigo); int validaCodigo(char *codigos); int verificaCodigo(char *codigo); int main(){ char codigo[10][100]; char codigoReal[10][100]; int sent=1; wiringPiSetup(); pinMode(LedPin,OUTPUT); pinMode(Rele,OUTPUT); signal(SIGALRM, mataDsreader); scanner=fork(); if(scanner==0){ system("./dsreader > cadastro.txt"); }else{ while(sent){ puts("Posicione o código de barras/QR CODE"); alarm(15); pause(); le_strings(codigo[0]); extraiCodigo(codigo[0], codigoReal[0]); sent=validaCodigo(codigoReal[0]); if(sent){ /* puts("\n\n\n\nCódigo não reconhecido!!!, tente novamente..."); digitalWrite(LedPin,LOW); digitalWrite(Rele,LOW); delay(1000);}*/ puts("Porta fechada"); digitalWrite(LedPin,LOW); digitalWrite(Rele,LOW); sleep(5); system("-c"); return 0; } } if(verificaCodigo(codigoReal[0])){ puts("Porta fechada"); digitalWrite(LedPin,LOW); digitalWrite(Rele,LOW); sleep(5); }else{ puts("Porta aberta"); digitalWrite(LedPin,HIGH); digitalWrite(Rele,HIGH); delay(5000); digitalWrite(LedPin,LOW); delay(15000); digitalWrite(Rele,LOW); } } return 0; } // Objetivo: Procedimento para fechar Dsreader quando tempo de execução acabar // Parâmetro: // Retorno: void mataDsreader(){ kill(scanner, SIGINT); } // Objetivo: Extrai apenas código da string vinda do arquivo // Parâmetro: string do arquivo, ponteiro para string do código // Retorno: código void extraiCodigo(char *str, char *codigo){ int linha, i, j; for(linha=0; linha<10; linha++){ for(i=0; *(str + linha*100 + i)!=':' && *(str + linha*100 + i)!='\0'; i++); for(i=i+2, j=0; *(str + linha*100 + i)!='(' && *(str + linha*100 + i)!='\0'; i++, j++){ *(codigo + linha*100 + j)=*(str + linha*100 + i); } *(codigo + linha*100 + j -1)='\0'; } } // Objetivo: Lê 10 linhas do arquivo // Parâmetro: ponteiro para strings // Retorno: strings void le_strings(char *matriz_string){ FILE *cadastro; int i=0; cadastro=fopen("cadastro.txt", "r"); while(!feof(cadastro) && i<10){ fgets(matriz_string+100*i, 100, cadastro); i++; } fclose(cadastro); return; } // Objetivo: Compara 10 códigos para testar se eles são iguais // Parâmetro: strings dos códigos // Retorno: 0 quando for igual, 1 se for diferente int validaCodigo(char *codigos){ int i; int resultado=0; for(i=0; i<10; i++){ if(strcmp(codigos, codigos+i*100)!=0){ resultado=1; } } return resultado; } // Objetivo: Procura um código na base de dados // Parâmetro: código // Retorno: 0 para sucesso, 1 quando não encontrar int verificaCodigo(char *codigo){ FILE *dados; int i=0; char aux[100]; int resultado=1; dados=fopen("codigo.txt", "r"); while(!feof(dados)){ fgets(aux, 100, dados); aux[strlen(aux)-1]='\0'; if(strcmp(aux, codigo)==0){ resultado=0; } } fclose(dados); return resultado; }
C
/* Childrens Game */ /* UVA 10905 */ /* Accepted */ #include <stdio.h> #include <stdlib.h> #include <string.h> char **numeros; int compara(const void *p1, const void *p2) { char *a = *(char **)p1; char *b = *(char **)p2; int i; for(i=0; a[i] != '\0' && b[i] != '\0'; i++) { if(a[i] < b[i]) return 1; else if(a[i] > b[i]) return -1; } if(a[i] == b[i]) return 0; if(a[i] == '\0'){ b += i; return compara(&a, &b); } else{ a += i; return compara(&a, &b); } } int main() { int n; int i; numeros = (char **)malloc(50*sizeof(char *)); for(i=0; i<50; i++) numeros[i] = (char *)malloc(500*sizeof(char)); while(42) { scanf(" %d", &n); if(n == 0) break; for(i=0; i<n; i++) scanf(" %s", numeros[i]); qsort(numeros, n, sizeof(char **), compara); for(i=0; i<n; i++) printf("%s", numeros[i]); printf("\n"); } for(i=0; i<50; i++) free(numeros[i]); free(numeros); return 0; }
C
/** @file common.h * * Common includes and typedefs used througout the Cude code base. */ #ifndef COMMON_H #define COMMON_H #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <assert.h> #include "error.h" /** * Because Byte is so much easier to type than uint8_t, and also much * more meaningful. */ typedef uint8_t Byte; /** Make it easier to work with C Strings. */ typedef char* String; /** The maximum number of local variables allowed in a block. */ #define LOCALS_MAX UINT8_MAX + 1 /** @brief Create a new String. * * Allocate new memory for the C String and copy over * the characters so there is no issue with ownership. * This works for valid C Strings that are null terminated. * * @param s The C String to be copied. * @return The new String containing the original C String. */ String string_init(const char *s); /** @brief Create a new String with the given length. * * Allocate new memory for the C String and copy over * the characters up to the given length. Can be used to * create a substring from a larger string. * * @param s The C String to be copied. * @param length The number of characters to be copied. * @return The new String containing the original C String. */ String string_copy(const char *s, int length); #endif // COMMON_H
C
/* * *** ***** *** * . . . (done) n rows */ #include<stdio.h> #include<conio.h> void main() { int n,i,j,x=0,z=0; clrscr(); printf("Enter number of rows n :- "); scanf("%d",&n); i=n/2+1; x=0; z=0; while(i>0) { x++; j=1; while(j<=i) { printf(" "); j++; } j=1; while(j<=x+z) { printf("*"); j++; } z++; printf("\n"); i--; } z=x+z-3; j=1; while(z>0) { i=1; printf(" "); while(i<=j) { printf(" "); i++; } i=1; while(i<=z) { printf("*"); i++; } j++; z=z-2; printf("\n"); } getch(); }