language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int arrequal(int arr1[], int arr2[], int size){ int inc; for (inc = 0; inc <= size; inc++){ if (arr1[inc] == arr2[inc]) { return 1; } else { return 0; } } } int main(void){ int size; scanf("%d", &size); int arr1[size]; int arr2[size]; int yinc; for (yinc = 0; yinc <= size; yinc++){ printf("arr1 number at %d:", yinc); scanf("%d", &arr1[yinc]); } for (yinc = 0; yinc <= size; yinc++){ printf("arr2 number at %d:", yinc); scanf("%d", &arr2[yinc]); } printf("%d", arrequal(arr1, arr2, size)); }
C
#include <stdio.h> #include <cs50.h> const int ouncesPerMinute = 192; const int bottleCapacityOunces = 16; int main(void) { printf("Minutes: "); int minutes = get_int(); printf("Bottles: %i\n", minutes * ouncesPerMinute / bottleCapacityOunces); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "cofo.h" #define True 1 #define False 0 typedef struct _dados_{ char nome[30]; int idade; int NumFilhos; float salario; int cpf; }dados; int CompCPF(void*cpf, void *pessoa){ int *key; dados *p; key = (int*)cpf; printf("\nkey:%i",key); p = (dados*)pessoa; printf("\np:%i",p->NumFilhos); if(*key == p->cpf){ return True; }else{ return False; } } void cadastro(dados *pessoa){ if(Gcriado == False){ printf("\nCuidado, seus dados estao sendo sobreposto\nPorfavor, crie um cofo.\n"); } printf("Nome: "); scanf("%s*c",&(pessoa -> nome)); printf("Idade: "); scanf("%d",&(pessoa -> idade)); printf("Numero de Filhos: "); scanf("%d",&(pessoa -> NumFilhos)); printf("Salario: R$"); scanf("%f",&(pessoa -> salario)); printf("cpf: "); scanf("%d",&(pessoa -> cpf)); } int main(){ //---------- declaracoes ----------------------- cofo *usuarios;// cofo de usuarios dados *pessoa, *RespQuery;// estrutura pessoa; resposta retornada pelo query. int RespInse;// resposta retornada, se foi inserido ou nao int opcao = -1;// opcoes do menu int NumPessoas, LibPessoa = False;// entrada do usuario para saber quantas pessoas vao ser guardadas no cofo; para liberar pessoas quando for sobrescrever outra pessoa int InputCpf;// cpf para ser pesquisado //---------- end(declaracoes) ------------------ //---------- Menu ----------------------- while(opcao != 0){ system("cls"); printf("1 - Inserir pessoa\n2 - Criar Cofo\n3 - Destruir Cofo\n4 - Inserir ultimos dados cadastrados no Cofo\n5 - Consultar Dados De um usuario pelo cpf\n6 - Remover Dados De um usuario pelo cpf\n7 - Mostrar Cofo Completo\n0 - Sair\n>>>>"); scanf("%i*c",&opcao); if(opcao == 1){ if(LibPessoa == True){ free(pessoa); LibPessoa = False; } pessoa = (dados*)malloc(sizeof(dados)); if(pessoa != NULL){ cadastro(pessoa); LibPessoa = True; } else{ printf("ERRO, alocacao de pessoa..."); free(pessoa); exit(0); } } else if(opcao == 2){ printf("Numero maximo de pessoas no cofo: "); scanf("%d*c",&NumPessoas); usuarios = CofCreate(NumPessoas);// ps: fazer pergunta para o usuario de quantos dados podem ser guardados if(usuarios == NULL){ printf("ERRO, na criacao do cofo"); CofDestroy(usuarios); exit(0); } else{ system("cls"); printf("\n--Cofo criado com sucesso--\n\n"); system("PAUSE"); } } else if(opcao == 3){ if(Gcriado == True){ CofDestroy(usuarios); system("cls"); printf("\n--Cofo Destruido com sucesso--\n\n"); system("PAUSE"); }else{ system("cls"); printf("\nERRO, cofo nao foi criado ou foi apagado\n\n"); system("PAUSE"); } } else if(opcao == 4){ if(Gcriado == True){// erro, entrando na opcao msm depois que ja foi adicionado if(pessoa != NULL){ RespInse = CofInsert(usuarios,(void*)pessoa); if(RespInse == 1){ free(pessoa); LibPessoa = False; system("cls"); printf("\nAdicionado ao usuario\n"); system("PAUSE"); } else{ system("cls"); printf("\nNao foi adicionado ao usuario"); system("PAUSE"); } } else{ printf("\nERRO, alocacao de pessoa ou ainda nao foi alocada..."); exit(0); } } else{ printf("ERRO, criacao do cofo ou nao existe..."); exit(0); } } else if(opcao == 5){ if(Gcriado == True){ printf("Buscar Cpf: "); scanf("%i*c",&InputCpf); RespQuery = (dados*)CofQuery(usuarios,(void*)InputCpf,CompCPF); if(RespQuery != NULL){ system("cls"); printf("\nnome:%s\ncpf:%d\n", RespQuery->nome, RespQuery->cpf); system("PAUSE"); } else{ printf("\nNao Achou..."); } } } else if(opcao > 7 || opcao < 0){ printf("\nERRO, opcao nao existe...\nTente Novamente.\n"); system("PAUSE"); } } //---------- end(Menu) ----------------------- return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { puts(getenv("PATH")); int res = setenv("PATH", "hahaha", 0); if(res == -1) { perror("set PATH"); exit(-1); } //system("echo $PATH"); puts(getenv("PATH")); //not overwrite old path. //int setenv(const char *name, const char *value, int overwrite); res = setenv("PATH", "hahaha", 1); if(res == -1) { perror("set PATH"); exit(-1); } puts(getenv("PATH")); // overrided the old PATH value with hahaha. // int unsetenv(const char *name); res = unsetenv("PATH"); if(res == -1) { perror("unset PATH"); exit(-1); } char * path = getenv("PATH"); if(path != NULL) { printf(" %s \n ", path); } else { puts("=========="); // path == NULL } // system("echo $PATH"); puts("**********************"); res = setenv("abcd", "12334565", 1); if(res == -1) { perror("set abcd"); exit(-1); } printf("abcd = %s \n", getenv("abcd")); //abcd = 12334565 res = unsetenv("abcd"); if(res == -1) { perror("set abcd"); exit(-1); } printf("abcd = %s \n", getenv("abcd")); res = unsetenv("abcd"); //abcd = (null) if(res == -1) { perror("set abcd"); exit(-1); } printf("abcd = %s \n", getenv("abcd")); // abcd = (null) }
C
#include<stdio.h> int main() { int a[100],i,j,n,store[100]={0}; printf("Enter the range\n"); scanf("%d",&n); int isprime=0; int c=0; for(i=2;i<=n;i++) { isprime=0; for(j=2;j<=i/2;j++) { if(i%j==0) { isprime++; } } if(isprime==0) { store[c]=i; c++; } } printf("The twin primes are\n"); for(i=0;i<c;i++) { if(store[i] == store[i-1]+2) { printf("%d %d\n",store[i-1],store[i]); } } return 0; }
C
#include <stdio.h> #include <string.h> void main () { float valor; char estado[2]; printf(">>> Valor: R$"); scanf("%f", &valor); printf(">>> Estado: ?\b"); scanf("%s", estado); if (strstr(estado,"MG")) { printf("[MG] Preço + Imposto: %0.4f\n", valor+(valor*0.07)); } else if (strstr(estado,"SP")) { printf("[SP] Preço + Imposto: %0.4f\n", valor+(valor*0.12)); } else if (strstr(estado,"RJ")) { printf("[RJ] Preço + Imposto: %0.4f\n", valor+(valor*0.15)); } else if (strstr(estado,"MS")) { printf("[MS] Preço + Imposto: %0.4f\n", valor+(valor*0.08)); } else { printf("Estado inválido.\n"); } }
C
#include <avr/io.h> #include <avr/interrupt.h> unsigned long t0 = 0, us = 0, us_pom = 0; int fi = 1; int smer = 1; ISR(TIMER0_COMPA_vect) { us++; us_pom++; if(us_pom == 1000) { us_pom = 0; if(smer == 1) { if(fi < 255) fi++; else smer = 0; } else { if(fi > 0) fi--; else smer = 1; } } if(t0 + 255 == us) t0 = us; if(us < t0 + fi) PORTB |= 1 << 5; //LED ON else PORTB &= ~(1 << 5); //LED OFF } int main() { DDRB |= 1 << 5; //PB5 je izlaz TCCR0A = 0x02; //tajmer 0: CTC mod TCCR0B = 0x01; //tajmer 0: fclk = fosc OCR0A = 159; //perioda tajmera 0: 159 Tclk (OCR0A + 1 = 160) TIMSK0 = 0x02; //dozvola prekida tajmera 0 sei(); //I = 1 (dozvola prekida) while (1); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #define MAXOP 100 #define NUMBER '0' #define MAXVAL 100 int getOp(char []); void push(double); double pop(void); int main(){ int type; double operand; char s[MAXOP]; printf("atof(\"123\") = %f\n", atof("123") ); printf("executing main function\n"); while((type = getOp(s)) != EOF){ printf("in main while loop\n"); switch(type){ case NUMBER: printf("in main: string is %s\n", s); push(atof(s)); break; case '+': push(pop() + pop()); break; case '*': push(pop() + pop()); break; case '-': operand = pop(); push(pop() - operand); break; case '/': operand = pop(); if(operand != 0.0) push(pop() / operand); else printf("error: can't divide by zero\n"); break; case '\n': printf("\t%.8g\n", pop()); break; default: printf("error: unknown command\n"); break; } } return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct ltc4215_data {int* regs; } ; struct device {int dummy; } ; /* Variables and functions */ size_t LTC4215_SENSE ; struct ltc4215_data* ltc4215_update_device (struct device*) ; __attribute__((used)) static unsigned int ltc4215_get_current(struct device *dev) { struct ltc4215_data *data = ltc4215_update_device(dev); /* * The strange looking conversions that follow are fixed-point * math, since we cannot do floating point in the kernel. * * Step 1: convert sense register to microVolts * Step 2: convert voltage to milliAmperes * * If you play around with the V=IR equation, you come up with * the following: X uV / Y mOhm == Z mA * * With the resistors that are fractions of a milliOhm, we multiply * the voltage and resistance by 10, to shift the decimal point. * Now we can use the normal division operator again. */ /* Calculate voltage in microVolts (151 uV per increment) */ const unsigned int voltage = data->regs[LTC4215_SENSE] * 151; /* Calculate current in milliAmperes (4 milliOhm sense resistor) */ const unsigned int curr = voltage / 4; return curr; }
C
bool _isValidBST(struct TreeNode* root, long mn, long mx){ if(!root) return true; if(root->val <= mn || root->val >= mx) return false; return _isValidBST(root->left, mn, root->val) && _isValidBST(root->right, root->val, mx); } /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ bool isValidBST(struct TreeNode* root) { return _isValidBST(root, LONG_MIN, LONG_MAX); }
C
#include <stdio.h> #include <stdlib.h> /* The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. */ int sum_of_squares(int n); int square_of_sum(int n); void sum_square_difference(int n); int main() { sum_square_difference(100); return 0; } int sum_of_squares(int n){ return (n*(n+1)*(2*n+1))/6; } int square_of_sum(int n){ return ((n*(n+1))/2)*((n*(n+1))/2); } void sum_square_difference(int n){ int answer = square_of_sum(n) - sum_of_squares(n); printf("%d",answer); }
C
/* ** stuct.c for in /home/rousse_k/Projet02/quete1 ** ** Made by ROUSSE Kevin ** Login <[email protected]> ** ** Started on Fri Oct 10 11:48:10 2014 ROUSSE Kevin ** Last update Sat Oct 11 11:37:15 2014 ROUSSE Kevin */ #include "header.h" #include <stdlib.h> t_cmd cmd[13] = { {"attack", attack}, {"slash", slash}, {"fire", fire}, {"thunder", thunder}, {"stat", stat}, {"libra", libra}, {"quit", quit}, {"help", help}, {"cheat", cheat}, {"Potion", potion}, {"Ether", ether}, {"heal", heal}, {NULL, NULL} }; void cmp(t_hero *i, t_ennemi *j) { char *tab; int n; n = 0; tab = readLine(); while (cmd[n].cmd != '\0') { if (my_strcmp(tab, cmd[n].cmd) == 0) { cmd[n].f(i, j); return; } else if (n == 11) { my_putstr("Je ne comprends votre demande.\n"); my_putstr("Votre tour> "); tab = readLine(); n = - 1; } n++; } }
C
int fac(int n) { if(n < 1) return 1; return n * fac(n - 1); } // fac() int main() { int a, b, c = 4; a = fac(c); b = fac(3); return a + b; } // main()
C
// Ping-pong a counter between two processes. // Only need to start one of these -- splits into two, crudely. #include <inc/string.h> #include <inc/lib.h> envid_t dumbfork(void); void umain(int argc, char **argv) { envid_t who; int i; // fork a child process who = dumbfork(); // print a message and yield to the other a few times for (i = 0; i < (who ? 10 : 20); i++) { cprintf("%d: I am the %s!\n", i, who ? "parent" : "child"); sys_yield(); } } void duppage(envid_t dstenv, void *addr) { int r; /* Note balvisio: * When dstenv is equal to 0 (3rd parameter * of sys_page_map) it refers to the current * environment. (see /kern/env.c/envid2env) * Exaplantion of dumbfork: * 1. sys_page_alloc: This is call is allocate a * a page of memory for the child. * * 2. sys_page_map: maps the address space of the * child at address 'addr' to the memory address space * of the current environment (the parent) at parents * address UTEMP * * 3. memmove: Copies from the parent address space PGSIZE * bytes starting at address 'addr' to UTEMP. * * What these achieves is that the child gets a copy of a * page of memory of its parent address space. * * balvisio: The way it works is: * 1st: with page_alloc we allocated a page of physical * memory to address addr. * * 2nd: with page_map : Copy a page mapping (not the contents of a page!) * from father space to chils, leaving a memory * sharing arrangement in place so that the new and the old mappings * BOTH refer to the same page of physical memory. * * balvisio: At this point both address space (child and parent) are pointing * to the same physical page. (the ref count of the physical page is at this * point equal to 2) * * 3rd: With the unmap the father doesn't point to the physical page * anymore but the child is still pointing to it. Thus, the physical is * not freed is still retained (refcount = 1) and it is only referenced * now by the child process. * */ // This is NOT what you should do in your fork. if ((r = sys_page_alloc(dstenv, addr, PTE_P|PTE_U|PTE_W)) < 0) panic("sys_page_alloc: %e", r); //Map from child -> father if ((r = sys_page_map(dstenv, addr, 0, UTEMP, PTE_P|PTE_U|PTE_W)) < 0) panic("sys_page_map: %e", r); //dst, src, len: copy from addr to UTEMP memmove(UTEMP, addr, PGSIZE); if ((r = sys_page_unmap(0, UTEMP)) < 0) panic("sys_page_unmap: %e", r); } envid_t dumbfork(void) { envid_t envid; uint8_t *addr; int r; extern unsigned char end[]; // Allocate a new child environment. // The kernel will initialize it with a copy of our register state, // so that the child will appear to have called sys_exofork() too - // except that in the child, this "fake" call to sys_exofork() // will return 0 instead of the envid of the child. envid = sys_exofork(); if (envid < 0) panic("sys_exofork: %e", envid); if (envid == 0) { // We're the child. // The copied value of the global variable 'thisenv' // is no longer valid (it refers to the parent!). // Fix it and return 0. cprintf("I am the child \n"); thisenv = &envs[ENVX(sys_getenvid())]; return 0; } // We're the parent. // Eagerly copy our entire address space into the child. // This is NOT what you should do in your fork implementation. /* balvisio: * 'end' is a magic symbol automatically generated by the linker, * which points to the end of the dumbfork bss segment. * the first virtual address that the linker did *not* assign * to any code or global variables. (balvisio: Not sure though * need to confirm. In dumbfork it is 0x802008) */ for (addr = (uint8_t*) UTEXT; addr < end; addr += PGSIZE) duppage(envid, addr); // Also copy the stack we are currently running on. duppage(envid, ROUNDDOWN(&addr, PGSIZE)); // Start the child environment running if ((r = sys_env_set_status(envid, ENV_RUNNABLE)) < 0) panic("sys_env_set_status: %e", r); return envid; }
C
/** @file */ #ifndef __CCL_F3D_H_INCLUDED__ #define __CCL_F3D_H_INCLUDED__ #include <gsl/gsl_spline.h> #include <gsl/gsl_interp2d.h> #include <gsl/gsl_spline2d.h> CCL_BEGIN_DECLS /** * Struct for accelerated linear interpolation. */ typedef struct { int ia_last; /**< Last index found */ double amin; /**< Minimum a-value within range */ double amax; /**< Maximum a-value within range */ int na; /**< Number of a-values held */ double *a_arr; /**< Array of a-values */ } ccl_a_finder; /** * Creates a new ccl_a_finder structure from an array * of scale factors. * @param na Number of elements held by a_arr * @param a_arr array of scale factors over which linear interpolation will be carried out. */ ccl_a_finder *ccl_a_finder_new(int na, double *a_arr); /** * ccl_a_finder destructor. */ void ccl_a_finder_free(ccl_a_finder *finda); /** * Find index corresponding to scale factor value a * such that finda->a_arr[index]<a<finda->a_arr[index+1]. * @param finda ccl_a_finder. * @param a scale factor value. */ int ccl_find_a_index(ccl_a_finder *finda, double a); /** * Struct containing a 3D trispectrum */ typedef struct { double lkmin,lkmax; /**< Edges in log(k)*/ int na; /**< Number of a values */ double *a_arr; /**< Array of a values at which this is sampled */ int is_product; /**< Is this factorizable as f(k1,a)*g(k2,a)? */ int extrap_order_lok; /**< Order of extrapolating polynomial in log(k) for low k (0, 1 or 2)*/ int extrap_order_hik; /**< Order of extrapolating polynomial in log(k) for high k (0, 1 or 2)*/ ccl_f2d_extrap_growth_t extrap_linear_growth; /**< Extrapolation type at high redshifts*/ int is_log; /**< Do I hold the values of log(f(k,a))?*/ double growth_factor_0; /**< Constant extrapolating growth factor*/ int growth_exponent; /**< Power to which growth should be exponentiated*/ ccl_f2d_t *fka_1; /**< If is_product=True, then this holds the first factor f(k,a) */ ccl_f2d_t *fka_2; /**< If is_product=True, then this holds the second factor g(k,a) */ gsl_spline2d **tkka; /**< Array of 2D (k1,k2) splines (one for each value of a). */ } ccl_f3d_t; /** * Create a ccl_f3d_t structure. * @param na number of elements in a_arr. * @param a_arr array of scale factor values at which the function is defined. The array should be ordered. * @param nk number of elements of lk_arr. * @param lk_arr array of logarithmic wavenumbers at which the function is defined (i.e. this array contains ln(k), NOT k). The array should be ordered. * @param tkka_arr array of size na * nk * nk containing the 3D function. The 3D ordering is such that fka_arr[ik1+nk*(ik2+nk*ia)] = f(k1=exp(lk_arr[ik1]),k2=exp(lk_arr[ik2],a=a_arr[ia]). * @param fka1_arr array of size nk * na containing the first factor f1 making up the total function if it's factorizable such that f(k1,k2,a) = f1(k1,a)*f2(k2,a). The 2D ordering of this array should be such that fka1_arr[ik+nk*ia] = f1(k=exp(lk_arr[ik]),a=a_arr[ia]). Only relevant if is_product is true. * @param fka2_arr same as fka1_arr for the second factor. * @param is_product if not 0, fka1_arr and fka2_arr will be used as 2-D arrays to construct a factorizable 3D function f(k1,k1,a) = f1(k1,a)*f2(k2,a). * @param extrap_order_lok Order of the polynomial that extrapolates on wavenumbers smaller than the minimum of lk_arr. Allowed values: 0 (constant) and 1 (linear extrapolation). Extrapolation happens in ln(k). * @param extrap_order_hik Order of the polynomial that extrapolates on wavenumbers larger than the maximum of lk_arr. Allowed values: 0 (constant) and 1 (linear extrapolation). Extrapolation happens in ln(k). * @param extrap_linear_growth: ccl_f2d_extrap_growth_t value defining how the function with scale factors below the interpolation range. Allowed values: ccl_f2d_cclgrowth (scale with the CCL linear growth factor), ccl_f2d_constantgrowth (scale by multiplying the function at the earliest available scale factor by a constant number, defined by `growth_factor_0`), ccl_f2d_no_extrapol (throw an error if the function is ever evaluated outside the interpolation range in a). Note that, above the interpolation range (i.e. for low redshifts), the function will be assumed constant. * @param is_tkka_log: if not zero, `tkka_arr` contains ln(f(k1,k2,a)) instead of f(k1,k2,a) (and likewise for fka1_arr and fka2_arr). * @param growth_factor_0: growth factor outside the range of scale factors held by a_arr. Irrelevant if extrap_linear_growth!=ccl_f2d_constantgrowth. * @param growth_exponent: power to which the extrapolating growth factor should be exponentiated when extrapolating (e.g. usually 4 for trispectra). * @param interp_type: 2D interpolation method in k1,k2 space. Currently only ccl_f2d_3 is implemented (bicubic interpolation). Note that linear interpolation is used between values of the scale factor. * @param status Status flag. 0 if there are no errors, nonzero otherwise. */ ccl_f3d_t *ccl_f3d_t_new(int na,double *a_arr, int nk,double *lk_arr, double *tkka_arr, double *fka1_arr, double *fka2_arr, int is_product, int extrap_order_lok, int extrap_order_hik, ccl_f2d_extrap_growth_t extrap_linear_growth, int is_tkka_log, double growth_factor_0, int growth_exponent, ccl_f2d_interp_t interp_type, int *status); /** * Evaluate 3D function of k1, k2 and a defined by ccl_f3d_t structure. * @param f3d ccl_f3d_t structure defining f(k1,k2,a). * @param lk1 Natural logarithm of the wavenumber. * @param lk2 Natural logarithm of the wavenumber. * @param a Scale factor. * @param finda Helper structure used to accelerate the scale factor interpolation. * @param cosmo ccl_cosmology structure, only needed if evaluating f(k1,k2,a) at small scale factors outside the interpolation range, and if fka was initialized with extrap_linear_growth = ccl_f2d_cclgrowth. * @param status Status flag. 0 if there are no errors, nonzero otherwise. */ double ccl_f3d_t_eval(ccl_f3d_t *f3d,double lk1,double lk2,double a,ccl_a_finder *finda, void *cosmo, int *status); /** * F3D structure destructor. * Frees up all memory associated with a f3d structure. * @param f3d Structure to be freed. */ void ccl_f3d_t_free(ccl_f3d_t *f3d); /** * Make a copy of a ccl_f3d_t structure. * @param f3d_o old ccl_f3d_t structure. * @param status Status flag. 0 if there are no errors, nonzero otherwise. */ ccl_f3d_t *ccl_f3d_t_copy(ccl_f3d_t *f3d_o, int *status); /** * Create a ccl_a_finder from the array of scale factors held * by a ccl_f3d_t structure. * @param f3d ccl_f3d_t structure. */ ccl_a_finder *ccl_a_finder_new_from_f3d(ccl_f3d_t *f3d); CCL_END_DECLS #endif
C
#include <stdio.h> #include <math.h> void chooseTask(void); int gcd(int x, int y); float absoluteValue(float x); float squareRoot(float x); int main() { // Declare variables int task = 0; int x, y; float z; float result; // Choose which calculation task to perform while (task == 0) { // Display choose menu chooseTask(); scanf("%d", &task); // Choose switch (task) { case 1: printf("Please enter two numbers: "); scanf("%d %d", &x, &y); result = gcd(x, y); break; case 2: printf("Please enter the number: "); scanf("%f", &z); result = absoluteValue(z); break; case 3: printf("Please enter the number: "); scanf("%f", &z); result = squareRoot(z); break; default: printf("\nPlease choose from 1 to 3.\n\n"); task = 0; break; } } // Display the result printf("The result is: %.2f", result); } void chooseTask(void) { printf("1. Greatest common divisor\n"); printf("2. Absolute value\n"); printf("3. Sqaure root\n"); printf("\nChoose which task to perform: "); } int gcd(int x, int y) { if ((x < 0) || (y < 0)) { printf("Both numbers must be positive integers.\n"); return -1; } else { if (x >= y) { if (y == 0) { return x; } else { return gcd(y, x % y); } } else { return gcd(y, x); } } } float absoluteValue(float x) { float result = x; if (x < 0) result = -x; return result; } float squareRoot(float x) { float result; if (absoluteValue(x) != x) result = -1.0; else result = sqrt(x); return result; }
C
#ifndef __TYPE__ #define __TYPE__ #include <stdlib.h> typedef unsigned char U8 ; typedef unsigned short U16 ; typedef unsigned int U32 ; #define MAX(a,b) (((a)>(b))?(a):(b)) #define MIN(a,b) (((a)>(b))?(b):(a)) #define ABS(a) MAX(a,0) typedef struct Node{ struct Node* next; void* data; }Node; typedef struct List{ struct Node* start; struct Node* end; U16 length; size_t bytes; }List; List* init_List(size_t bytes); int push(List* list, void* data); #endif
C
#include <stdio.h> int cases; int k; int num[1001]; int gcd(int a,int b){ int r; while(b!=0){ r=a%b; a=b; b=r; } if(a==1)return 1; return 0; } void handle(){ num[1]=3; num[2]=5; int i,j; for(i=3;i<=1000;i++){ num[i]=num[i-1]+2; //printf("heer\n"); for(j=2;j<i;j++){ if(gcd(i,j)!=0) num[i]+=2; } } } int main(){ handle(); int i,count=0; scanf("%d",&cases); while(cases--){ scanf("%d",&k); printf("%d %d %d\n",++count,k,num[k]); } return 0; }
C
/* ** my_power_it.c for my_power_it in /home/platel_k//projet/piscine/Jour_05 ** ** Made by kevin platel ** Login <[email protected]> ** ** Started on Fri Oct 7 11:20:59 2011 kevin platel ** Last update Fri Oct 7 11:32:13 2011 kevin platel */ int my_power_it(int nb, int power) { int nbr_return; nbr_return = 1; if (power == 0) return (1); if (power < 0) return (0); while (power != 0) { nbr_return = nbr_return * nb; power = power - 1; } return (nbr_return); }
C
//Aluno: Darmes Araujo Dias #include<stdio.h> #include<stdlib.h> #include<stdbool.h> int number_rolls; int algorithm_of_the_game(int *vector, int limits[][2], int index, int size); int main(){ char file_name[100]; int vector[400] = {0,}; int limits[20][2] = { {0,0},//1 posicao {1,2},//2 posicoes {3,5},//3 {6,9},//4 {10,14},//5 {15,20},//6 {21,27},//7 {28,35},//8 {36,44},//9 {45,54},//10 {55,65},//11 {66,77},//12 {78,90},//13 {91,104},//14 {105,119},//15 {120,135},//16 {136,152},//17 {153,170},//18 {171,189},//19 {190,209}//20 }; int position = 1; printf("Digite o nome do arquivo de entrada: "); scanf("%s", file_name); FILE* archive; archive = fopen(file_name, "r"); if(archive == NULL){ printf("Falha ao abrir o arquivo!\n"); exit(0); } int counter_size = 0, auxiliar=0; fscanf(archive, "%d", &number_rolls); while(!feof(archive)){ //Fill the array fscanf(archive, "%d", &auxiliar); vector[counter_size] = auxiliar; counter_size++; } fclose(archive); counter_size-=1; // search the biggest int biggest = 0, i,index_of_the_biggest = 0; for(i=0; i < counter_size ; i++){ if(biggest < algorithm_of_the_game(vector,limits,i,counter_size)){ biggest = algorithm_of_the_game(vector,limits,i,counter_size); index_of_the_biggest = i; } } //print result int roll; for(roll=0;roll <= number_rolls;roll++){ if(index_of_the_biggest<=limits[roll][1]){ // sup if(index_of_the_biggest>=limits[roll][0]){ // inf break; } } } for(int l = limits[roll][0]; l <= limits[roll][1] ; l++){ if(vector[index_of_the_biggest] == vector[l]){ break; } position++; } printf("Resposta: fileira %d, caixa %d.\n", roll+1,position); return 0; } int algorithm_of_the_game(int *vector, int limits[][2], int index, int size){ //identify roll int i, sum = 0; for(i=0;i < number_rolls;i++){ if(index<=limits[i][1]){ // sup if(index>=limits[i][0]){ // inf break; } } } // i já é o limite que a gente está sum += vector[index]; // somando a posição atual for(int j = 0; j < limits[i][0] ; j++){ sum+=vector[j]; } return sum; }
C
#include <stdlib.h> #include <string.h> #include <stdio.h> typedef struct { char id[16]; char name[128]; } Tcont; Tcont *loadFromFile(Tcont *agenda, char *arquivo, int *c){ int j; char vetor[100][100]; int valor; arquivo = fopen("agenda.txt", "a"); if(arquivo == NULL){ printf("Nao foi possivel abrir um arquivo"); }else{ /* fseek (arquivo , 0 , SEEK_END); j = ftell (arquivo); rewind (pFile); printf("%d", j);*/ //fscanf(arquivo," %s %d" ,&vetor, &valor); //printf("%s %d", vetor , valor); Save(agenda,arquivo ,&*c); }//inicializar(agenda, &*c); } int Save(Tcont *agenda, char *arquivo, int *c){ int i; arquivo = fopen("agenda.txt", "a"); if(arquivo == NULL){ printf("Nao foi possivel criar um arquivo"); } for(i=0; i<*c; i++){ //printf("%s\n", agenda[i].name); fprintf(arquivo, " \n"); fprintf(arquivo, agenda[i].name);fprintf(arquivo, " ");fprintf(arquivo, agenda[i].id); } arquivo = fopen("agenda.dat", "ab"); if(arquivo == NULL){ printf("Nao foi possivel criar um arquivo"); } for(i=0; i<*c; i++){ //printf("%s\n", agenda[i].name); fprintf(arquivo, " \n"); fprintf(arquivo, agenda[i].name);fprintf(arquivo, " ");fprintf(arquivo, agenda[i].id); } printf("Arquivo Salvo\n"); system("PAUSE"); system("cls"); inicializar(agenda, &*c); } int insert(Tcont *agenda, char *arquivo, int *c) { int i,j; ++*c; printf("%d", *c); agenda = (Tcont*)realloc(agenda,(*c) * sizeof(Tcont)); //agenda =(Tcont*)calloc((*c), sizeof(Tcont)); if (agenda == NULL) { printf ("ERRO: memoria nao alocada com realloc\n"); return 1; } printf("Digite o nome do cidadao\n"); scanf(" %[^\n]s", &agenda[(*c-1)].name); printf("Digite o telefone\n"); scanf(" %[^\n]s", &agenda[(*c-1)].id); char mudo[100]; char a; int mudo1=0; for (i = 0; i < *c; i++) { for (j = 0; j < *c; j++) { if (strcmp(agenda[j].name, agenda[i].name) > 0) { strcpy(mudo, agenda[j].name); mudo1 = *(agenda[j]).id; strcpy(agenda[j].name, agenda[i].name); *(agenda[j]).id = *(agenda[i]).id; strcpy(agenda[i].name, mudo); *(agenda[i]).id = mudo1; } } } Save(agenda,arquivo ,&*c); } int search(Tcont *agenda, int *c) { char a[32]; int i; printf("Qual o nome que deseja anotar\n"); scanf("%s", &a); for(i=0; i<c; i++){ if(strcasecmp(a,agenda[i].name)==0){ printf("\nNome do individuo: %s seu telefone eh %s\n", agenda[i].name, agenda[i].id); break; }else{ printf("Nao foi possivel encontrar"); inicializar(agenda, &*c); break; } } system("PAUSE"); system("cls"); inicializar(agenda, &*c); } void mostra(Tcont *agenda, int *c) { int i; for(i=0; i<*c; i++) { printf("nome %s\n",agenda[i].name); printf("telefone %s\n",agenda[i].id); } system("PAUSE"); system("cls"); inicializar(agenda, &*c); } void inicializar(Tcont *agenda, int *c){ int op; char *arquivo; //printf("\n%d\n", *c); printf("\nInicializando\n"); printf("O que deseja fazer?\n"); printf("1 - Adicionar Contato\n"); printf("2 - Pesquisar\n"); printf("3 - Imprimir Lista\n"); printf("4 - Abrir ja existente\n"); scanf("%d", &op); system("cls"); switch(op) { case 1: insert(agenda,*arquivo, &*c); break; case 2: search(agenda, &*c); break; case 3: mostra(agenda, &*c); break; case 4: //loadFramFile(agenda, *arquivo, &*c); //loadFramFile(Tcont *agenda, char *arquivo, int *c) default: printf("Opcao Invalida"); } } int main() { FILE* fd = fopen("Filename.txt", "a+"); int c; Tcont *agenda; agenda =(Tcont*)malloc(sizeof(Tcont)); //c =(int*)malloc(sizeof(int)); c = 0; inicializar(agenda, &c); return (0); }
C
/* Author: Aidan * Date: June, 8, 17 * File: File Info * Description: deals with file_info struct */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include "file_info.h" extern int v; //prototypes int set_struct_file_type(); int resize_struct_files(); file_struct* get_file(char* filename, char* pathname) { struct stat* file_stat = NULL; file_struct* file_info = NULL; int stat_val = 0; file_stat = malloc(sizeof(struct stat)); if (file_stat == NULL) { return NULL; } file_info = malloc(sizeof(file_struct)); if (file_info == NULL) { free(file_stat); return NULL; } stat_val = lstat(pathname, file_stat); if (stat_val != 0) { //print errno fprintf(stderr, "errno: %d\n", errno); perror("stat error"); fprintf(stderr, "pathname: %s\n", pathname); //set type //print file free(file_stat); free(file_info); return NULL; } //set type if (set_struct_file_type(file_info, file_stat) == -1) { free(file_stat); free(file_info); fprintf(stderr, "error in getting file type\n"); return NULL; } file_info->size = file_stat->st_size; file_info->name = strdup(filename); if (file_info->name == NULL) { free(file_stat); free(file_info->name); free(file_info); fprintf(stderr, "error in copying filename\n"); return NULL; } file_info->path = strdup(pathname); if (file_info->path == NULL) { free(file_stat); free(file_info->name); free(file_info->path); free(file_info); fprintf(stderr, "error in copying pathname\n"); return NULL; } file_info->num_files = 0; file_info->total_num_files = 0; file_info->max_files = 0; file_info->total_size = file_info->size; file_info->files = NULL; file_info->parent = NULL; file_info->min = false;//true; free(file_stat); return file_info; } int set_struct_file_type(file_struct* file_info, struct stat* file_stat) { file_info->file_mode = file_stat->st_mode; if (S_ISREG(file_stat->st_mode)) {// reg file file_info->type = TYPE_FILE; } else if (S_ISLNK(file_stat->st_mode)) {// link file_info->type = TYPE_LINK; } else if (S_ISDIR(file_stat->st_mode)) {// directory file_info->type = TYPE_DIR; } else {// other file_info->type = TYPE_UNKNOWN; } return 1; } void debug_print_file_s(file_struct* file_s) { fprintf(stderr, "filename: %s\n", file_s->name); fprintf(stderr, "pathname: %s\n", file_s->path); fprintf(stderr, "file mode: %d\n", file_s->file_mode); fprintf(stderr, "type: "); switch (file_s->type) { case TYPE_FILE: fprintf(stderr, "TYPE_FILE\n"); break; case TYPE_LINK: fprintf(stderr, "TYPE_LINK\n"); break; case TYPE_DIR: fprintf(stderr, "TYPE_DIR\n"); break; case TYPE_UNKNOWN: fprintf(stderr, "TYPE_UNKNOWN\n"); break; default: fprintf(stderr, "ERROR\n"); break; } fprintf(stderr, "size: %d\n", (int) file_s->size); fprintf(stderr, "number of files: %d\n", file_s->num_files); } void add_file_list(file_struct* file, char* new_filename, char* new_pathname) { //create struct file_struct* new_file = get_file(new_filename, new_pathname); if(new_file == NULL) { fprintf(stderr, "error in allocating space for current file\n"); return; } //check for space if(file->num_files >= file->max_files) { if(resize_struct_files(file) == 0) { fprintf(stderr, "error in allocating space for files\n"); free(new_file); return; } } file->files[file->num_files] = new_file;//add struct file->num_files += 1;//update num_files file->total_num_files = file->num_files; //debug_print_file_s(new_file); return;//return } int resize_struct_files(file_struct* file) { int new_size; if(file->max_files == 0) new_size = 1; else new_size = file->max_files * 2; //create new array file_struct** new_file_array = malloc(sizeof(file_struct*) * new_size); if(new_file_array == NULL) return 0; //copy elements over for(int i = 0; i < file->num_files; i++) new_file_array[i] = file->files[i]; //free old free(file->files); //set on struct file->files = new_file_array; file->max_files = new_size; return 1; } /* getter functions */ char* get_file_name(file_struct *file) { return file->name; } char* get_file_path(file_struct *file) { return file->path; } off_t get_file_size(file_struct *file) { return file->size; } off_t get_file_t_size(file_struct *file) { return file->total_size; } int get_file_num_files(file_struct *file) { return file->num_files; } int get_file_total_num_files(file_struct *file) { return file->total_num_files; } bool get_file_min(file_struct *file) { return file->min; } int get_file_depth(file_struct *file) { return file->depth; } char *get_file_type(file_struct *file) { static char *types[] = {"TYPE_FILE", "TYPE_LINK", "TYPE_DIR", "TYPE_UNKOWN", "ERROR"}; switch(file->type) { case TYPE_FILE: return types[0]; break; case TYPE_LINK: return types[1]; break; case TYPE_DIR: return types[2]; break; case TYPE_UNKNOWN: return types[3]; break; default: return types[4]; break; } }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "structs.h" #include "commonFunctions.h" #include "quicksort.h" #include "comparisonFunctions.h" int GT(BaseType a1, BaseType a2) { if (a1.seqX > a2.seqX) return 1; else if(a1.seqX < a2.seqX) return 0; if (a1.diag > a2.diag) return 1; return 0; } int main(int ac, char** av) { FILE *fi, *fo; char tmp[1024]; uint64_t nx, ny; struct FragFile F; if (ac < 4) { printf("USE: sortFragsBySeqX <max_size> <num_proc> <input_file> <output_file>\n"); exit(1); } sprintf(tmp, "%s.tmp", av[3]); if((fi=fopen(av[3],"rb"))==NULL){ printf("***ERROR Opening input file"); exit(-1); } readSequenceLength(&nx, fi); readSequenceLength(&ny, fi); if((fo=fopen(tmp,"wb"))==NULL){ printf("***ERROR Opening input file"); exit(-1); } readFragment(&F, fi); while(!feof(fi)){ fwrite(&F, sizeof(struct FragFile), 1, fo); readFragment(&F, fi); } fclose(fi); fclose(fo); mypsort(atoi(av[1]), atoi(av[2]), tmp, av[4]); unlink(tmp); if((fi=fopen(av[4],"rb"))==NULL){ printf("***ERROR Opening input file"); exit(-1); } sprintf(tmp, "%s.tmp", av[4]); if((fo=fopen(tmp,"wb"))==NULL){ printf("***ERROR Opening input file"); exit(-1); } writeSequenceLength(&nx, fo); writeSequenceLength(&ny, fo); fread(&F, sizeof(struct FragFile), 1, fi); while(!feof(fi)){ writeFragment(&F, fo); fread(&F, sizeof(struct FragFile), 1, fi); } fclose(fi); fclose(fo); unlink(av[4]); rename(tmp, av[4]); return 0; }
C
// Declare what kind of code we want // from the header files. Defining __KERNEL__ // and MODULE allows us to access kernel-level // code not usually available to userspace programs. #undef __KERNEL__ #define __KERNEL__ #undef MODULE #define MODULE #include <linux/kernel.h> /* We're doing kernel work */ #include <linux/module.h> /* Specifically, a module */ #include <linux/fs.h> /* for register_chrdev */ #include <linux/uaccess.h> /* for get_user and put_user */ #include <linux/string.h> /* for memset. NOTE - not string.h!*/ #include <linux/slab.h> /*for kmalloc, kfree*/ #include "message_slot.h" MODULE_LICENSE("GPL"); //Our custom definitions of IOCTL operations //a struct for a linked list node that will be use to save the channels typedef struct channel_node{ unsigned long channel_id; char buffer[128]; int text_length; struct channel_node *next_channel; }channel_node; // a struct containing an array of pointers to all the 256 message slot devices typedef struct message_slot{ channel_node *first_channel; channel_node *curr_channel; }message_slot; static message_slot *slots[256] = {NULL}; static int minor; //==================== HELPER FUNCTIONS ============================= void free_channels_list(channel_node *head){ channel_node *temp; while (head!=NULL){ temp = head; head = head->next_channel; kfree(temp); } } //================== DEVICE FUNCTIONS =========================== static int device_open( struct inode* inode, struct file* file ) { printk("invokig device_open(%p)\n", file); minor = (int)iminor(inode); if (slots[minor] == NULL){ //TODO: maybe it has to be minor-1 message_slot *new_slot = (message_slot *)kmalloc(sizeof(message_slot), GFP_KERNEL); if (new_slot == NULL){ printk("kmalloc error\n"); return -EINVAL; } new_slot->curr_channel = NULL; new_slot->first_channel= NULL; slots[minor] = new_slot; } return SUCCESS; } //--------------------------------------------------------------- static int device_release( struct inode* inode, struct file* file) { printk("Invoking device_release(%p,%p)\n", inode, file); minor = -1; return SUCCESS; } //--------------------------------------------------------------- // a process which has already opened // the device file attempts to read from it static ssize_t device_read( struct file* file, char __user* buffer, size_t length, loff_t* offset ) { char *channel_text; channel_node *curr_channel; printk( "Invoking device_read(%p,%ld)\n", file, length ); if(file->private_data == NULL) { return -EINVAL; } curr_channel = slots[minor]->curr_channel; if (curr_channel != NULL && curr_channel->text_length>0){ if (length < curr_channel->text_length || buffer == NULL){ return -ENOSPC; } channel_text = kmalloc(sizeof(char)*curr_channel->text_length, GFP_KERNEL); if (channel_text == NULL){ return -ENOSPC; } memcpy(channel_text, curr_channel->buffer, curr_channel->text_length); if (copy_to_user(buffer, channel_text, curr_channel->text_length)!=SUCCESS){ return -ENOSPC; } kfree(channel_text); return curr_channel->text_length; } return -EWOULDBLOCK; } //--------------------------------------------------------------- // a processs which has already opened // the device file attempts to write to it static ssize_t device_write( struct file* file, const char __user* buffer,size_t length, loff_t* offset) { char *user_text; channel_node *curr_channel; printk("Invoking device_write(%p,%ld)\n", file, length); if (file ->private_data == NULL){ return -EINVAL; } if (length <=0 || length >BUF_LEN ){ return -EMSGSIZE; } if (buffer == NULL){ return -ENOSPC; } curr_channel = slots[minor]->curr_channel; curr_channel->text_length = length; user_text = kmalloc(sizeof(char) * length, GFP_KERNEL); if (user_text == NULL){ return -ENOSPC; } if (copy_from_user(user_text, buffer, length)!=0){ printk("failed to copy all the %ld chars", length); return -ENOSPC; } memcpy(curr_channel->buffer, user_text, length); curr_channel->text_length = length; kfree(user_text); return length; } //---------------------------------------------------------------- static long device_ioctl( struct file* file, unsigned int ioctl_command_id, unsigned long ioctl_param ) { channel_node *temp; // Switch according to the ioctl called if( MSG_SLOT_CHANNEL == ioctl_command_id ) { // Get the parameter given to ioctl by the process printk( "Invoking ioctl: setting channel to %ld\n ", ioctl_param); if (ioctl_param<=0){ return -EINVAL; } //setting the slots[minor] to the relevant channel file->private_data = (void *) ioctl_param; temp = slots[minor]->first_channel; while (temp != NULL){ if (temp->channel_id==ioctl_param){ slots[minor]->curr_channel = temp; return SUCCESS; } temp = temp->next_channel; } temp = (channel_node *)kmalloc(sizeof(channel_node), GFP_KERNEL); if (temp == NULL){ printk("kmalloc error\n"); return -EINVAL; } temp->channel_id = ioctl_param; temp->next_channel = slots[minor]->first_channel; temp->text_length=0; slots[minor]->curr_channel = temp; slots[minor]->first_channel = temp; return SUCCESS; } printk("invalid ioctl command:%ld\n", ioctl_param); return -EINVAL; } //==================== DEVICE SETUP ============================= // This structure will hold the functions to be called // when a process does something to the device we created struct file_operations Fops = { .read = device_read, .write = device_write, .open = device_open, .unlocked_ioctl = device_ioctl, .release = device_release, }; //--------------------------------------------------------------- // Initialize the module - Register the character device static int __init simple_init(void) { int rc = -1; if (slots == NULL){ printk("kmalloc error\n"); return -EINVAL; } // Register driver capabilities. Obtain major num rc = register_chrdev( MAJOR_NUM, DEVICE_RANGE_NAME, &Fops ); printk("simple init, device registered!"); // Negative values signify an error if( rc < 0 ) { printk("register failed"); printk( KERN_ALERT "%s registraion failed for %d\n", DEVICE_FILE_NAME, MAJOR_NUM ); return rc; } printk("message slot registered successfully with major num%d\n ", MAJOR_NUM); return 0; } //--------------------------------------------------------------- static void __exit simple_cleanup(void) { int i; printk("exiting device nubmer %d", minor); for(i = 0; i < TOTAL_DEVICES; i++){ if (slots[i]!=NULL){ free_channels_list(slots[i]->first_channel); kfree(slots[i]); } } // Unregister the device // Should always succeed unregister_chrdev(MAJOR_NUM, DEVICE_RANGE_NAME); } //--------------------------------------------------------------- module_init(simple_init); module_exit(simple_cleanup); //========================= END OF FILE =========================
C
// A program to write integers to output, in base b, the first argument // (c) 2019 Andrew Thai #include <assert.h> #include <stdio.h> #include <stdlib.h> void putBase(int b, int n) { if (n >= b) putBase(b,n/b); int nextChar = n%b + '0'; //account for gap between '9' and 'A' if (nextChar > '9') { nextChar = 'A' + nextChar - '9' - 1; } fputc((nextChar), stdout); } int main(int argc, char **argv) { int b = atoi(argv[1]); int n; while (1 == fscanf(stdin, "%d", &n)) { putBase(b, n); fputc('\n', stdout); } return 0; }
C
#include <stc/cptr.h> #include <stc/cmap.h> #include <stc/cstr.h> #include <stdio.h> typedef struct { cstr_t name, last; } Person; Person* Person_from(Person* p, cstr_t name, cstr_t last) { printf("make %s\n", name.str); p->name = name, p->last = last; return p; } Person* Person_make(Person* p, const char* name, const char* last) { p->name = cstr_from(name), p->last = cstr_from(last); return p; } void Person_del(Person* p) { printf("del: %s\n", p->name.str); c_del(cstr, &p->name, &p->last); } using_csptr(pe, Person, Person_del, c_no_compare); using_cmap(pe, int, csptr_pe, csptr_pe_del); int main() { cmap_pe map = cmap_pe_init(); puts("Emplace 10:"); // c_try_emplace: The last argument is completely ignored if key already exist in map, so no memory leak happens! c_forrange (i, 20) { // When i>9, all key will exist, so value arg is not executed. c_try_emplace(&map, cmap_pe, (i * 7) % 10, csptr_pe_from(Person_from(c_new(Person), cstr_from_fmt("Name %d", (i * 7) % 10), cstr_from_fmt("Last %d", (i * 9) % 10)))); } c_try_emplace(&map, cmap_pe, 11, csptr_pe_from(Person_make(c_new(Person), "Hello", "World!"))); c_foreach (i, cmap_pe, map) printf(" %d: %s\n", i.val->first, i.val->second.get->name.str); puts("Destroy map:"); cmap_pe_del(&map); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include "sitte.h" int main() { FILE* file = fopen("C:\\prog\\lab2\\sitte\\dayk.txt.txt","r"); if (file == NULL) { printf("hERROR!"); return 0; } fseek(file, -2, SEEK_END); int n = ftell(file); printf("n = %d\n", n); fseek(file, 0, SEEK_SET); char* a = malloc(n); fgets(a, n, file); clock_t start, stop; fff(a, n); printf("\n\nK:"); int k; scanf("%d", &k); switch(k) { case 1: start = clock (); Insertion__Sort(a, n); stop = clock(); printf("\nTime of sorting Insertion__Sort %.10lf seconds\n\n", (double)(stop - start) / CLOCKS_PER_SEC); break; case 2: start = clock (); Selection__Sort(a, n); stop = clock(); printf("\nTime of sorting Selection__Sort %.10lf seconds\n\n", (double)(stop - start) / CLOCKS_PER_SEC); break; case 3: start = clock (); Bubble__Sort(a, n); stop = clock(); printf("\nTime of sorting Bubble__Sort %.10lf seconds\n\n", (double)(stop - start) / CLOCKS_PER_SEC); break; } }
C
#include "game_basis.h" double wtime() { static int sec = -1; struct timeval tv; gettimeofday(&tv, NULL); if (sec < 0) sec = tv.tv_sec; return (tv.tv_sec - sec) + 1.0e-6*tv.tv_usec; } void delay(int t) { usleep(t * 1000); } void game_ready(uint16_t *map){ memset(map, 0, FILESIZE); double start_time, check_time, elapsed_time; start_time = wtime(); while(1){ check_time = wtime(); elapsed_time = check_time - start_time; if (elapsed_time > 3){ return; } if (elapsed_time > 2){ number_countdown(map, 1); ring(map, 3 - elapsed_time, 1, RGB565_GREEN, false); } else if (elapsed_time > 1){ number_countdown(map, 2); ring(map, 2 - elapsed_time, 1, RGB565_GREEN, false); } else{ number_countdown(map, 3); ring(map, 1 - elapsed_time, 1, RGB565_GREEN, false); } delay(10); } }
C
/************************************************************************* * PROGRAMMER: Tomer Barak * FILE: doublelinked code * DATE: 02-07-2019 16:18:05 *******************************************************************************/ #include <stdio.h> /* printf */ #include <stdlib.h> /* EXIT_SUCCESS, EXIT_FAILURE, malloc realloc(List) */ #include <string.h> /* strcat, strlen, strcpy */ #include "list.h" #include "list_itr.h" struct Node{ void* m_data; Node* m_next; Node* m_prev; }; struct List { int m_magicNumber; Node m_head; Node m_tail; }; static ListItr CreateNode(void* _element); /*static size_t ListCountItemsWithRange(ListItr _begin,ListItr _end);*/ List* ListCreate() { List *l=(List*)malloc(1*sizeof(List)); if(NULL==l) { return NULL; } (l->m_head).m_next=&l->m_tail; (l->m_head).m_prev=NULL; (l->m_tail).m_prev=&l->m_head; (l->m_tail).m_next=NULL; l->m_magicNumber=123456789; return l; } void ListDestroy(List** _pList, void (*_elementDestroy)(void* _item)) { Node* temp; if(NULL==*_pList||NULL==_pList) { return; } temp=(*_pList)->m_head.m_next; while(NULL!=temp->m_next) { _elementDestroy(temp->m_data); temp=temp->m_next; free(temp->m_prev); } free(*_pList); *_pList=NULL; return; } void itemDestroy(void* _temp) { free(_temp); } ListResult ListPushHead(List* _list, void* _item) { Node *n=(Node*)malloc(1*sizeof(Node)); if(NULL==n) { return LIST_ALLOCATION_ERROR; } n->m_next=_list->m_head.m_next; _list->m_head.m_next=n; n->m_next->m_prev=n; n->m_prev=&_list->m_head; n->m_data=_item; return LIST_SUCCESS; } ListResult ListPushTail(List* _list, void* _item) { Node *n=(Node*)malloc(1*sizeof(Node)); if(NULL==n) { return LIST_ALLOCATION_ERROR; } n->m_data=_item; n->m_prev=_list->m_tail.m_prev; _list->m_tail.m_prev=n; n->m_prev->m_next=n; n->m_next=&_list->m_tail; return LIST_SUCCESS; } ListResult ListPopHead(List* _list, void** _pItem) { Node *n; if(_list->m_head.m_next==&_list->m_tail) { return LIST_NULL_ELEMENT_ERROR; } n=_list->m_head.m_next; _list->m_head.m_next=_list->m_head.m_next->m_next; _list->m_head.m_next->m_prev=&_list->m_head; n->m_next=NULL; n->m_prev=NULL; *_pItem=n->m_data; free(n); return LIST_SUCCESS; } ListResult ListPopTail(List* _list, void** _pItem) { Node *n; if(_list->m_head.m_next==&_list->m_tail) { return LIST_UNINITIALIZED_ERROR; } n=_list->m_tail.m_prev; _list->m_tail.m_prev=_list->m_tail.m_prev->m_prev; _list->m_tail.m_prev->m_next=&_list->m_tail; n->m_next=NULL; n->m_prev=NULL; *_pItem=n->m_data; free(n); return LIST_SUCCESS; } size_t ListCountItems(List* _list) { unsigned long int i=0; while(_list->m_head.m_next!=&_list->m_tail) { i++; _list->m_head.m_next=_list->m_head.m_next->m_next; } return i; } /*static size_t ListCountItemsWithRange(ListItr _begin,ListItr _end) { unsigned long int countNodes=0; while(((Node*)_begin)->m_next!=(Node*)_end) { countNodes++; (Node*)_begin=((Node*)_begin)->m_next; } return countNodes; }*/ size_t DLLForEach( List* _l, DLLElementAction _action, void* _context) { size_t size=ListCountItems(_l); int i; Node* temp=&_l->m_head; printf("\n\nsize= %ld\n",size); if(NULL!=temp->m_next) { temp=temp->m_next; } if(_l->m_magicNumber==123456789) { i=0; if(NULL== _l) { return 0; } for (i=0;i<size;i++) { if(_action(temp->m_data,i,_context)==0) { printf("i=%d\n",i); return ++i; } } return i; } return 0; } void printList(List* _l,DLLElementAction _action) { size_t i=1; Node* n=_l->m_head.m_next; while(NULL!=n) { _action(n->m_data,i,NULL); n=n->m_next; i++; } } ListItr ListItr_Begin(const List* _list) { return (ListItr)((_list->m_head).m_next); } ListItr ListItr_End(const List* _list) { return (ListItr)((&_list->m_tail)); } int ListItr_Equals(const ListItr _a, const ListItr _b) { if((ListItr)_a==(ListItr)_b) { return 1; } return 0; } ListItr ListItr_Next(ListItr _itr) { if(NULL==(ListItr)(((Node*)_itr)->m_next)) { return (ListItr)(((Node*)_itr)); } return (ListItr)(((Node*)_itr)->m_next); } ListItr ListItr_Prev(ListItr _itr) { if(NULL==(ListItr)(((Node*)_itr)->m_prev)) { return (ListItr)(((Node*)_itr)); } return (ListItr)(((Node*)_itr)->m_prev); } void* ListItr_Get(ListItr _itr) { return (ListItr)(((Node*)_itr)->m_data); } void* ListItr_Set(ListItr _itr, void* _element) { void* temp=((Node*)_itr)->m_data; ((Node*)_itr)->m_data=_element; return temp; } ListItr ListItr_InsertBefore(ListItr _itr, void* _element) { ListItr temp=CreateNode(_element); ((Node*)temp)->m_next=(Node*)_itr; ((Node*)temp)->m_prev=((Node*)_itr)->m_prev; ((Node*)_itr)->m_prev=((Node*)temp); ((Node*)_itr)->m_prev->m_next=((Node*)temp); return _itr; } static ListItr CreateNode(void* _element) { Node* temp; ListItr li; temp=(Node*)malloc(1*sizeof(Node)); if(NULL==temp) { return NULL; } temp->m_next=NULL; temp->m_prev=NULL; li=(ListItr)temp; return li; } void* ListItr_Remove(ListItr _itr) { void* saveData=((Node*)_itr)->m_data; /*empty list if((List)_itr->m_next==(List)(_itr->m_tail)) &&(List)_itr->m_prev==NULL) { return NULL; }*/ ((Node*)_itr)->m_prev->m_next=((Node*)_itr)->m_next; ((Node*)_itr)->m_next->m_prev=((Node*)_itr)->m_prev; ((Node*)_itr)->m_next=NULL; ((Node*)_itr)->m_prev=NULL; free(_itr); return saveData; } ListItr ListItr_ForEach(ListItr _begin, ListItr _end, ListActionFunction _action, void* _context) { Node* temp=(Node*)&_begin; if(NULL!=temp->m_next) { temp=temp->m_next; } /*if(NULL== _l) { return 0; } while(temp!=_end) { if(_action(temp->m_data,i,_context)==0) { return ++i; } temp=temp->next; } return 0;*/ return _begin; }
C
/* routines to do useful things with filenames */ /* the routines a written so that they may be nested to any level during */ /* a call, BUT the result of calling a routine is not guaranteed after */ /* any further, non-nested calls to the routines */ /* the routines included are: */ /* NameRoot : string -> string */ /* - removes any trailing ".xxx" suffix from */ /* filename "/a/b/f.xxx", where f has at least */ /* one character */ /* e.g. when passed "a/b/c.d" returns "a/b/c" */ /* when passed "a/.b" returns "a/.b" */ /* NameExt : string -> string */ /* - returns the extension (if any) of a filename */ /* (returns "" if no extension */ /* e.g. when passed "a/b.c" returns "c" */ /* NameFile : string -> string */ /* - removes all leading pathname components from a filename s */ /* e.g. when passed "a/b/c.d" returns "c.d" */ /* NameDir : string -> string */ /* - returns name of directory containing file s */ /* e.g. when passed "a/b/c.d" returns "a/b" */ /* when passed "/s" returns "" */ /* NamePath : string -> string */ /* - returns path of directory containing file s */ /* e.g. when passed "a/b/c.d" returns "a/b/" */ /* when passed "/s" returns "/" */ /* NameHead : string -> string */ /* - returns head directory of pathname */ /* e.g. when passed "a/b/c.d" returns "a" */ /* when passed "/s" returns "" */ /* NameTail : string -> string */ /* - returns tail of pathname */ /* e.g. when passed "a/b/c.d" returns "b/c.d" */ /* when passed "/s" returns "s" */ /* AbsPath : string -> string */ /* - returns the absolute path (i.e. one starting at / ) */ /* of given file. (actually, returns canonical path, */ /* i.e. one starting at root and containing no */ /* '..'s or '.'s). Uses system routine "getwd" and */ /* will bomb completely if this fails */ char *NameHead(char *); char *NameTail(char *); char *NameRoot(char *); char *NameExt(char *); char *NameFile(char *); char *NameDir(char *); char *NamePath(char *); char *AbsPath(char *);
C
/* @(#) Simple sorting methods. */ #include <sys/types.h> #include <stdint.h> /* Exchange two values. */ static inline void swap(long *v1, long *v2) { long tmp = *v1; *v1 = *v2; *v2 = tmp; } void selection_sort(long *val, size_t num) { size_t i = 0, j = 0, min = 0; if (num < 2) return; for (i = 0; i < num; ++i) { min = i; for (j = i + 1; j < num; ++j) { if (val[min] < val[j]) min = j; } if (min != i -1) swap(&val[min], &val[i-1]); } } void insertion_sort(long *val, size_t num) { ssize_t i = 0, j = 0; long v = 0; if (num < 2) return; for (i = 1; i < (ssize_t)num; ++i) { v = val[i]; for (j = i - 1; j >= 0 && val[j] > v; --j) val[j + 1] = val[j]; val[j] = v; } } void shell_sort(long *val, size_t num) { ssize_t i = 0, j = 0, k = 0, h = 0; long v = 0; if (num < 2) return; for (h = 1; h <= N/9; h += 3*h + 1); for (; h > 0; h /= 3) { for (i = h; i < (ssize_t)num; ++i) { v = val[i]; for (j = i - h; j >= 0 && val[j] > v; j -= h) val[j + h] = val[j]; val[j] = v; } } } void bubble_sort(long *val, size_t num) { ssize_t i = 0, j = 0; long v = 0; if (num < 2) return; for (i = (ssize_t)num - 1; i >= 1; --i) { for (j = 1; j <= i; ++j) { if (val[j-1] > val[j]) swap(&val[j-1], &val[j]); } } } /* __EOF__ */
C
#include "../includes/Interpretador.h" #define MaxInter 30 #define MAXFILEPATH 100 void printsList(GList *tabela) { TABLE temp = NULL; GList *tab = tabela; for(;tab->next;tab = tab->next) { temp = tab->data; printf("\"%s\",",getVar_name(temp)); } temp = tab->data; printf("\"%s\".\n",getVar_name(temp)); } void help(GList *tabela) { printf("Possible Commands:\n" " -variable = Function name: saves a function in a variable\n\n" " -show(variable): Prints the content of determined variable\n\n" " -toCSV(variable,char delim,FILE* filepath): Puts content a determined TABLE into a .csv file\n\n" " -load_sgr(char *users, char *businesses, char *reviews): loads all the files to the strucs.\n\n" " -clear : clear screen.\n\n" " -quit : exits program.\n\n" "Possible Functions:\n " " -businesses_started_by_letter(SGR sgr, char letter): prints all the bussinesses that start with \"letter\"\n\n" " -business_info(SGR sgr, char *business_id): Prints all info of a business with the given id\n\n" " -businesses_reviewed(SGR sgr, char *user_id)): Prints all the businesses that user_id reviewed\n\n" " -businesses_with_stars_and_city(SGR sgr, float stars, char *city): Prints all the businesses with determined number of stars in determined city\n\n" " -top_businesses_by_city(SGR sgr, int top): Prints all top businesses\n\n" " -international_users(SGR sgr): Prints all international users\n\n" " -top_businesses_with_category(SGR sgr, int top, char *category): Prints all top businesses in determined category\n\n" " -reviews_with_word(SGR sgr,char *word): Prints all top reviews with determied word\n\n" " -proj(x, cols): Makes a new table with a subset columns from x TABLE\n\n" " -fromCSV(filepath, delim)" " -filter(x, column_name, value, oper): Filter a column from TABLE x based on variable value with oper options(GT,EQ,LT)\n\n"); if(tabela) { printf("\nTables in Program:"); printsList(tabela); } } /*Test variables format for load_sgr */ int parse_variablesSGR(char* variables,char* first, char* second, char* third) { int i,size = strlen(variables),indice; for(indice = i = 0; variables[i] != ',' && variables[i] != ')' && i<size; i++,indice++) { first[indice] = variables[i]; } if(strcmp(first,"") == 0 || variables[i] == ')' || i>=size) return -1; i++; for(indice = 0;variables[i] != ',' && variables[i] != ')' && i<size; i++, indice++) { second[indice] = variables[i]; } if(strcmp(second,"") == 0 || variables[i] == ')' || i>=size) return -1; i++; for(indice = 0;variables[i] != ')' && variables[i] != ',' && i<size; i++, indice++) { third[indice] = variables[i]; } if(strcmp(third,"") == 0 || variables[i] == ',') return -1; return 0; } /* Test variables format for "Filter" */ int parse_variablesFilter(char* variables,char* first, char* second, char* third,char* fourth) { int i,size = strlen(variables),indice; for(indice = i = 0; variables[i] != ',' && variables[i] != ')' && i<size; i++,indice++) { first[indice] = variables[i]; } if(strcmp(first,"") == 0 || variables[i] == ')' || i>=size) return -1; i++; first[indice] = '\0'; for(indice = 0;variables[i] != ',' && variables[i] != ')' && i<size; i++, indice++) { second[indice] = variables[i]; } if(strcmp(second,"") == 0 || variables[i] == ')' || i>=size) return -1; second[indice] = '\0'; i++; for(indice = 0;variables[i] != ',' && variables[i] != ')' && i<size; i++, indice++) { third[indice] = variables[i]; } if(strcmp(third,"") == 0 || variables[i] == ')' || i>=size) return -1; third[indice] = '\0'; i++; for(indice = 0;variables[i] != ')' && variables[i] != ',' && i<size; i++, indice++) { fourth[indice] = variables[i]; } if(strcmp(fourth,"") == 0 || variables[i] == ',') return -1; fourth[indice] = '\0'; return 0; } /* Test variables format for query with (sgr,string) arguments */ int parse_variablesString(char* variables,char* string) { int i = 0,indice, size = strlen(variables); for(; variables[i] != ',' && i < size; i++); //ignores SGR name if( i >= size) return -1; i++; for(indice = 0; variables[i] != ',' && variables[i] != ')' && i<size; i++,indice++) { string[indice] = variables[i]; } string[indice] = '\0'; if(strcmp(string,"") == 0 || variables[i] == ',') return -1; return 0; } /*tests and parses variables for queries with (int/float,char*) formats */ int parse_variablesCharNumber(char * variables, char * first, char* number) { int i = 0,indice, size = strlen(variables); for(; variables[i] != ',' && i < size; i++); //ignores SGR name if(i >= size) return -1; i++; //So that ignores the ',' //Puts the number in a string for(indice = 0; variables[i] != ',' && i<size; i++,indice++) { number[indice] = variables[i]; } number[indice] = '\0'; if(strcmp(number,"") == 0 || i >= size) return -1; i++; //So that ignores the ',' //for the String argument for(indice = 0; i<size && variables[i] != ',' ; i++,indice++) { first[indice] = variables[i]; } first[indice] = '\0'; if(strcmp(first,"") == 0 || variables[i] == ',') return -1; return 0; } /*for businesses_started_by_letter, tests if the variables format are correct */ char parse_variablesChar(char* variables) { int i = 0; for(;variables[i] != ',';i++); char letter = variables[++i]; if(variables[i+1] != '\0') return '\0'; return letter; } /*tests if variables on fromcsv are correct */ char parse_variablesCSV(char*variables,char* filepath) { int i = 0,indice, size = strlen(variables); char delim; for(indice = 0; variables[i] != ',' && i<size; i++,indice++) { filepath[indice] = variables[i]; } filepath[indice] = '\0'; if(strcmp(filepath,"") == 0 || i >= size) return '\0'; i++; delim=variables[i]; if(i+1 != size) { printf("delim is not a char\n"); return '\0'; } return delim; } //For function proj, puts on "headers" variables the TABLE name and all headers, returns -1 if something goes wrong int GetHeaders(char* variables,char **headers) { int size = 0; int i,j; for(i = 0; size<6 && i<strlen(variables); i++,size++) { //printf("%s\n",variables); headers[size] = malloc(ID_SIZE+1); for(j = 0;variables[i] != ',' && i < strlen(variables);i++,j++) { headers[size][j] = variables[i]; } headers[size][j] = '\0'; } return size; } /*Recognizes the OPERATOR for the function filter*/ OPERATOR find_operator(char *operator) { if(strcmp(operator,"LT") == 0) { return LT; } else if(strcmp(operator,"GT") == 0) { return GT; } else return EQ; } /*Function that recognize the query that the user asked, tests the format and if its ok, makes the TABLE otherwise returns NULL and prints why*/ TABLE recognize_function(char* function,GList *tabela, SGR sgr) { char *function_name = strtok(function,"("); char *variables = strtok(NULL, "\0"); TABLE new = NULL; if(variables != NULL) { /* Query 2*/ if(strcmp(function_name,"businesses_started_by_letter") == 0) { char letter = parse_variablesChar(variables); if(letter != '0') new = businesses_started_by_letter(sgr,letter); else printf("\nBad format of function\nPlease Try again -- (businesses_started_by_letter(SGR sgr, char letter))\n\n"); } /* Query 3*/ else if(strcmp(function_name,"business_info") == 0) { char * business_id = malloc(ID_SIZE); int bool = parse_variablesString(variables,business_id); if(bool != -1) { new = businesses_info(sgr,business_id); } else printf("\nBad format of function\nPlease Try again -- (business_info(SGR sgr,char *business_id))\n\n"); free(business_id); } /* Query 4*/ else if(strcmp(function_name,"businesses_reviewed") == 0) { char * user_id = malloc(ID_SIZE); int bool = parse_variablesString(variables,user_id); if(bool != -1) { new = businesses_reviewed(sgr,user_id); } else printf("\nBad format of function\nPlease Try again -- (businesses_reviewed(SGR sgr,char *user_id))\n\n"); free(user_id); } /* Query 5*/ else if(strcmp(function_name,"businesses_with_stars_and_city") == 0) { char* city = malloc(CITY_SIZE); char* number = malloc(MaxInter); int bool = parse_variablesCharNumber(variables,city,number); if(bool != -1) { float stars = atof(number); new = businesses_with_stars_and_city(sgr,stars,city); } else printf("\nBad format of function\nPlease Try again -- (businesses_with_stars_and_city(SGR sgr,float stars,char *city))\n\n"); free(city); free(number); } /* Query 6*/ else if(strcmp(function_name,"top_businesses_by_city") == 0) { char* number = malloc(MaxInter); int bool = parse_variablesString(variables,number); if(bool != -1) { int top = atoi(number); if(top == 0) printf("Argument is not a number\n Please Try again -- (top_businesses_by_city(SGR sgr, int top))"); else new = top_businesses_by_city(sgr,top); } free(number); } /* Query 7*/ else if(strcmp(function_name,"international_users") == 0) { new = international_users(sgr); printf("Number of international users: %d",get_Columns(new)); } /* Query 8*/ else if(strcmp(function_name,"top_businesses_with_category") == 0) { char* category = malloc(MAX_CATEGORIES); char* number = malloc(MaxInter); int bool = parse_variablesCharNumber(variables,category,number); if(bool != -1) { int top = atoi(number); new = top_businesses_with_category(sgr,top,category); } else printf("\nBad format of function\nPlease Try again -- (top_businesses_with_category(SGR sgr,int top,char *category))\n\n"); free(number); free(category); } /* Query 9*/ else if(strcmp(function_name,"reviews_with_word") == 0) { char* word = malloc(WORD_SIZE); int bool = parse_variablesString(variables,word); if(bool != -1) { new = reviews_with_word(sgr,word); } else printf("\nBad format of function\nPlease Try again -- (reviews_with_word(SGR sgr,char *word))\n\n"); free(word); } /*Proj function*/ else if(strcmp(function_name, "proj") == 0) { char **headers; headers = malloc(6 * ID_SIZE); int size = GetHeaders(variables,headers); TABLE temp = look_Table(tabela,headers[0]); if(temp == NULL) printf("Table does not exist.\n"); else { int any = -1; //to Find out if at least one column exists new = initTable(size-1,get_Columns(temp)); for(int i = 1; i<size;i++) { any = projTable(temp,new,headers[i],i-1); //Makes column by column } if(any == -1) { // freeTable(new); new = NULL; printf("No Columns with given headers\n"); } } for(int i = 0; i<size; i++) free(headers[i]); free(headers); } /*filter function*/ else if(strcmp(function_name,"filter") == 0) { char * table_name = malloc(MaxInter); char * column = malloc(MaxInter); char * value = malloc(MaxInter); char * operator = malloc(MaxInter); int bool = parse_variablesFilter(variables,table_name,column,value,operator); if(bool != -1) { TABLE temp = look_Table(tabela,table_name); if(!temp) printf("table %s does not exist in this pogram\n",table_name); else { OPERATOR oper = find_operator(operator); new = filter(temp,column,value,oper); } } else printf("\nBad format of function\nPlease Try again -- filter(x, column_name, value, oper)\n\n"); free(table_name); free(column); free(value); free(operator); } /*fromCSV function */ else if(strcmp("fromCSV",function_name) == 0) { char* filepath = malloc(MAXFILEPATH); char delim = parse_variablesCSV(variables,filepath); if(delim != '\0') { new = fromFile(fopen(filepath,"r"),delim); } else printf("\nBad format of function\nPlease Try again -- fromCSV(filepath, delim)\n\n"); free(filepath); } else printf("Function does not exist\n"); } else printf("Missing arguments\n"); return new; } /*Tests the format of load_sgr function and if the filepaths really exists */ SGR Sgr_tester(char * variables,SGR sgr) { char * users = malloc(MAXFILEPATH); char * businesses = malloc(MAXFILEPATH); char * reviews = malloc(MAXFILEPATH); int bool = 1; if(variables) bool = parse_variablesSGR(variables, users,businesses,reviews); if(bool == -1) { printf("Format not right: load_sgr(char *users, char *businesses, char *reviews)\n"); } else { if(variables) { free_sgr(sgr); sgr = load_sgr(users,businesses,reviews); } //If something fails in load_sgr function we ask new filepaths until its done correctly while(!sgr) { printf("Error sgr not Loaded\n\n"); printf("Please Write users path:"); if(scanf("%s",users)); printf("Please Write businesses path:"); if(scanf("%s",businesses)); printf("Please Write reviews path:"); if(scanf("%s",reviews)); sgr = load_sgr(users,businesses,reviews); } if(fgets(users,100,stdin)); printf("SGR sucessufly loaded\n"); } free(businesses); free(users); free(reviews); return sgr; }
C
#include<stdio.h> int main(){ //we want to know how many prime numbers we have until n; int n,i,j,p,q=0; printf("enter your number please = "); scanf("%d",&n); for (i=2;i<=n;i++){ p=0; for (j=2;j<=n;j++){ if (i%j==0 && i!=j){ p=1; break; } } if (p==0) q++; } printf("tedad adad avval ta n = %d",q); return 0; }
C
#include "gotoonebot.h" #include <stdlib.h> typedef struct Et_gotoone { Joueur qui_suis_je; arbre_mnx mon_jeu; }gotoone_interne; /** * \brief initialise une IA basée sur la structure de donnée Minimax * \param qui_est_ce // l'identité de l'IA */ gotoone gotoone_init(Joueur qui_est_ce) { gotoone Le_gotoone = (gotoone) malloc(sizeof(gotoone_interne)); /* Le_gotoone est un genre de batman super fort du hex, comme Le Batman est : Le Batman, Le Gotoone se doit d'être Le Gotoone*/ Le_gotoone->qui_suis_je = qui_est_ce; Le_gotoone->mon_jeu = NULL; return Le_gotoone; } /** * \brief fais jouer une IA de type gotoonebot * \param le_gotoone // l'IA gotoonebot allant jouer * \param D // le damier que va manipuler l'IA * \param *X // @ de la coordonée X sur le plateau de jeu * \param *Y // @ de la coordonnée Y sur le plateau de jeu */ void gotoone_jouer(gotoone le_gotoone, Damier D, int *X, int *Y) { arbre_mnx memoire_mnx; le_gotoone->mon_jeu = construir_mnx(D, le_gotoone->qui_suis_je); le_gotoone->mon_jeu = noter_mnx_V2(le_gotoone->mon_jeu); memoire_mnx = le_gotoone->mon_jeu; le_gotoone->mon_jeu = obtenir_config_gagnante_mnx(le_gotoone->mon_jeu); obtenir_XY_mnx(le_gotoone->mon_jeu, X, Y); suprimer_mnx(memoire_mnx); le_gotoone->mon_jeu = NULL; //on peut pas actuellement suprimer le_gotoone car on en a besoin au tours suivants, il faudrait le free a la fin de la partie, mais a quel moment est-il déjà initialisé ? } /** * \brief libère l'espace mémoire alloué a une IA de type gotoonebot * \param G // l'IA a suprimer */ void suprimer_gotoone(gotoone G) { if(G->mon_jeu != NULL) { suprimer_mnx(G->mon_jeu); } free(G); }
C
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <assert.h> #define SCHEME_CREATE_MAIN #define SCHEME_ASSERT_STDOUT_IS_PIPED #define SCHEME_FUNCTION read_dem #include "scheme.h" FILE * pFile = NULL; long lSize; char * buffer = NULL; size_t result; struct Color { float elevation; float red; float green; float blue; float alpha; }; int num_colors = 0; struct Color * colors = NULL; void get_chars(int count) { buffer = (char*)realloc(buffer, count+1); result = fread(buffer, 1, count, pFile); buffer[count] = '\0'; } int read_dem(int argc, char ** argv, FILE * pipe_in, FILE * pipe_out, FILE * pipe_err) { char style_file[300] = "elevation_colors.csv";//src/read_dem_elevation_style_defaults.txt"; char filename[300] = ""; float water_level = 75; int set_invalid_data_to_water_level = 1; int c; while ((c = getopt(argc, argv, "f:w:c:s:")) != -1) switch (c) { case 'f': strncpy(filename, optarg, 300); break; case 's': strncpy(style_file, optarg, 300); break; case 'w': water_level = atof(optarg); break; case 'c': // 45,5.5,3.3,2.2,1.1 [semi colon separated] { break; } default: abort(); } pFile = fopen(filename, "rb"); if (pFile == NULL) { fprintf(stderr, "Usage: %s -f [file_name]\n", argv[0]); exit(1); } FILE * fpColor = fopen(style_file, "r"); if (!fpColor) { fprintf(stderr, "Error: %s -c '%s' should be a valid file\n", argv[0], optarg); exit(1); } char line[1000]; while (fgets(line, sizeof(line), fpColor) != NULL) { num_colors ++; colors = (struct Color *)realloc(colors, sizeof(struct Color)*num_colors); struct Color * color = &colors[num_colors-1]; memset(color, 0, sizeof(struct Color)); char * ptr = strtok(line, " "); if (ptr != NULL) color->elevation = atof(ptr); if (ptr != NULL) ptr = strtok(NULL, " "); color->red = (ptr != NULL) ? atof(ptr) : 1.0; if (ptr != NULL) ptr = strtok(NULL, " "); color->green = (ptr != NULL) ? atof(ptr) : 1.0; if (ptr != NULL) ptr = strtok(NULL, " "); color->blue = (ptr != NULL) ? atof(ptr) : 1.0; if (ptr != NULL) ptr = strtok(NULL, " "); color->alpha = (ptr != NULL) ? atof(ptr) : 1.0; } fclose(fpColor); fseek (pFile, 0, SEEK_END); lSize = ftell (pFile); rewind (pFile); get_chars(40+60+9); // junk get_chars(4); int lng_deg = atoi(buffer); get_chars(2); int lng_min = atoi(buffer); get_chars(7); float lng_sec = atof(buffer); get_chars(4); int lat_deg = atoi(buffer); get_chars(2); int lat_min = atoi(buffer); get_chars(7); float lat_sec = atof(buffer); //float lng = (fabs(lng_deg) + lng_min/60.0 + lng_sec/3600.0) * (lng_deg < 0 ? -1 : 1); //float lat = (fabs(lat_deg) + lat_min/60.0 + lat_sec/3600.0) * (lng_deg < 0 ? -1 : 1); //printf("%d %d %f (%f)\n", lng_deg, lng_min, lng_sec, lng); //printf("%d %d %f (%f)\n", lat_deg, lat_min, lat_sec, lat); get_chars(1+1+3+4+6+6+6+6+15*24+6+6+6); // junk get_chars(24); float sw_lng = atof(buffer) / 3600.00; get_chars(24); float sw_lat = atof(buffer) / 3600.00; get_chars(24); float nw_lng = atof(buffer) / 3600.00; get_chars(24); float nw_lat = atof(buffer) / 3600.00; get_chars(24); float ne_lng = atof(buffer) / 3600.00; get_chars(24); float ne_lat = atof(buffer) / 3600.00; get_chars(24); float se_lng = atof(buffer) / 3600.00; get_chars(24); float se_lat = atof(buffer) / 3600.00; //printf("%f %f\n", sw_lng, sw_lat); //printf("%f %f\n", nw_lng, nw_lat); //printf("%f %f\n", ne_lng, ne_lat); //printf("%f %f\n", se_lng, se_lat); get_chars(24); float min_elev = atof(buffer); get_chars(24); float max_elev = atof(buffer); //printf("%f %f\n", min_elev, max_elev); // min/max get_chars(24+6); get_chars(12); float x_res = atof(buffer); get_chars(12); float y_res = atof(buffer); get_chars(12); float z_res = atof(buffer); //printf("%f %f %f\n", x_res, y_res, z_res); // +2*6+5+ // 1+5+1+4+4+1+1+2+ // 2+2+4+4+4*2+7); // junk rewind(pFile); get_chars(1024); // Record type A int type_b_header_size = 2*6 + 2*6 + 2*24 + 24 + 2*24; int type_b_data_size = ceil((6*1201+type_b_header_size)/1024.0)*1024 - type_b_header_size; float elevation_data[1201][1201]; float lat[1201]; // col_id float lng[1201]; // col_id int col_id; for (col_id = 0 ; col_id < 1201 ; col_id++) { get_chars(6); int row = atoi(buffer); assert(row == 1); get_chars(6); int col = atoi(buffer); get_chars(6); int rn = atoi(buffer); // 1201 for canada assert(rn == 1201); get_chars(6); int n = atoi(buffer); // 1 assert(n == 1); get_chars(24); lng[col_id] = atof(buffer) / 3600.00; // long in arc seconds get_chars(24); lat[col_id] = atof(buffer) / 3600.00; // lat in arc seconds //printf("%d %f %f\n", col, lng, lat); get_chars(24); // always 0.0 get_chars(24); float min = atof(buffer); // min elevation get_chars(24); float max = atof(buffer); // max elevation int char_count = 0; int row_id = 0; while (row_id < 1201) { get_chars(6); //short alt = atoi(buffer); char_count += 6; elevation_data[col_id][row_id] = atof(buffer); if (set_invalid_data_to_water_level && elevation_data[col_id][row_id] == -32767) elevation_data[col_id][row_id] = water_level; // kbfu, applies to toronto data only, USA is invalid but it's all water anyway row_id ++; if (((row_id - 146) % 170 == 0 && row_id != 0) || row_id == 146) { get_chars(4); char_count += 4; } // junk } if (type_b_data_size > char_count) get_chars(type_b_data_size - char_count); // junk } struct Shape * shape = new_shape(); shape->gl_type = GL_POINTS; shape->vertex_arrays[0].num_dimensions = 2; get_or_add_array(shape, GL_COLOR_ARRAY); set_num_vertexs(shape, 1201*1201); for (col_id = 0 ; col_id < 1201 ; col_id++) { int row_id = 0; for (row_id = 0 ; row_id < 1201 ; row_id++) { float v[3] = { lng[col_id], lat[col_id]+(row_id*y_res/3600.00), elevation_data[col_id][row_id] }; //fprintf(stderr, "num_colors = %d\n", num_colors); struct Color * color1 = NULL; struct Color * color2 = NULL; int j; for (j = 0 ; j < num_colors - 1 ; j++) { if (colors[j].elevation <= elevation_data[col_id][row_id] && colors[j+1].elevation >= elevation_data[col_id][row_id]) { color1 = &colors[j]; color2 = &colors[j+1]; } } if (color1 != NULL && color2 != NULL) { float c[4] = { ((elevation_data[col_id][row_id] - color1->elevation) / (color2->elevation - color1->elevation) * (color2->red - color1->red)) + color1->red, ((elevation_data[col_id][row_id] - color1->elevation) / (color2->elevation - color1->elevation) * (color2->green - color1->green)) + color1->green, ((elevation_data[col_id][row_id] - color1->elevation) / (color2->elevation - color1->elevation) * (color2->blue - color1->blue)) + color1->blue, ((elevation_data[col_id][row_id] - color1->elevation) / (color2->elevation - color1->elevation) * (color2->alpha - color1->alpha)) + color1->alpha }; if (row_id > 1 && row_id < 1200) { if (elevation_data[col_id][row_id-1] > elevation_data[col_id][row_id] || elevation_data[col_id][row_id] > elevation_data[col_id][row_id+1]) for (j = 0 ; j < 3 ; j++) c[j] *= 1 - ((elevation_data[col_id][row_id-1] - elevation_data[col_id][row_id]) + (elevation_data[col_id][row_id] - elevation_data[col_id][row_id+1])) * 0.03; if (elevation_data[col_id][row_id-1] < elevation_data[col_id][row_id] || elevation_data[col_id][row_id] < elevation_data[col_id][row_id+1]) for (j = 0 ; j < 3 ; j++) c[j] *= 1 + ((elevation_data[col_id][row_id] - elevation_data[col_id][row_id-1]) + (elevation_data[col_id][row_id+1] - elevation_data[col_id][row_id])) * 0.03; } if (col_id > 1 && col_id < 1200) { if (elevation_data[col_id-1][row_id] > elevation_data[col_id][row_id] || elevation_data[col_id][row_id] > elevation_data[col_id+1][row_id]) for (j = 0 ; j < 3 ; j++) c[j] *= 1 - ((elevation_data[col_id-1][row_id] - elevation_data[col_id][row_id]) + (elevation_data[col_id][row_id] - elevation_data[col_id+1][row_id])) * 0.03; if (elevation_data[col_id-1][row_id] < elevation_data[col_id][row_id] || elevation_data[col_id][row_id] < elevation_data[col_id+1][row_id]) for (j = 0 ; j < 3 ; j++) c[j] *= 1 + ((elevation_data[col_id][row_id] - elevation_data[col_id-1][row_id]) + (elevation_data[col_id+1][row_id] - elevation_data[col_id][row_id])) * 0.03; } set_vertex(shape, 0, col_id*1201 + row_id, v); set_vertex(shape, 1, col_id*1201 + row_id, c); //append_vertex2(shape, v, c); } else { float c[4] = { 1, 0, 0, 1 }; set_vertex(shape, 0, col_id*1201 + row_id, v); set_vertex(shape, 1, col_id*1201 + row_id, c); //append_vertex2(shape, v, c); } //if (row_id > 0 && elevation_data[row_id-1] < elevation_data[col_id][row_id]) { c[0] *= 0.8; c[2] *= 0.8; } //if (row_id < 1200 && elevation_data[row_id+1] > elevation_data[col_id][row_id]) { c[0] /= 0.8; c[2] /= 0.8; } } } write_shape(pipe_out, shape); free_shape(shape); //get_chars(type_b_header_size); //printf("%s\n", buffer); //get_chars(ceil((6*1201+type_b_header_size)/1024.0)*1024 - type_b_header_size); //printf("%s------------\n", buffer); //char temp[100]; //sprintf(temp, "cp %s 030/", fn); //printf("%s\n", temp); //system(temp); free(colors); fclose(pFile); free(buffer); }
C
/* * Opdracht 0 - X * * Maarten Paauw <[email protected]> * s1094220 * INF3C */ #include <avr/io.h> #include <util/delay.h> // #include <stdlib.h> // Genereer een random nummer tussen 1 en 6. // int dobbel () { // return rand() % 6 + 1; // } void initADC () { ADMUX |= (1 << REFS0); // Zet op 5 volt. ADCSRA |= ((1 << ADPS0) | (1 << ADPS1) | (1 << ADPS2)); // Divider op 128 voor 10 bit precisie. ADCSRA |= (1 << ADEN); // AD enable. } uint16_t readADC () { ADCSRA |= (1 << ADSC); // Starten met lezen. loop_until_bit_is_clear(ADCSRA, ADSC); // Loop totdat er een waarde is. return ADC; // Geef de waarde terug. } void delay (uint16_t value) { for (uint16_t i = 0; i < value; i++) { _delay_ms(1); } } int main(void) { DDRB = (1 << PB5); PORTD = (1 << PD2); initADC(); while (1) { // PORTB = bit_is_clear(PIND, PD2) ? (1 << PB5) : 0; // PORTB = (readADC() > 512) ? (1 << PB5) : 0; uint16_t pwm = readADC(); PORTB = (1 << PB5); _delay_ms(2); PORTB = 0; delay(pwm / 100); } return 0; }
C
#include <stdlib.h> #include <stdio.h> void readFile(char *path); // Main program int main(int argc, char *argv[]) { if (argc == 1) { printf("No filename provided\n"); return 0; } else if (argc >= 2) { for (int i = 1; i < argc; ++i) { readFile(argv[i]); } return 0; } } void readFile(char *path) { FILE *file; char p = '0', line[10]; int count = 0, i = 0; if ((file = fopen(path, "r")) == NULL) { perror("my-zip: cannot open file\n"); exit(1); } while(fgets(line, 10, file) != NULL) { if(line[0] != '\n'){ for(i=0;i<9;i++){ //skip newline if(line[i] == '\n') { continue; } //break on terminating newline if(line[i] == '\0') { //write count & character to stdout fwrite(&count, sizeof(int), 1, stdout); fwrite(&p, sizeof(char), 1, stdout); break; } //initialize p if(p == '0') { p = line[0]; } //different character: change value of p and set count to 1 if(line[i] != p) { //write count & character to stdout fwrite(&count, sizeof(int), 1, stdout); fwrite(&p, sizeof(char), 1, stdout); p = line[i]; count = 1; } else { count++; } } } } fclose(file); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: iiliuk <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/12/01 15:57:49 by iiliuk #+# #+# */ /* Updated: 2017/03/09 16:55:36 by iiliuk ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" int get_next_line(int fd, char **line) { char buf[BUFF_SIZE + 1]; int bytes_read; int res; static t_lst *head; while ((bytes_read = read(fd, buf, BUFF_SIZE)) != 0) { if (bytes_read < 0 || fd < 0 || line == NULL) return (-1); buf[bytes_read] = '\0'; if ((res = check_extra(fd, buf, &head)) == 1) { *line = get_extra(fd, &head); return (1); } if (res == -1) return (-1); } if ((*line = get_extra(fd, &head)) != NULL) return (1); return (0); } char *get_extra(int fd, t_lst **head) { t_lst *elem; char *begin; char *end; char *tmp; elem = find_extra(fd, head); if (elem->left == NULL) return (NULL); if ((end = ft_strstr((char *)elem->left, "\n")) != NULL) { if (!(begin = ft_strsub((char *)elem->left, 0, (elem->left_size - ft_strlen(++end) - 2)))) return (NULL); tmp = elem->left; elem->left = (ft_strlen(end) == 0) ? NULL : (void *)ft_strdup(end); elem->left_size = ft_strlen(end) + 1; free(tmp); } else { begin = get_extra_else(elem); if (!begin) return (NULL); } return (begin); } char *get_extra_else(t_lst *elem) { char *begin; if (!(begin = ft_strdup((char *)elem->left))) return (NULL); free((*elem).left); elem->left = NULL; elem->left_size = 0; return (begin); } t_lst *find_extra(int fd, t_lst **head) { t_lst *tmp; tmp = *head; while (tmp && tmp->fd != fd) tmp = tmp->next; return (tmp); } int check_extra(int fd, char *buf, t_lst **head) { t_lst *elem; char *tmp; elem = find_extra(fd, head); if (elem == NULL) { if (!(elem = (t_lst *)ft_lstnew((void *)buf, (ft_strlen(buf) + 1)))) return (-1); elem->fd = fd; ft_list_add_back((t_list **)head, (t_list *)elem); } else { if (!(tmp = ft_strjoin((char *)elem->left, buf))) return (-1); free(elem->left); elem->left = (void *)tmp; elem->left_size = ft_strlen(tmp) + 1; } if (ft_strstr((char *)elem->left, "\n") != NULL) return (1); return (0); }
C
#include "testUtils.h" #include "stack_using_link_list.h" #include <stdlib.h> Stack *start; typedef char String[256]; void setup(){ start = create_link_list(); } void test_for_create_Stack(){ ASSERT(NULL == start->head); ASSERT(0 == start->size); } //========================Integer====================================== void test_for_push_int_type_element_into_stack(){ int element = 1; push(start, &element); ASSERT(1 == start->size); ASSERT(element == *(int*)(start->head->data)); } void test_for_remove_int_element_from_stack(){ int element = 1; push(start, &element); ASSERT(element == *(int*)(start->head->data)); pop(start); ASSERT(start->size == 0); ASSERT(NULL == start->head); } //========================float====================================== void test_for_push_float_type_element_into_stack(){ float element = 1.0f; push(start, &element); ASSERT(1 == start->size); ASSERT(element == *(float*)(start->head->data)); } void test_for_remove_float_element_from_stack(){ float element = 1.0f; push(start, &element); ASSERT(element == *(float*)(start->head->data)); pop(start); ASSERT(start->size == 0); ASSERT(NULL == start->head); } //========================double====================================== void test_for_push_double_type_element_into_stack(){ double element = 1.0; push(start, &element); ASSERT(1 == start->size); ASSERT(element == *(double*)(start->head->data)); } void test_for_remove_double_element_from_stack(){ double element = 1.0; push(start, &element); ASSERT(element == *(double*)(start->head->data)); pop(start); ASSERT(start->size == 0); ASSERT(NULL == start->head); } //========================Character====================================== void test_for_push_char_type_element_into_stack(){ char element = 'p'; push(start, &element); ASSERT(1 == start->size); ASSERT(element == *(char*)(start->head->data)); } void test_for_remove_char_element_from_stack(){ char element = 'p'; push(start, &element); ASSERT(element == *(char*)(start->head->data)); pop(start); ASSERT(start->size == 0); ASSERT(NULL == start->head); } //========================String====================================== void test_for_push_string_type_element_into_stack(){ String element = "Prajakta"; push(start, &element); ASSERT(1 == start->size); ASSERT(element == *(String*)(start->head->data)); } void test_for_remove_String_element_from_stack(){ String element = "Praju"; push(start, &element); ASSERT(element == *(String*)(start->head->data)); pop(start); ASSERT(start->size == 0); ASSERT(NULL == start->head); } void test_gives_the_top_most_element_from_the_stack_integers(){ Stack* start = create_link_list(); int element = 40; push(start, &element); ASSERT(element == *(int*)top(start)); }; typedef struct{ int emp_id,contact_no; } emp_contact; void test_push_struct_into_stack(){ emp_contact data[2] = {{1,679876543},{2,450987650}}; push(start, data); ASSERT(NULL == start->head->next); pop(start); ASSERT(0 == start->size); }
C
#include<stdio.h> #include<stdlib.h> #include<time.h> int main(){ int number; srand(time(0)); number = rand() % 100 + 1; // printf("%d", number);// int guess,nguess; nguess = 1; do { printf("enter the guess\n"); scanf("%d", &guess); if(guess<number){ printf("higher the number please\n"); }else if(guess>number){ printf("lower the number please\n"); }else{ printf("ur score is the no in %d\n", nguess); } nguess++; } while (guess!=number); return 0; }
C
/* * File: main.c * Author: Robert N. * * Created on 11 listopada 2015, 12:44 */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> /* * build: gcc -I/usr/include -L/usr/lib64 main.c -lpthread */ const int SIZE = 800; const int SIZE_2 = 5; // 800/150 = 5 const int MAX_PEOPLE_INSIDE = 10; pthread_mutex_t mutex; pthread_cond_t reader_condition, writer_condition; int writers_waiting = 0; int writers_inside = 0, readers_inside = 0; void * reader_task (void *arg); void * writer_task (void *arg); int main() { pthread_t reader_threads[SIZE]; pthread_t writer_threads[SIZE_2]; pthread_mutex_init(&mutex, NULL); pthread_cond_init(&reader_condition, NULL); pthread_cond_init(&writer_condition, NULL); int i; int j=0; for (i=0;i<SIZE;i++) { pthread_create(&reader_threads[i], NULL, reader_task, NULL); if ((i+1)%150 == 0) pthread_create(&writer_threads[j++], NULL, writer_task, NULL); } for (i=0;i<SIZE;i++) pthread_join(reader_threads[i], NULL); for (i=0;i<SIZE_2;i++) pthread_join (writer_threads[i], NULL); pthread_exit(NULL); //return (EXIT_SUCCESS); } //--------------------------------------------------------------- void * reader_task (void *arg) { pthread_mutex_lock(&mutex); while ((writers_inside + writers_waiting) > 0 || readers_inside >= MAX_PEOPLE_INSIDE) pthread_cond_wait(&reader_condition, &mutex); readers_inside++; printf("Reader has entered. Readers inside: %d\n", readers_inside); pthread_mutex_unlock(&mutex); usleep(3000); pthread_mutex_lock(&mutex); readers_inside--; printf("Reader has exited.\n"); if (writers_waiting > 0) pthread_cond_signal(&writer_condition); else pthread_cond_signal(&reader_condition); pthread_mutex_unlock(&mutex); return (NULL); } void * writer_task (void *arg) { pthread_mutex_lock(&mutex); writers_waiting++; while ((writers_inside + readers_inside) > 0) pthread_cond_wait(&writer_condition, &mutex); writers_inside++; writers_waiting--; printf("Writer has entered. Writers inside: %d\n", writers_inside); usleep(1000000); printf("Writer has exited.\n"); writers_inside--; if (writers_waiting > 0) pthread_cond_signal(&writer_condition); else pthread_cond_broadcast(&reader_condition); // broadcast = signalAll pthread_mutex_unlock(&mutex); return (NULL); }
C
#include<stdio.h> void main() { int a[5][5],i,j,n; printf("enter the matrix rangei,j"); scanf("%d%d",&i,&j); for(i=0;i<4;i++) { for(j=0;j<4;j++) { scanf("%d",&a[i][j]); } } for(i=0;i<4;i++) { printf("%d",a[i][4]); } for(i=0;i<4;i++) { printf("%d",a[i][3]); } for(j=3;j<0;j--) { printf("%d",a[1][j]); } printf("%d",a[2][0]); for(i=0;i<3;i++) { printf("%d",a[i][3]); } for(i=3;i<n-3;i--) { printf("%d",a[i][2]); } }
C
// Author: Anthony Huynh // Class: CS 344 - Operating Systems // Project: Program 3 - smallsh // Date Due: 11/20/2019 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <signal.h> #define PROMPT_REQUEST ":" #define MAX_ARGUMENTS 512 volatile sig_atomic_t foregroundOnly = 0; void showStatus(int childExitMethod) { //code from slides if (WIFEXITED(childExitMethod)) { int exitStatus = WEXITSTATUS(childExitMethod); printf("exit value %d\n", exitStatus); fflush(stdout); } else { printf("terminated by signal %d\n", childExitMethod); fflush(stdout); } } void catchSIGINT(int signo) { char* message = "terminated by signal 2\n"; write(STDOUT_FILENO, message, 23); _Exit(1); } void catchSIGTSTP(int signo) { if (!foregroundOnly) { foregroundOnly = 1; char* message = "\nEntering foreground-only mode (& is now ignored)\n"; write(STDOUT_FILENO, message, 50); } else { foregroundOnly = 0; char* message = "\nExiting foreground-only mode\n"; write(STDOUT_FILENO, message, 30); } } int main(int argc, char* argv[]) { //2049 is to allow for 2048 characters plus terminator at end char userInput[2049]; int i; char* parsedInput; char* arguments[MAX_ARGUMENTS]; int currentArgument = 0; pid_t cpid; int childExitMethod = 0; char* inputFileName = NULL; char* outputFileName = NULL; int outputFile = 0; int inputFile = 0; int result = 0; int foregroundProcess = 1; struct sigaction SIGINT_action = { 0 }; struct sigaction SIGTSTP_action = { 0 }; //actions for catching SIGINT and SIGTSTP //obtained from slides SIGINT_action.sa_handler = SIG_IGN; sigfillset(&SIGINT_action.sa_mask); SIGINT_action.sa_flags = 0; sigaction(SIGINT, &SIGINT_action, NULL); SIGTSTP_action.sa_handler = catchSIGTSTP; sigfillset(&SIGTSTP_action.sa_mask); SIGTSTP_action.sa_flags = 0; sigaction(SIGTSTP, &SIGTSTP_action, NULL); for (i = 0; i < MAX_ARGUMENTS; i++) { arguments[i] = NULL; } while (1) { foregroundProcess = 1; //prompt and flushes printf("%s ", PROMPT_REQUEST); fflush(stdout); //sets userInput to all \0 before reading in memset(userInput, '\0', sizeof(userInput)); fgets(userInput, sizeof(userInput), stdin); //will remove trailing \n at end of user input and replace with \0 userInput[strlen(userInput) - 1] = '\0'; //parsing user input, if no space, null pointer will be returned parsedInput = strtok(userInput, " "); //will loop through each space separated text and place in arguments while (parsedInput != NULL) { //if < was detected, indicating an input file will be next if (strcmp(parsedInput, "<") == 0) { parsedInput = strtok(NULL, " "); inputFileName = malloc(100 * sizeof(char)); strcpy(inputFileName, parsedInput); parsedInput = strtok(NULL, " "); } //if > was detected, indicated an output file will be next else if (strcmp(parsedInput, ">") == 0) { parsedInput = strtok(NULL, " "); outputFileName = malloc(100 * sizeof(char)); strcpy(outputFileName, parsedInput); parsedInput = strtok(NULL, " "); } //all other arguments else { arguments[currentArgument] = malloc(100 * sizeof(char)); strcpy(arguments[currentArgument], parsedInput); currentArgument++; parsedInput = strtok(NULL, " "); } //will change any instances of $$ into process id as text is being parsed char* p; p = strstr(arguments[currentArgument - 1], "$$"); if (p) { pid_t pid = getpid(); char* mypid = (char *)malloc(sizeof(int)); sprintf(mypid, "%d", pid); strcpy(p, mypid); free(mypid); } } //if last argument was a &, will turn process into background process //will also free last argument and set to null //will only check for & if there is at least one argument if (currentArgument != 0) { if (strcmp(arguments[currentArgument - 1], "&") == 0) { if (!foregroundOnly) { foregroundProcess = 0; } free(arguments[currentArgument - 1]); arguments[currentArgument - 1] = NULL; currentArgument--; } } //if there were no arguments or the first argument started with #, will print line if (arguments[0] == NULL || arguments[0][0] == '#') { } //will exit upon request, also freeing any memory that was malloc'd else if (strcmp(arguments[0], "exit") == 0) { for (i = 0; i < currentArgument; i++) { free(arguments[i]); } free(outputFileName); free(inputFileName); exit(0); } //to change directories, if no directory is stated, will go to home else if (strcmp(arguments[0], "cd") == 0) { if (arguments[1] == NULL) { chdir(getenv("HOME")); } else { chdir(arguments[1]); } } //prints either exit status or the terminating signal of the last foreground process else if (strcmp(arguments[0], "status") == 0) { showStatus(childExitMethod); } //all other commands that are not built in else { cpid = fork(); switch (cpid) { //if something went wrong during fork case -1: perror("Hull breach!"); childExitMethod = 1; break; //if the process is the child process case 0: //child process that is running in foreground will terminate if sigint is received if (foregroundProcess) { SIGINT_action.sa_handler = catchSIGINT; sigaction(SIGINT, &SIGINT_action, NULL); } //if input file is specified, opens named file if (inputFileName != NULL) { inputFile = open(inputFileName, O_RDONLY); if (inputFile == -1) { printf("cannot open %s for input\n", inputFileName); fflush(stdout); _Exit(1); } //will redirect stdin to inputFile result = dup2(inputFile, 0); if (result == -1) { perror("dup2 error"); _Exit(1); } close(inputFile); } //if output file is specified, opens named file if (outputFileName != NULL) { outputFile = open(outputFileName, O_WRONLY | O_TRUNC | O_CREAT , 0700); if (outputFile == -1) { perror("open output file error"); _Exit(1); } //will redirect stdout to outputFile result = dup2(outputFile, 1); if (result == -1) { perror("dup2 error"); _Exit(1); } close(outputFile); } //will redirect input/output files to /dev/null if not specified and if background process if (!foregroundProcess) { if (inputFileName == NULL) { inputFile = open("/dev/null", O_RDONLY); if (inputFile == -1) { perror("cannot open /dev/null for reading"); _Exit(1); } result = dup2(inputFile, 0); if (result == -1) { perror("dup2 error"); _Exit(1); } close(inputFile); } if (outputFileName == NULL) { outputFile = open("/dev/null", O_WRONLY | O_TRUNC | O_CREAT, 0700); if (outputFile == -1) { perror("cannot open /dev/null for writing"); _Exit(1); } result = dup2(outputFile, 1); if (result == -1) { perror("dup2 error"); _Exit(1); } close(outputFile); } } //if execvp fails, will return a negative one and alert the user if (execvp(arguments[0], arguments) < 0) { printf("%s: no such file or directory\n", arguments[0]); fflush(stdout); _Exit(1); } break; //if the process is the parent default: if (foregroundProcess) { waitpid(cpid, &childExitMethod, 0); if (!WIFEXITED(childExitMethod)) { showStatus(childExitMethod); } break; } else { printf("background pid is %d\n", cpid); fflush(stdout); } } } //frees all memory malloc'd and sets currentArguments to 0 before prompting for more input for (i = 0; i < currentArgument; i++) { free(arguments[i]); arguments[i] = NULL; } currentArgument = 0; free(outputFileName); free(inputFileName); inputFileName = NULL; outputFileName = NULL; //will check if any children have finished before new prompt cpid = waitpid(-1, &childExitMethod, WNOHANG); while (cpid > 0) { printf("background pid %d is done: ", cpid); showStatus(childExitMethod); cpid = waitpid(-1, &childExitMethod, WNOHANG); } } return 0; }
C
/* pcspkr - listen to pcm sound over the internal pc speaker Written in 2014 by <Ahmet Inan> <[email protected]> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include <signal.h> #include <sys/io.h> #include <stdlib.h> #include <unistd.h> #include <sched.h> void disable_speaker_and_counter() { outb(inb(0x61) & 12, 0x61); } void enable_speaker_and_counter() { outb((inb(0x61) & 12) | 3, 0x61); } void reset_counter(unsigned char c) { outb(c, 0x42); } void move_speaker(int v) { static int init; static unsigned char settings; if (!init) { init = 1; settings = (inb(0x61) & 12) | 1; } outb(settings | (v << 1), 0x61); } void prepare_hardware() { disable_speaker_and_counter(); outb(160, 0x43); // 16bit counter, mode 0, MSB only, timer 2 reset_counter(0); outb(144, 0x43); // 16bit counter, mode 0, LSB only, timer 2 reset_counter(0); } void cleanup(int signum) { (void)signum; disable_speaker_and_counter(); exit(1); } void install_signal_handlers() { signal(SIGTERM, cleanup); signal(SIGINT, cleanup); } void set_io_permissions() { ioperm(0x42, 2, 1); ioperm(0x61, 1, 1); } void set_realtime_scheduling() { const int policy = SCHED_FIFO; struct sched_param param; sched_getparam(0, &param); param.sched_priority = sched_get_priority_max(policy); sched_setscheduler(0, policy, &param); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_itoa.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pilespin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/11/12 18:58:38 by pilespin #+# #+# */ /* Updated: 2015/05/03 15:11:57 by pilespin ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static char *ft_retourne(char *src, int lon) { char *dest; int i; int j; dest = (char *)memalloc_or_die(lon + 1); j = lon; i = 0; dest[lon] = '\0'; while (i < lon) { dest[i] = src[j - 1]; i++; j--; } return (dest); } static int ft_compte_la_longueur(int c) { int i; int lon; i = 1; if (c < 0) { i++; c = -c; } lon = c; while (lon >= 10) { lon = lon / 10; i++; } return (i); } char *ft_itoa(int c) { int lon; char *str; char *dst; int cc; int i; if (c == -2147483648) return (ft_strdup("-2147483648")); cc = c; lon = ft_compte_la_longueur(c); str = (char *)memalloc_or_die(lon + 1); if (c < 0) c = -c; i = 0; while (i < lon) { str[i] = (c % 10) + 48; c = c / 10; i++; } if (cc < 0) str[i - 1] = '-'; dst = ft_retourne(str, lon); free(str); return (dst); }
C
/** * Malloc Lab * CS 241 - Spring 2019 */ #pragma once typedef struct _alloc_stats_t { unsigned long long max_heap_used; unsigned long memory_uses; unsigned long long memory_heap_sum; } alloc_stats_t; #ifdef CONTEST_MODE // timeout in contest modes in seconds #define TIMER_TIMEOUT 30 // Memory Limit for contest mode #define MEMORY_LIMIT ((1024L * 1024L * 1024L * 2L) + (1024L * 1024L * 512L)) #else // timeout in replace mode in seconds #define TIMER_TIMEOUT 120000 // Memory Limit for contest mode #define MEMORY_LIMIT ((1024L * 1024L * 1024L * 12L) + (1024L * 1024L * 512L)) #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_args.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hrossouw <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/09/17 13:11:22 by hrossouw #+# #+# */ /* Updated: 2018/09/18 15:43:28 by hrossouw ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/push_swap.h" int create_list(char **str, t_hold *node) { int i; int size; t_stack *ret; i = 0; size = 0; ret = node->a; while (str[size]) size++; while (i < (size - (node->debug + node->colour + node->supcolour + node->vis + 1))) { ret->next = (t_stack *)malloc(sizeof(t_stack)); ret = ret->next; ret->data = 0; ret->pos = 0; i++; } ret->next = NULL; node->b = NULL; return (1); } int error_check(t_hold *node, int checker) { t_stack *temp; t_stack *list; temp = node->a; if (checker == 1) return (1); while (temp != NULL) { list = temp; list = list->next; while (list != NULL) { if (list->data == temp->data) { ERROR; return (0); } list = list->next; } temp = temp->next; } return (1); } // populates arguments into a linked list while checking for extra command flags int create_stacks(char **str, t_hold *node, int checker) { int i; int dx; t_stack *ret; create_list(str, node); ret = node->a; i = 0; while (str[i]) { dx = 0; while (ft_isspace(str[i][dx]) == 1) dx++; if (!(str[i][dx] == '-' && str[i][dx + 1] == 'v') && !(str[i][dx] == '-' && str[i][dx + 1] == 'c')) { ret->data = atoi(str[i]); ret = ret->next; if (ret == NULL) return (error_check(node, checker)); } i++; } ret->next = NULL; return (error_check(node, checker)); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_put_pixel_to_image.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: erobert <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2013/12/17 15:30:17 by erobert #+# #+# */ /* Updated: 2015/01/20 19:09:39 by erobert ### ########.fr */ /* */ /* ************************************************************************** */ #include <mlx.h> #include "fdf.h" static unsigned int ft_swap_endian(unsigned int in) { unsigned int out; out = (in << 24); out |= ((in << 8) & 0x00ff0000); out |= ((in >> 8) & 0x0000ff00); out |= (in >> 24); return (out); } static unsigned int ft_true_color(t_data *d, int rgb) { unsigned int color; color = mlx_get_color_value(d->mlx_ptr, rgb); if (d->img.endian == 1) color = ft_swap_endian(color); return (color); } void ft_put_pixel_to_image(t_data *d, int x, int y, int c) { unsigned int color; int i; int bpp; if (x > d->size[0] || y > d->size[1] || x < 0 || y < 0) return ; color = ft_true_color(d, c); bpp = d->img.bpp / 8; i = y * d->img.line + x * bpp; ft_memcpy(d->img.data + i, &color, bpp); }
C
// Write a C program to find the area of parallelogram #include <stdio.h> int main() { float b,h,area; printf("Enter base & height of parallelogram\n"); scanf("%f %f",&b,&h); area=b*h; printf("Area of the parallelogram is %f",area); } /*Output: Enter base & height of parallelogram 4 5.5 Area of the parallelogram is 22.000000*/
C
#include <stdlib.h> /* exit func */ #include <stdio.h> /* printf func */ #include <fcntl.h> /* open syscall */ #include <getopt.h> /* args utility */ #include <sys/ioctl.h> /* ioctl syscall*/ #include <unistd.h> /* close syscall */ #include <string.h> #include <stdint.h> #include <ctype.h> #include "ime-ioctl.h" #include "intel_pmc_events.h" const char * device = "/dev/ime/pmc"; int exit_ = 0; //pmc mask, cpu mask, event mask, start values, pebs mask, user mask, kernel mask, reset value //n: set pmc, i: interactive, o: print buffer on file #define ARGS "p:c:e:s:b:u:k:d:m:r:niof" #define MAX_LEN 256 typedef struct{ int pmc_id[MAX_ID_PMC]; int event_id[MAX_ID_PMC]; int cpu_id[MAX_ID_PMC][MAX_ID_CPU]; uint64_t start_value[MAX_ID_PMC]; uint64_t reset_value[MAX_ID_PMC]; int enable_PEBS[MAX_ID_PMC][MAX_ID_CPU]; int user[MAX_ID_PMC][MAX_ID_CPU]; int kernel[MAX_ID_PMC][MAX_ID_CPU]; int buffer_module_length; int buffer_pebs_length; }configuration_t; configuration_t current_config; char binary[16][5] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; char* convert_binary(char c){ char* res; if(c >= '0' && c <= '9') return binary[atoi(&c)]; if(c >= 'A' && c <= 'F') return binary[c-'A'+10]; return NULL; } int convert_decimal(char c){ int res; if(c >= '0' && c <= '9') return atoi(&c); if(c >= 'A' && c <= 'F') return (c-'A'+10); return -1; } int check_len(char* input){ int len = strnlen(input, MAX_LEN); if(len != MAX_ID_PMC){ return 0; } return 1; } int int_from_stdin() { char buffer[12]; int i = -1; if (fgets(buffer, sizeof(buffer), stdin)) { sscanf(buffer, "%d", &i); } return i; }// int_from_stdin int read_buffer(int fd){ int err = 0; unsigned long size_buffer, i; struct buffer_struct* args; if ((err = ioctl(fd, IME_SIZE_BUFFER, &size_buffer)) < 0){ printf("IOCTL: IME_SIZE_BUFFER failed\n"); return err; } printf("IOCTL: IME_SIZE_BUFFER success\n"); if(!size_buffer) return 0; args = (struct buffer_struct*) malloc (sizeof(struct buffer_struct)*size_buffer); if ((err = ioctl(fd, IME_READ_BUFFER, args)) < 0){ printf("IOCTL: IME_READ_BUFFER failed\n"); return err; } printf("IOCTL: IME_READ_BUFFER success\n"); FILE *f = fopen("file.txt", "w"); if (f == NULL) { printf("Error opening file!\n"); exit(1); } for(i = 0; i < size_buffer; i++){ fprintf(f, "0x%lx\t%d\n", args[i].address << 12, args[i].times); printf("0x%lx\t%d\n", args[i].address << 12, args[i].times); } fclose(f); free(args); return err; } int set_reset_pmc(int fd, int on){ int err = 0; struct sampling_spec* output = (struct sampling_spec*) malloc (sizeof(struct sampling_spec)); int i, k; for (i = 0; i < MAX_ID_PMC; i++){ if(current_config.pmc_id[i] == 0) continue; output->pmc_id = i; output->event_id = current_config.event_id[i]; output->buffer_module_length = current_config.buffer_module_length; output->buffer_pebs_length = current_config.buffer_pebs_length; for(k = 0; k < MAX_ID_CPU; k++){ output->enable_PEBS[k] = current_config.enable_PEBS[i][k]; } output->start_value = current_config.start_value[i]; output->reset_value = current_config.reset_value[i]; for(k = 0; k < MAX_ID_CPU; k++){ output->cpu_id[k] = current_config.cpu_id[i][k]; } for(k = 0; k < MAX_ID_CPU; k++){ output->user[k] = current_config.user[i][k]; } for(k = 0; k < MAX_ID_CPU; k++){ output->kernel[k] = current_config.kernel[i][k]; } if(on == 1){ if ((err = ioctl(fd, IME_SETUP_PMC, output)) < 0){ printf("IOCTL: IME_SETUP_PMC failed\n"); return err; } printf("IOCTL: IME_SETUP_PMC success\n"); } else{ if ((err = ioctl(fd, IME_RESET_PMC, output)) < 0){ printf("IOCTL: IME_RESET_PMC failed\n"); return err; } printf("IOCTL: IME_RESET_PMC success\n"); } } free(output); return err; } int ioctl_cmd(int fd) { printf("\n%d: EXIT\n", 0); printf("%d: LIST_EVENT\n", 1); printf("%d: READ_CONFIGURATION\n", 2); printf("%d: IME_SETUP_PMC\n", _IOC_NR(IME_SETUP_PMC)); printf("%d: IME_PROFILER_ON\n", _IOC_NR(IME_PROFILER_ON)); printf("%d: IME_PROFILER_OFF\n", _IOC_NR(IME_PROFILER_OFF)); printf("%d: IME_RESET_PMC\n", _IOC_NR(IME_RESET_PMC)); printf("%d: IME_PMC_STATS\n", _IOC_NR(IME_PMC_STATS)); printf("%d: IME_READ_BUFFER\n", _IOC_NR(IME_READ_BUFFER)); printf("%d: IME_RESET_BUFFER\n", _IOC_NR(IME_RESET_BUFFER)); printf("Put cmd >> "); int cmd = int_from_stdin(); int err = 0; int var = 0; unsigned long uvar = -1; if(cmd == 0){ exit_ = 1; return err; } if(cmd == 1){ printf("%d: EVT_INSTRUCTIONS_RETIRED\n", EVT_INSTRUCTIONS_RETIRED); printf("%d: EVT_UNHALTED_CORE_CYCLES\n", EVT_UNHALTED_CORE_CYCLES); printf("%d: EVT_UNHALTED_REFERENCE_CYCLES\n", EVT_UNHALTED_REFERENCE_CYCLES); printf("%d: EVT_BR_INST_RETIRED_ALL_BRANCHES\n", EVT_BR_INST_RETIRED_ALL_BRANCHES); printf("%d: EVT_MEM_INST_RETIRED_ALL_LOADS\n", EVT_MEM_INST_RETIRED_ALL_LOADS); printf("%d: EVT_MEM_INST_RETIRED_ALL_STORES\n", EVT_MEM_INST_RETIRED_ALL_STORES); printf("%d: EVT_MEM_LOAD_RETIRED_L3_HIT\n", EVT_MEM_LOAD_RETIRED_L3_HIT); return err; } if(cmd == 2){ int i; for (i = 0; i < MAX_ID_PMC; i++){ if(current_config.pmc_id[i] == 1){ printf("PMC%d | EVENT:%d", i, current_config.event_id[i]); int k; printf(" | CPU MASK: "); for(k = 0; k < MAX_ID_CPU; k++){ printf("%d", current_config.cpu_id[i][k]); } printf(" | PEBS MASK: "); for(k = 0; k < MAX_ID_CPU; k++){ printf("%d", current_config.enable_PEBS[i][k]); } printf(" | USER MASK: "); for(k = 0; k < MAX_ID_CPU; k++){ printf("%d", current_config.user[i][k]); } printf(" | KERNEL MASK: "); for(k = 0; k < MAX_ID_CPU; k++){ printf("%d", current_config.kernel[i][k]); } printf(" | START VALUE: %lx", current_config.start_value[i]); printf(" | RESET VALUE: %lx", current_config.reset_value[i]); printf(" | PEBS DIM: %d", current_config.buffer_pebs_length); printf(" | MODULE DIM: %d\n", current_config.buffer_module_length); } } return 0; } if(cmd == _IOC_NR(IME_PROFILER_ON)) { ioctl(fd, IME_PROFILER_ON); printf("IOCTL: IME_PROFILER_ON success\n"); return 0; } if(cmd == _IOC_NR(IME_PROFILER_OFF)) { ioctl(fd, IME_PROFILER_OFF); printf("IOCTL: IME_PROFILER_OFF success\n"); return 0; } if(cmd == _IOC_NR(IME_SETUP_PMC)){ return set_reset_pmc(fd, 1); } if(cmd == _IOC_NR(IME_RESET_PMC)){ return set_reset_pmc(fd, 0); } if(cmd == _IOC_NR(IME_PMC_STATS)){ int i, k; for (i = 0; i < MAX_ID_PMC; i++){ if(current_config.pmc_id[i] == 0) continue; struct pmc_stats* args = (struct pmc_stats*) malloc (sizeof(struct pmc_stats)); args->pmc_id = i; if ((err = ioctl(fd, IME_PMC_STATS, args)) < 0){ printf("IOCTL: IME_PMC_STATS failed\n"); return err; } for(k = 0; k < MAX_ID_CPU; k++){ printf("The resulting value of PMC%d on CPU%d is: %lx\n",i, k, args->percpu_value[k]); } free(args); } return 0; } if(cmd == _IOC_NR(IME_READ_BUFFER)){ return read_buffer(fd); } if(cmd == _IOC_NR(IME_RESET_BUFFER)){ if ((err = ioctl(fd, IME_RESET_BUFFER)) < 0){ printf("IOCTL: IME_RESET_BUFFER failed\n"); return err; } printf("IOCTL: IME_RESET_BUFFER success\n"); return 0; } return err; }// ioctl_cmd int main(int argc, char **argv) { /* nothing to do */ if (argc < 2) goto open_device; int fd, option, err, val; char path[128]; int len, i, k; uint64_t sval; char delim[] = ","; char *ptr; fd = open(device, 0666); if (fd < 0) { printf("Error, cannot open %s\n", device); return -1; } err = 0; option = getopt(argc, argv, ARGS); for(i = 0; i < MAX_ID_PMC; i++){ current_config.start_value[i] = -1; current_config.reset_value[i] = -1; } current_config.buffer_pebs_length = 0; current_config.buffer_module_length = 0; while(!err && option != -1) { switch(option) { case 'p': if(!check_len(optarg)) break; for(i = 0; i < MAX_ID_PMC; i++){ if(optarg[i] == '1') current_config.pmc_id[i] = 1; else current_config.pmc_id[i] = 0; } ioctl(fd, IME_RESET_BUFFER); break; case 'c': if(!check_len(optarg)) break; for(i = 0; i < MAX_ID_PMC; i++){ char c = toupper(optarg[i]); if(current_config.pmc_id[i] == 1 && convert_binary(c) != NULL){ char* cpu = convert_binary(c); for(k = 0; k < MAX_ID_CPU; k++){ if(cpu[MAX_ID_CPU-1-k] == '1') current_config.cpu_id[i][k] = 1; else current_config.cpu_id[i][k] = 0; } } } break; case 'b': if(!check_len(optarg)) break; for(i = 0; i < MAX_ID_PMC; i++){ char c = toupper(optarg[i]); if(current_config.pmc_id[i] == 1 && convert_binary(c) != NULL){ char* cpu = convert_binary(c); for(k = 0; k < MAX_ID_CPU; k++){ if(cpu[MAX_ID_CPU-1-k] == '1' && current_config.cpu_id[i][k] == 1) current_config.enable_PEBS[i][k] = 1; else current_config.enable_PEBS[i][k] = 0; } } } break; case 'e': len = strnlen(optarg, MAX_LEN); if(len != (MAX_ID_PMC*2)) break; for(i = 0; i < (MAX_ID_PMC*2); i = i+2){ char c1 = toupper(optarg[i]); char c2 = toupper(optarg[i+1]); if(current_config.pmc_id[i/2] == 0) continue; if((convert_decimal(c1) == -1) || (convert_decimal(c2) == -1)){ current_config.pmc_id[i/2] = 0; continue; } val = convert_decimal(c1)*16 + convert_decimal(c2); if(val < 0 || val >= MAX_ID_EVENT){ current_config.pmc_id[i/2] = 0; continue; } current_config.event_id[i/2] = val; } break; case 's': ptr = strtok(optarg, delim); i = 0; while(ptr != NULL && i < MAX_ID_PMC){ sscanf(ptr, "%lx", &sval); current_config.start_value[i] = sval; ptr = strtok(NULL, delim); ++i; } break; case 'r': ptr = strtok(optarg, delim); i = 0; while(ptr != NULL && i < MAX_ID_PMC){ sscanf(ptr, "%lx", &sval); current_config.reset_value[i] = sval; ptr = strtok(NULL, delim); ++i; } break; case 'u': if(!check_len(optarg)) break; for(i = 0; i < MAX_ID_PMC; i++){ char c = toupper(optarg[i]); if(current_config.pmc_id[i] == 1 && convert_binary(c) != NULL){ char* cpu = convert_binary(c); for(k = 0; k < MAX_ID_CPU; k++){ if(cpu[MAX_ID_CPU-1-k] == '1' && current_config.cpu_id[i][k] == 1) current_config.user[i][k] = 1; else current_config.user[i][k] = 0; } } } break; case 'k': if(!check_len(optarg)) break; for(i = 0; i < MAX_ID_PMC; i++){ char c = toupper(optarg[i]); if(current_config.pmc_id[i] == 1 && convert_binary(c) != NULL){ char* cpu = convert_binary(c); for(k = 0; k < MAX_ID_CPU; k++){ if(cpu[MAX_ID_CPU-1-k] == '1' && current_config.cpu_id[i][k] == 1) current_config.kernel[i][k] = 1; else current_config.kernel[i][k] = 0; } } } break; case 'n': set_reset_pmc(fd, 1); break; case 'f': set_reset_pmc(fd, 0); break; case 'o': read_buffer(fd); break; case 'd': val = atoi(optarg); current_config.buffer_pebs_length = val; break; case 'm': val = atoi(optarg); current_config.buffer_module_length = val; break; case 'i': goto interactive; default: break; } /* get next arg */ option = getopt(argc, argv, ARGS); } goto no_interactive; open_device: fd = open(device, 0666); if (fd < 0) { printf("Error, cannot open %s\n", device); return -1; } interactive: while (1) { if (ioctl_cmd(fd)) printf("IOCTL ERROR\n"); if(exit_ == 1) break; } no_interactive: close(fd); return 0; }// main
C
#include <stdio.h> int m, n; //m is length of x sequence, n is length of y sequence char x[110]; char y[110]; float gap_p, mis_p; float opt[110][110]; char x_r[110], y_r[110] = { 0, }; //x_r is optimal alignment of x sequence, y_r is optimal alignment of y sequence. typedef struct { int r; int c; }visited; visited v[200]; void sequencealignment() { int i, j; float penalty; v[0].r=m; v[0].c=n; int k=0; for (int w = 0; w <= m+1; w++) opt[w][n+1] = 10000; for (int k = 0; k <= n+1; k++)opt[m+1][k] = 10000; for (i = m; i >= 0; i--) { for (j = n; j >= 0; j--) { if (i == m) //initialize opt[i][j] = gap_p * (n - j); else if (j == n) //initialize opt[i][j] = gap_p * (m - i); else { //The order of inputted is opt[i+1][j+1], opt[i+1][j], and opt[i][j+1]. if (x[i] == y[j]) penalty = 0; else penalty = mis_p; if (opt[i + 1][j + 1] + penalty < opt[i + 1][j] + gap_p) { if (opt[i + 1][j + 1] + penalty < opt[i][j + 1] + gap_p) { //When opt[i+1][j+1]+penalty is the smallest opt[i][j] = opt[i + 1][j + 1] + penalty; if(v[k].c==j+1&&v[k].r==i+1){ v[++k].r=i-1; v[k].c=j-1; x_r[k]=x[i]; y_r[k]=y[j]; } } else{ //When opt[i][j+1]+gap_p is the smallest opt[i][j] = opt[i][j + 1] + gap_p; if(v[k].c==j+1&&v[k].r==i){ v[++k].r=i; v[k].c=j-1; x_r[k]='-'; y_r[k]=y[j]; } } } //end of if(opt[i+1][j+1]+penalty<opt[i+1][j]+gap_p) else { if (opt[i + 1][j] + gap_p < opt[i][j + 1] + gap_p) { //When opt[i+1][j]+gap_p is the smallest opt[i][j] = opt[i + 1][j] + gap_p; if(v[k].c==j&&v[k].r==i+1){ v[++k].r=i-1; v[k].c=j; x_r[k]=x[i]; y_r[k]='-'; } } else { //When opt[i][j+1]+gap_p is the smallest opt[i][j] = opt[i][j + 1] + gap_p; if(opt[i][j+1]==opt[i+1][j]){ if((v[k].c==j&&v[k].r==i+1)||(v[k].c==j+1&&v[k].r==i)){ v[++k].r=i; v[k].c=j-1; x_r[k]='-'; y_r[k]=y[j]; v[++k].r=i-1; v[k].c=j; x_r[k]=x[i]; y_r[k]='-'; } } else{ if(v[k].c==j+1&&v[k].r==i){ v[++k].r=i; v[k].c=j-1; x_r[k]='-'; y_r[k]=y[j]; } } } } //end of else } //end of else } //end of for(j=n;j>=0;j--) } //end of for(i=m;i>=0;i--) printf("%.1f ", opt[0][0]); } int main() { scanf("%d %d %s %s %f %f", &m, &n, x, y, &gap_p, &mis_p); sequencealignment(); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main () { int s=0,aux,trocas,cont,l,n,trem[51]; scanf("%d",&n); while (n>0){ scanf("%d",&l); for(cont = 0;cont<l;cont++){ scanf("%d",&trem[cont]); } trocas = 1; while (trocas > 0){ trocas = 0; for (cont = 0;cont<l-1;cont++){ if (trem[cont]>trem[cont+1]){ aux = trem[cont]; trem[cont] = trem[cont+1]; trem[cont+1] = aux; trocas = 1; s = s+1; } } } printf("Optimal train swapping takes %d swaps.\n",s); s = 0; n=n-1; } return 0; }
C
/* * EEPROM.c * * Created: 22-12-2020 23:42:49 * Author: ahmed */ #include "EEPROM.h" void EEPROM_write(u16 Address, u8 Data) { while(EECR & (1<<EEWE)); EEAR = Address; EEDR = Data; EECR |= (1<<EEMWE); EECR |= (1<<EEWE); } u8 EEPROM_read(u16 Address) { while(EECR & (1<<EEWE)); EEAR = Address; EECR |= (1<<EERE); return EEDR; }
C
#include <stdio.h> #include <math.h> int main() { // https://www.mathscareers.org.uk/article/calculating-pi/ // https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80#Notes long double pi; long double num = 0.0; long double sign = 1.0; long long n; int i; // ask for number of reps printf("\nEnter the number of terms to determine approximation: "); scanf("%lli", &n); for(i = 0; i < n; i++) { num += sign / (2.0F * i + 1.0F); sign = -sign; } pi = num * 4.0L; printf("\nApproximation of pi ~ %.62Lf\n\n", pi); return 0; }
C
/******************************************************************************* * * * FILE: testScanner.c * * * * PURPOSE: Driver program to test scanner.c * * * * EXTERNAL VARIABLES: * * Source: scanner.c ( Declared in scanner.h ) * * Name Type I/O Description * * ---- ---- --- ----------- * * lineNumber int I Current line in source file * * * * DEVELOPMENT HISTORY * * Date Author Description * * 04/08/2005 W.W.A Oliver NoN * * * ********************************************************************************/ #include <stdio.h> #include <stdlib.h> #include "token.h" #include "error.h" #include "scanner.h" /*define constants*/ #define true 1 #define false 0 char c; /* function prototypes */ static void common(Token_t *sym); static void expr(Token_t *sym); static void cheack(Token_t *sym, TokenType_t expected) /*method for cheacking the for the symbol*/ { if(sym->type != expected) { print_error(&expected,&sym->type,&lineNumber); /*parse on whearther it is missing or expected*/ printf("Compiling teminated\n"); exit(EXIT_FAILURE); } else { getSym(sym); } } static char compare(Token_t *sym, TokenType_t expected) { if(sym->type == expected) { getSym(sym); return true; } else return false; } static char relation (Token_t *sym) { if(!compare(sym,SM_EQUALS)) if(!compare(sym,SM_NOT_EQUAL)) if(!compare(sym,SM_SMALLER)) if(!compare(sym,SM_LARGER)) if(!compare(sym,SM_E_SMALLER)) if(!compare(sym,SM_E_LARGER)) return false; return true; } static char mul_op (Token_t *sym) { if(!compare(sym,SM_MULTI)) if(!compare(sym,SM_DIVIDE)) if(!compare(sym,SM_AND)) { return false; } return true; } static char add_op (Token_t *sym) { if(!compare(sym,SM_PLUS)) if(!compare(sym,SM_SUB)) if(!compare(sym,SM_OR)) { return false; } return true; } static char factor (Token_t *sym) { if(!compare(sym,SM_NUMBER)) if(compare(sym,SM_ID)) { if(compare(sym,SM_LT_S_BRK)) { expr(sym); cheack(sym,SM_RT_S_BRK); } }else if(compare(sym,SM_LT_R_BRK)) { expr(sym); cheack(sym,SM_RT_R_BRK); }else if(!compare(sym,SM_TRUE)) if(!compare(sym,SM_FALSE)) if(compare(sym,SM_NOT)) { if(!factor(sym)) { print_cerror("Factor composition\n",&sym->type,&lineNumber); exit(EXIT_FAILURE); } } else { return false; } return true; } static char term(Token_t *sym) { if(factor(sym)) { while(mul_op(sym)) { if(!factor(sym)) { print_cerror("factor composition\n",&sym->type,&lineNumber); exit(EXIT_FAILURE); break; } } } else { return false; } return true; } static char simple(Token_t *sym) { char option = false; /*option to determine weather a term is expected or a simple*/ if(compare(sym,SM_PLUS) || compare(sym,SM_SUB)) /*cheack for the optional charaters*/ { option = true; /*indicated that a term is expected*/ } if(term(sym)) { while(add_op(sym)) { if(!term(sym)) { print_cerror("term composition\n",&sym->type,&lineNumber); exit(EXIT_FAILURE); break; } } } else { if(option) /*if a term expected then return true, else return false, indicated a simple or expresion*/ { print_cerror("term composition\n",&sym->type,&lineNumber); } else { return false; } } return true; } static void expr(Token_t *sym) { if(simple(sym)) { if(relation(sym)) { if(!simple(sym)) { print_cerror("simple composition\n",&sym->type,&lineNumber); exit(EXIT_FAILURE); } } } else { print_cerror("Expression composition\n",&sym->type,&lineNumber); exit(EXIT_FAILURE); } } static void IF(Token_t *sym) { cheack(sym,SM_LT_R_BRK); expr(sym); cheack(sym,SM_RT_R_BRK); common(sym); if(compare(sym,SM_ELSE)) { common(sym); } } static void FOR(Token_t *sym) { cheack(sym,SM_LT_R_BRK); cheack(sym,SM_ID); cheack(sym,SM_EQUAL); expr(sym); cheack(sym,SM_SEMI_COLON); expr(sym); cheack(sym,SM_RT_R_BRK); common(sym); } static void WHILE(Token_t *sym) { cheack(sym,SM_LT_R_BRK); expr(sym); cheack(sym,SM_RT_R_BRK); common(sym); } static void assignment(Token_t *sym) { if(compare(sym,SM_EQUAL)) { expr(sym); } else if(compare(sym,SM_LT_S_BRK)) { expr(sym); cheack(sym,SM_RT_S_BRK); cheack(sym,SM_EQUAL); expr(sym); } else { print_cerror("Assignment operator expected, (=,[)\n",&sym->type,&lineNumber); exit(EXIT_FAILURE); } cheack(sym,SM_SEMI_COLON); } static void common(Token_t *sym) { /*cheack for the matchin of everything in vardecl, command( simple,compound,block)*/ if(compare(sym,SM_PRINT)) { cheack(sym,SM_LT_R_BRK); expr(sym); cheack(sym,SM_RT_R_BRK); cheack(sym,SM_SEMI_COLON); } else if(compare(sym,SM_ID)) { assignment(sym); }else if(sym->type != SM_SEMI_COLON) if(compare(sym,SM_IF)) { IF(sym); } else if(compare(sym,SM_FOR)) { FOR(sym); } else if(compare(sym,SM_WHILE)) { WHILE(sym); } else if(compare(sym,SM_LT_C_BRK)) { while(!compare(sym,SM_RT_C_BRK)) { common(sym); } } else { print_cerror("Command(Simple, Compound,Block)\n",&sym->type,&lineNumber); exit(EXIT_FAILURE); /*error invaled command*/ } } static void VarDecl(Token_t *sym) /*cheaks for all type's of varible decl;arations*/ { cheack(sym,SM_ID); while(!compare(sym,SM_SEMI_COLON)) { cheack(sym,SM_COMMA); cheack(sym,SM_ID); } } static void santatical(Token_t *sym) /*Start the snatatical analissys method*/ { getSym(sym); /*get the first token*/ cheack(sym, SM_CLASS); cheack(sym, SM_ID); cheack(sym, SM_LT_C_BRK); while((compare(sym,SM_INT)) || (compare(sym,SM_BOOLEAN))) /*if found must cheack santax against Vardecl orders*/ { VarDecl(sym); } while(!compare(sym, SM_RT_C_BRK)) { common(sym); /*call the next method to deal with next expected logic*/ } //cheack(sym, SM_EOF); /*Files with out leed char (linux)*/ } int main( int argc, char * argv[] ) { Token_t sym; sym.ident = (char*) malloc((MAX_STR_LEN + 1) * sizeof(char)); if(sym.ident == NULL) { printf("Error Not Enough memory Avalible"); return EXIT_FAILURE; } else { if( argc != 2 ) { printf( "Usage: testScanner <filename>\n" ); printf( "\twhere <filename> is the file to be scanned\n" ); } else { initScanner( argv[1] ); santatical(&sym); } free( sym.ident ); printf("Reading File has ended"); return EXIT_SUCCESS; } }
C
/* LC-2K Instruction-level simulator */ #include <stdlib.h> #include <stdio.h> #include <string.h> #define NUMMEMORY 65536 /* maximum number of words in memory */ #define NUMREGS 8 /* number of machine registers */ #define MAXLINELENGTH 1000 // Basic struct typedef struct stateStruct { int pc; int mem[NUMMEMORY]; int reg[NUMREGS]; int numMemory; } stateType; // Declare functions void printState(stateType *); int convertNum(int); // main function int main(int argc, char *argv[]) { // necessary variables int total_instruction = 0; int alive = 1; int instruction; char line[MAXLINELENGTH]; stateType state; FILE *filePtr; // incorrect type if(argc != 2){ printf("error: usage: %s <machine-code file>\n", argv[0]); exit(1); } // open file to read filePtr = fopen(argv[1], "r"); if(filePtr == NULL) { printf("error: can't open file %s", argv[1]); perror("fopen"); exit(1); } // CPU BOOTING // a 32-bit computer state.pc = 0; for(int i = 0; i < NUMREGS; i++) state.reg[i] = 0; /* read in the entire machine-code file into memory */ for(state.numMemory = 0; fgets(line, MAXLINELENGTH, filePtr) != NULL; state.numMemory++) { if(sscanf(line, "%d", state.mem+state.numMemory) != 1) { printf("error in reading address %d\n", state.numMemory); exit(1); } printf("memory[%d]=%d\n", state.numMemory, state.mem[state.numMemory]); } // RUN CPU // opcode is (state.mem[state.pc] >> 22) while(alive) { //while((state.mem[state.pc] >> 22) != 6) { /* * KEEP in mind * printState(&state); * state.pc++; if add, nor, lw, sw, noop */ total_instruction++; instruction = state.mem[state.pc]; printState(&state); // instruction >> 22 = opcode switch(instruction >> 22) { case 0: // add // instruction % 8 = destReg // (instruction >> 19) % 8 = regA // (instruction >> 16) % 8 = regB state.reg[instruction % 8] = state.reg[(instruction >> 19) % 8] + state.reg[(instruction >> 16) % 8]; state.pc++; break; case 1: // nor state.reg[instruction % 8] = ~( state.reg[(instruction >> 19) % 8] | state.reg[(instruction >> 16) % 8]); state.pc++; break; case 2: // lw // instruction % 65536 = offset (16-bit) state.reg[(instruction >> 16) % 8] = state.mem[state.reg[(instruction >> 19) % 8] + convertNum(instruction % 65536)]; state.pc++; break; case 3: // sw state.mem[state.reg[(instruction >> 19) % 8] + convertNum(instruction % 65536)] = state.reg[(instruction >> 16) % 8]; state.pc++; break; case 4: // beq if(state.reg[(instruction >> 19) % 8] == state.reg[(instruction >> 16) % 8]) state.pc += convertNum(instruction % 65536); state.pc++; break; case 5: // jalr state.reg[(instruction >> 16) % 8] = state.pc + 1; state.pc = state.reg[(instruction >> 19) % 8]; break; case 6: // halt // ERROR SITUATION alive = 0; // dead potato state.pc++; break; case 7: // noop state.pc++; break; default: // ERROR SITUATION exit(1); break; } } // state before halt is executed printf("machine halted\n"); printf("total of %d instructions executed\n", total_instruction); printf("final state of machine:\n"); // print the final halt state printState(&state); return(0); } // print STATE void printState(stateType *statePtr) { int i; printf("\n@@@\nstate:\n"); printf("\tpc %d\n", statePtr->pc); printf("\tmemory:\n"); for(i=0; i<statePtr->numMemory; i++) { printf("\t\tmem[ %d ] %d\n", i, statePtr->mem[i]); } printf("\tregisters:\n"); for(i=0; i<NUMREGS; i++) { printf("\t\treg[ %d ] %d\n", i, statePtr->reg[i]); } printf("end state\n"); } // PROFESSOR HINT int convertNum(int num) { /* convert a 16-bit number into a 32-bit Linux integer */ if(num & (1<<15)) { num -= (1<<16); } return(num); }
C
/* * _2_LED_3_.c * * Created: 2018-04-11 오전 9:37:26 * Author: 17 */ #define F_CPU 14745600L #include <avr/io.h> #include <util/delay.h> int main(void) { uint8_t ledData; DDRA=0xff; ledData=0x7f; while(1) { PORTA=ledData; _delay_ms(500); ledData=ledData>>1; ledData=ledData|0b10000000; if(ledData==0xff) { ledData=0x7f; } } return 0; }
C
/* Test: strncpy.c Simple test of strncpy */ #include <stdlib.h> #include <string.h> #include <stdio.h> int main(argc,argv) int argc; char **argv; { char *a = "This is a long string"; char *b = "short"; char *c = "abcde"; char *d; d = strncpy( a, b, 10 ); if( d != a ) return 10; if( a[0] != 's' ) return 20; if( a[5] != NULL ) return 30; if( a[6] != NULL ) return 40; d = strncpy( a, c, 3 ); if( d != a ) return 40; if( a[3] != 'r' ) return 50; return 0; }
C
#include<stdio.h> int main() { int character; printf("Enter the character:"); scanf("%ch",&character); if(('A'&&'Z')||('a'&&'z')) { printf("Alphabet"); } else { printf("not"); return 0; } }
C
#define EE_DEVICE_ADDR 0xA0 #define SDA PIN_C13 #define SCL PIN_D9 #define IIC_READ 1 //-------------------------------------------------------------------------- void IIC_Delay(void) { delay_us(2); } //-------------------------------------------------------------------------- void init_i2c(void) { output_drive(SCL); output_drive(SDA); Output_high(SCL); Output_high(SDA); } //-------------------------------------------------------------------------- // Sends ack to I2C device //-------------------------------------------------------------------------- void IIC_SendAck(void) { output_low(SDA); IIC_Delay(); output_high(SCL); IIC_Delay(); output_low(SCL); IIC_Delay(); output_high(SDA); } //-------------------------------------------------------------------------- // Sends one unsigned to I2C device //-------------------------------------------------------------------------- void IIC_SendOne(void) { output_high(SDA); IIC_Delay(); output_high(SCL); IIC_Delay(); output_low(SCL); } //-------------------------------------------------------------------------- // Sends 8 bits to I2C device // Gets the byte to send from W register //-------------------------------------------------------------------------- bit IIC_WriteByte(UCHAR send_bits) { UINT count; bit Ack; output_drive(SCL); output_drive(SDA); for (count = 0; count < 8; count++) { if (send_bits & 0x80) Output_high(SDA); else Output_low(SDA); send_bits <<= 1; output_high(SCL); IIC_Delay(); output_low(SCL); } output_high(SDA); output_float(SDA); IIC_Delay(); output_high(SCL); IIC_Delay(); Ack = input(SDA); output_low(SCL); output_float(SDA); // output_float(SCL); delay_us(50); return !Ack; } //-------------------------------------------------------------------------- // Receives 8 bits from I2C device // returns the received byte in the W reg. //-------------------------------------------------------------------------- UCHAR IIC_ReadByte(UCHAR ack) { UCHAR rec_bits = 0; UINT count; output_drive(SCL); output_high(SDA); output_float(SDA); IIC_Delay(); for (count = 0; count < 8; count++) { rec_bits <<= 1; output_high(SCL); IIC_Delay(); if (input(SDA)) rec_bits |= 1; output_low(SCL); IIC_Delay(); } output_drive(SDA); output_high(SDA); if (ack) IIC_SendAck(); delay_us(50); return rec_bits; } //-------------------------------------------------------------------------- // Sends start unsigned to I2C device //-------------------------------------------------------------------------- void IIC_Start(void) { output_high(SDA); IIC_Delay(); IIC_Delay(); output_high(SCL); IIC_Delay(); IIC_Delay(); output_low(SDA); IIC_Delay(); IIC_Delay(); output_low(SCL); IIC_Delay(); IIC_Delay(); } //-------------------------------------------------------------------------- // Sends stop unsigned to I2C device //-------------------------------------------------------------------------- void IIC_Stop(void) { output_drive(SDA); output_low(SDA); IIC_Delay(); IIC_Delay(); output_high(SCL); IIC_Delay(); IIC_Delay(); output_high(SDA); IIC_Delay(); } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- void IIC_PacketPreamble(UINT Address) { // IIC_Polling(); IIC_Start(); IIC_WriteByte(EE_DEVICE_ADDR); IIC_WriteByte(make8(Address, 1)); IIC_WriteByte(make8(Address, 0)); } //-------------------------------------------------------------------------- void IIC_PrepareToRead(UINT Address) { IIC_PacketPreamble(Address); IIC_Stop(); IIC_Start(); IIC_WriteByte(EE_DEVICE_ADDR | IIC_READ); } //-------------------------------------------------------------------------- void IIC_CloseRead(void) { IIC_ReadByte(0); IIC_SendOne(); IIC_Stop(); } //-------------------------------------------------------------------------- void IIC_ReadBytes(UINT Address, UCHAR *bufptr, UINT n_Len) { IIC_PrepareToRead(Address); while (n_Len--) { *bufptr++ = IIC_ReadByte(0); IIC_SendAck(); } IIC_CloseRead(); } //-------------------------------------------------------------------------- void IIC_WriteBytes(UINT Address,UCHAR *bufptr, UINT n_Len) { IIC_PacketPreamble(Address); #ignore_warnings 203 // the following loop IS an endless loop while (1) { #ignore_warnings none // the following loop IS an endless loop IIC_WriteByte(*bufptr++); ++Address; if (!--n_Len) break; } IIC_Stop(); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> /* * [Basic Idea] Use DP */ typedef unsigned int pos_value_t; typedef unsigned long tree_length_t; typedef struct dp_table_entry { tree_length_t dpe_min_tree_length; pos_value_t dpe_x; pos_value_t dpe_y; } dp_table_entry; #define NUM_POINTS_MAX 1000 int load_data(FILE *fp, int num_points_max, pos_value_t x[], pos_value_t y[]) { int n; unsigned int i; if (1 != fscanf(fp, "%u\n", &n)) return -1; if (num_points_max < n) return -1; for (i = 0; i < n; i++) { pos_value_t xi, yi; if (2 != fscanf(fp, "%u %u\n", &xi, &yi)) return -1; x[i] = xi, y[i] = yi; } return n; } void init_dp_table(int n, dp_table_entry **table, pos_value_t x[], pos_value_t y[]) { int i, j; const tree_length_t LENGTH_MAX = ULONG_MAX; for (i = 0; i < n; i++) { table[i][i].dpe_min_tree_length = 0; table[i][i].dpe_x = x[i]; table[i][i].dpe_y = y[i]; } for (i = 0; i < n; i++) { for (j = i+1; j < n; j++) { table[i][j].dpe_min_tree_length = LENGTH_MAX; } } } tree_length_t length_of_tree_between(dp_table_entry **table, int i, int d, int j) { dp_table_entry *ip, *jp; tree_length_t length = 0; ip = &(table[i][d]); jp = &(table[d+1][j]); length += ip->dpe_min_tree_length; length += jp->dpe_min_tree_length; length += jp->dpe_x - ip->dpe_x; length += ip->dpe_y - jp->dpe_y; return length; } void fill_dp_table(int n, dp_table_entry **table) { int i, j, k; /* * table[0][1], table[1][2], ..., table[n-2][n-1] * table[0][2], table[1][3], ..., table[n-3][n-1] * : * table[0][n-3], table[1][n-2], table[2][n-1] * table[0][n-2], table[1][n-1] * table[0][n-1] */ for (k = 1; k < n; k++) { for (i = 0, j = k; j < n; i++, j++) { /* table[0][k], table[1][1+k], ..., table[n-1-k][n-1] */ int d; /* division point */ dp_table_entry *ep = &(table[i][j]); for (d = i; d < j; d++) { tree_length_t length = length_of_tree_between(table, i, d, j); if (ep->dpe_min_tree_length <= length) continue; ep->dpe_min_tree_length = length; ep->dpe_x = table[i][d].dpe_x; ep->dpe_y = table[d+1][j].dpe_y; } } } } dp_table_entry** dp_table_alloc(int n) { int i; dp_table_entry **table; if (!(table = malloc(n * sizeof(dp_table_entry*)))) { return NULL; } memset(table, 0, (n * sizeof(dp_table_entry*))); for (i = 0; i < n; i++) { if (!(table[i] = malloc(n * sizeof(dp_table_entry)))) { goto free_exit; } } return table; free_exit: for (i = 0; i < n; i++) { if (!table[i]) continue; free(table[i]); table[i] = NULL; } free(table); table = NULL; return NULL; } void dp_table_free(dp_table_entry** table, int n) { int i; for (i = 0; i < n; i++) { free(table[i]); table[i] = NULL; } free(table); } tree_length_t calc_total_length(int n, pos_value_t x[], pos_value_t y[]) { tree_length_t length; dp_table_entry **table; if (!(table = dp_table_alloc(n))) { return 0; /* pending: should return negative value? */ } init_dp_table(n, table, x, y); fill_dp_table(n, table); length = table[0][n-1].dpe_min_tree_length; dp_table_free(table, n); table = NULL; return length; } int main(int argc, char *argv[]) { pos_value_t x[NUM_POINTS_MAX], y[NUM_POINTS_MAX]; int n; if ((n = load_data(stdin, NUM_POINTS_MAX, x, y)) <= 0) { return 1; } printf("%lu\n", calc_total_length(n, x, y)); return 0; }
C
/*subfile: polygn.c ********************************************************/ /* */ /* This software was developed at the National Institute of Standards */ /* and Technology by employees of the Federal Government in the */ /* course of their official duties. Pursuant to title 17 Section 105 */ /* of the United States Code this software is not subject to */ /* copyright protection and is in the public domain. These programs */ /* are experimental systems. NIST assumes no responsibility */ /* whatsoever for their use by other parties, and makes no */ /* guarantees, expressed or implied, about its quality, reliability, */ /* or any other characteristic. We would appreciate acknowledgment */ /* if the software is used. This software can be redistributed and/or */ /* modified freely provided that any derivative works bear some */ /* notice that they are derived from it, and any modified versions */ /* bear some notice that they have been modified. */ /* */ /*****************************************************************************/ /* The functions in this file maintain: * a stack of free vertex/edge structures, * a stack of free polygon structures, and * one or more stacks of defined polygon structures. * Only one defined polygon stack may be created at a time. * However, multiple stacks may be saved by using external pointers. */ #include <stdio.h> #include <string.h> /* prototype: memset, memcpy */ #include <math.h> /* prototype: fabs */ #include "types.h" #include "view3d.h" #include "prtyp.h" typedef struct memblock /* block of memory for small structure allocation */ { UX blockSize; /* number of bytes in block */ UX dataOffset; /* offset to free space */ struct memblock *priorBlock; /* pointer to previous block */ struct memblock *nextBlock; /* pointer to next block */ } MEMBLOCK; IX TransferVrt( VERTEX2D *toVrt, const VERTEX2D *fromVrt, IX nFromVrt ); I1 *_memPoly=NULL; /* memory block for polygon descriptions; must start NULL */ HCVE *_nextFreeVE; /* pointer to next free vertex/edge */ POLY *_nextFreePD; /* pointer to next free polygon descripton */ POLY *_nextUsedPD; /* pointer to top-of-stack used polygon */ R4 _epsDist; /* minimum distance between vertices */ R4 _epsArea; /* minimum surface area */ extern FILE *_ulog; /* log file */ /* Extensive use is made of 'homogeneous coordinates' (HC) which are not * familiar to most engineers. The important properties of HC are * summarized below: * A 2-D point (X,Y) is represented by a 3-element vector (w*X,w*Y,w), * where w may be any real number except 0. A line is also represented * by a 3-element vector (a,b,c). The directed line from point * (w*X1,w*Y1,w) to point (v*X2,v*Y2,v) is given by * (a,b,c) = (w*X1,w*Y1,w) cross (v*X2,v*Y2,v). * The sequence of the cross product is a convention to determine sign. * A point lies on a line if (a,b,c) dot (w*X,w*Y,w) = 0. * 'Normalize' the representation of a point by setting w to 1. Then * if (a,b,c) dot (X,Y,1) > 0.0, the point is to the left of the line. * If it is less than zero, the point is to the right of the line. * The point where two lines intersect is given by * (w*X,w*Y,w) = (a1,b1,c1) cross (a2,b2,c2). * Reference: W.M. Newman and R.F. Sproull, "Principles of Interactive * Computer Graphics", Appendix II, McGraw-Hill, 1973. */ /*** PolygonOverlap.c ******************************************************/ /* Process two convex polygons. Vertices are in clockwise sequence!! * * There are three processing options -- savePD: * (1) Determine the portion of polygon P2 which is within polygon P1; * this may create one convex polygon. * (3) Determine the portion of polygon P2 which is outside polygon P1; * this may create one or more convex polygons. * (2) Do both (1) and (3). * * If freeP2 is true, free P2 from its stack before exiting. * Return 0 if P2 outside P1, 1 if P2 inside P1, 2 for partial overlap. */ IX PolygonOverlap( const POLY *p1, POLY *p2, const IX savePD, IX freeP2 ) { POLY *pp; /* pointer to polygon */ POLY *initUsedPD; /* initial top-of-stack pointer */ HCVE *pv1; /* pointer to edge of P1 */ IX nLeftVrt; /* number of vertices to left of edge */ IX nRightVrt; /* number of vertices to right of edge */ IX nTempVrt; /* number of vertices of temporary polygon */ VERTEX2D leftVrt[MAXNVT]; /* coordinates of vertices to left of edge */ VERTEX2D rightVrt[MAXNVT]; /* coordinates of vertices to right of edge */ VERTEX2D tempVrt[MAXNVT]; /* coordinates of temporary polygon */ IX overlap=0; /* 0: P2 outside P1; 1: P2 inside P1; 2: part overlap */ IX j, jm1; /* vertex indices; jm1 = j - 1 */ #if( DEBUG > 0 ) NullPointerTest( __FILE__, __LINE__ ); #endif #if( DEBUG > 1 ) fprintf( _ulog, "PolygonOverlap: P1 [%p] P2 [%p] flag %d\n", p1, p2, savePD ); #endif initUsedPD = _nextUsedPD; nTempVrt = GetPolygonVrt2D( p2, tempVrt ); #if( DEBUG > 1 ) DumpP2D( "P2:", nTempVrt, tempVrt ); #endif pv1 = p1->firstVE; do{ /* process tempVrt against each edge of P1 (long loop) */ /* transfer tempVrt into leftVrt and/or rightVrt */ R8 a1, b1, c1; /* HC for current edge of P1 */ IX u[MAXNVT]; /* +1 = vertex left of edge; -1 = vertex right of edge */ IX left=1; /* true if all vertices left of edge */ IX right=1; /* true if all vertices right of edge */ #if( DEBUG > 1 ) fprintf(_ulog, "Test against edge of P1\nU:" ); #endif /* compute and save u[j] - relations of vertices to edge */ a1 = pv1->a; b1 = pv1->b; c1 = pv1->c; pv1 = pv1->next; for( j=0; j<nTempVrt; j++ ) { R8 dot = tempVrt[j].x * a1 + tempVrt[j].y * b1 + c1; if( dot > _epsArea ) { u[j] = 1; right = 0; } else if( dot < -_epsArea ) { u[j] = -1; left = 0; } else u[j] = 0; #if( DEBUG > 1 ) fprintf( _ulog, " %d", u[j] ); #endif } #if( DEBUG > 1 ) fprintf( _ulog, "\nQuick test: right %d; left %d;\n", right, left ); #endif /* use quick tests to skip unnecessary calculations */ if( right ) continue; if( left ) goto p2_outside_p1; /* check each vertex of tempVrt against current edge of P1 */ jm1 = nTempVrt - 1; for( nLeftVrt=nRightVrt=j=0; j<nTempVrt; jm1=j++ ) /* short loop */ { if( u[jm1]*u[j] < 0 ) /* vertices j-1 & j on opposite sides of edge */ { /* compute intercept of edges */ R8 a, b, c, w; /* HC intersection components */ a = tempVrt[jm1].y - tempVrt[j].y; b = tempVrt[j].x - tempVrt[jm1].x; c = tempVrt[j].y * tempVrt[jm1].x - tempVrt[jm1].y * tempVrt[j].x; w = b * a1 - a * b1; #if( DEBUG > 1 ) if( fabs(w) < _epsArea*(a+b+c) ) { error( 1, __FILE__, __LINE__, "small W", "" ); DumpHC( "P1:", p1, p1 ); DumpHC( "P2:", p2, p2 ); fprintf( _ulog, "a, b, c, w: %g %g %g %g\n", a, b, c, w ); fflush( _ulog ); fprintf( _ulog, "x, y: %g %g\n", (c*b1-b*c1)/w, (a*c1-c*a1)/w ); } #endif #if( DEBUG > 0 ) if( w == 0.0 ) error( 3, __FILE__, __LINE__, " Would divide by zero (w=0)", "" ); #endif rightVrt[nRightVrt].x = leftVrt[nLeftVrt].x = (R4)(( c*b1 - b*c1 ) / w); rightVrt[nRightVrt++].y = leftVrt[nLeftVrt++].y = (R4)(( a*c1 - c*a1 ) / w); } if( u[j] >= 0 ) /* vertex j is on or left of edge */ { leftVrt[nLeftVrt].x = tempVrt[j].x; leftVrt[nLeftVrt++].y = tempVrt[j].y; } if( u[j] <= 0 ) /* vertex j is on or right of edge */ { rightVrt[nRightVrt].x = tempVrt[j].x; rightVrt[nRightVrt++].y = tempVrt[j].y; } } /* end of short loop */ #if( DEBUG > 1 ) DumpP2D( "Left polygon:", nLeftVrt, leftVrt ); DumpP2D( "Right polygon:", nRightVrt, rightVrt ); #endif if( nLeftVrt >= MAXNVT || nRightVrt >= MAXNVT ) error( 3, __FILE__, __LINE__, "Parameter MAXNVT too small", "" ); if( savePD > 1 ) /* transfer left vertices to outside polygon */ { nTempVrt = TransferVrt( tempVrt, leftVrt, nLeftVrt ); #if( DEBUG > 1 ) DumpP2D( "Outside polygon:", nTempVrt, tempVrt ); #endif if( nTempVrt > 2 ) { SetPolygonHC( nTempVrt, tempVrt, p2->trns ); overlap = 1; } } /* transfer right side vertices to tempVrt */ nTempVrt = TransferVrt( tempVrt, rightVrt, nRightVrt ); #if( DEBUG > 1 ) DumpP2D( "Inside polygon:", nTempVrt, tempVrt ); #endif if( nTempVrt < 2 ) /* 2 instead of 3 allows degenerate P2; espArea = 0 */ goto p2_outside_p1; } while( pv1 != p1->firstVE ); /* end of P1 long loop */ /* At this point tempVrt contains the overlap of P1 and P2. */ if( savePD < 3 ) /* save the overlap polygon */ { #if( DEBUG > 1 ) DumpP2D( "Overlap polygon:", nTempVrt, tempVrt ); #endif pp = SetPolygonHC( nTempVrt, tempVrt, p2->trns * p1->trns ); if( pp==NULL && savePD==2 ) /* overlap area too small */ goto p2_outside_p1; } overlap += 1; goto finish; p2_outside_p1: /* no overlap between P1 and P2 */ overlap = 0; #if( DEBUG > 1 ) fprintf( _ulog, "P2 outside P1\n" ); #endif if( savePD > 1 ) /* save outside polygon - P2 */ { if( initUsedPD != _nextUsedPD ) /* remove previous outside polygons */ FreePolygons( _nextUsedPD, initUsedPD ); if( freeP2 ) /* transfer P2 to new stack */ { pp = p2; freeP2 = 0; /* P2 already freed */ } else /* copy P2 to new stack */ { HCVE *pv, *pv2; pp = GetPolygonHC(); /* get cleared polygon data area */ pp->area = p2->area; /* copy P2 data */ pp->trns = p2->trns; pv2 = p2->firstVE; do{ if( pp->firstVE ) pv = pv->next = GetVrtEdgeHC(); else pv = pp->firstVE = GetVrtEdgeHC(); memcpy( pv, pv2, sizeof(HCVE) ); /* copy vertex/edge data */ pv2 = pv2->next; } while( pv2 != p2->firstVE ); pv->next = pp->firstVE; /* complete circular list */ #if( DEBUG > 1 ) DumpHC( "COPIED SURFACE:", pp, pp ); #endif } pp->next = initUsedPD; /* link PP to stack */ _nextUsedPD = pp; } finish: #if( DEBUG > 0 ) NullPointerTest( __FILE__, __LINE__ ); #endif if( freeP2 ) /* transfer P2 to free space */ FreePolygons( p2, p2->next ); return overlap; } /* end of PolygonOverlap */ /*** TransferVrt.c *********************************************************/ /* Transfer vertices from polygon fromVrt to polygon toVrt eliminating nearly * duplicate vertices. Closeness of vertices determined by _epsDist. * Return number of vertices in polygon toVrt. */ IX TransferVrt( VERTEX2D *toVrt, const VERTEX2D *fromVrt, IX nFromVrt ) { IX j, /* index to vertex in polygon fromVrt */ jm1, /* = j - 1 */ n; /* index to vertex in polygon toVrt */ jm1 = nFromVrt - 1; for( n=j=0; j<nFromVrt; jm1=j++ ) if( fabs(fromVrt[j].x - fromVrt[jm1].x) > _epsDist || fabs(fromVrt[j].y - fromVrt[jm1].y) > _epsDist ) { /* transfer to toVrt */ toVrt[n].x = fromVrt[j].x; toVrt[n++].y = fromVrt[j].y; } else if( n>0 ) /* close: average with prior toVrt vertex */ { toVrt[n-1].x = 0.5f * (toVrt[n-1].x + fromVrt[j].x); toVrt[n-1].y = 0.5f * (toVrt[n-1].y + fromVrt[j].y); } else /* (n=0) average with prior fromVrt vertex */ { toVrt[n].x = 0.5f * (fromVrt[jm1].x + fromVrt[j].x); toVrt[n++].y = 0.5f * (fromVrt[jm1].y + fromVrt[j].y); nFromVrt -= 1; /* do not examine last vertex again */ } return n; } /* end TransferVrt */ /*** SetPolygonHC.c ********************************************************/ /* Set up polygon including homogeneous coordinates of edges. * Return NULL if polygon area too small; otherwise return pointer to polygon. */ POLY *SetPolygonHC( const IX nVrt, const VERTEX2D *polyVrt, const R4 trns ) /* nVrt - number of vertices (vertices in clockwise sequence); * polyVrt - X,Y coordinates of vertices (1st vertex not repeated at end), index from 0 to nVrt-1. */ { POLY *pp; /* pointer to polygon */ HCVE *pv; /* pointer to HC vertices/edges */ R8 area=0.0; /* polygon area */ IX j, jm1; /* vertex indices; jm1 = j - 1 */ pp = GetPolygonHC(); /* get cleared polygon data area */ #if( DEBUG > 1 ) fprintf( _ulog, " SetPolygonHC: pp [%p] nv %d\n", pp, nVrt ); #endif jm1 = nVrt - 1; for( j=0; j<nVrt; jm1=j++ ) /* loop through vertices */ { if( pp->firstVE ) pv = pv->next = GetVrtEdgeHC(); else pv = pp->firstVE = GetVrtEdgeHC(); pv->x = polyVrt[j].x; pv->y = polyVrt[j].y; pv->a = polyVrt[jm1].y - polyVrt[j].y; /* compute HC values */ pv->b = polyVrt[j].x - polyVrt[jm1].x; pv->c = polyVrt[j].y * polyVrt[jm1].x - polyVrt[j].x * polyVrt[jm1].y; area -= pv->c; } pv->next = pp->firstVE; /* complete circular list */ pp->area = (R4)(0.5 * area); pp->trns = trns; #if( DEBUG > 1 ) fprintf( _ulog, " areas: %f %f, trns: %f\n", pp->area, _epsArea, pp->trns ); fflush( _ulog ); #endif if( pp->area < _epsArea ) /* polygon too small to save */ { FreePolygons( pp, NULL ); pp = NULL; } else { pp->next = _nextUsedPD; /* link polygon to current list */ _nextUsedPD = pp; /* prepare for next linked polygon */ } return pp; } /* end of SetPolygonHC */ /*** GetPolygonHC.c ********************************************************/ /* Return pointer to a cleared polygon structure. * This is taken from the list of unused structures if possible. * Otherwise, a new structure will be allocated. */ POLY *GetPolygonHC( void ) { POLY *pp; /* pointer to polygon structure */ if( _nextFreePD ) { pp = _nextFreePD; _nextFreePD = _nextFreePD->next; memset( pp, 0, sizeof(POLY) ); /* clear pointers */ } else pp = Alc_EC( &_memPoly, sizeof(POLY), "nextPD" ); return pp; } /* end GetPolygonHC */ /*** GetVrtEdgeHC.c ********************************************************/ /* Return pointer to an uncleared vertex/edge structure. * This is taken from the list of unused structures if possible. * Otherwise, a new structure will be allocated. */ HCVE *GetVrtEdgeHC( void ) { HCVE *pv; /* pointer to vertex/edge structure */ if( _nextFreeVE ) { pv = _nextFreeVE; _nextFreeVE = _nextFreeVE->next; } else pv = Alc_EC( &_memPoly, sizeof(HCVE), "nextVE" ); return pv; } /* end GetVrtEdgeHC */ /*** Alc_EC.c **************************************************************/ /* Allocate small structures within a larger allocated block. * Can delete entire block but not individual structures. * This saves quite a bit of memory allocation overhead. * Also quite a bit faster than calling alloc() for each small structure. * Based on idea and code by Steve Weller, "The C Users Journal", * April 1990, pp 103 - 107. * Must begin with Alc_ECI for initialization; free with Fre_EC. */ void *Alc_EC( I1 **block, UX size, I1 *name ) /* block; pointer to current memory block. * size; size (bytes) of structure being allocated. * name; name of structure being allocated. */ { I1 *p; /* pointer to the structure */ UX blockSize; MEMBLOCK *mb, /* memory block */ *nb; /* new block */ #ifdef __TURBOC__ size = (size+3) & 0xFFFC; /* multiple of 4 */ #else size = (size+7) & 0xFFF8; /* multiple of 8 */ #endif mb = (void *)*block; blockSize = mb->blockSize; if( size > blockSize - sizeof(MEMBLOCK) ) error( 3, __FILE__, __LINE__, "Requested size larger than block ", IntStr(size), "" ); if( mb->dataOffset + size > blockSize ) { if( mb->nextBlock ) nb = mb->nextBlock; /* next block already exists */ else { /* else create next block */ nb = (MEMBLOCK *)Alc_E( blockSize, name ); nb->priorBlock = mb; /* back linked list */ mb->nextBlock = nb; /* forward linked list */ nb->nextBlock = NULL; nb->blockSize = blockSize; nb->dataOffset = sizeof(MEMBLOCK); } mb = nb; *block = (I1 *)(void *)nb; } p = *block + mb->dataOffset; mb->dataOffset += size; return (void *)p; } /* end of Alc_EC */ /*** FreePolygons.c ********************************************************/ /* Restore list of polygon descriptions to free space. */ void FreePolygons( POLY *first, POLY *last ) /* first; - pointer to first polygon in linked list (not NULL). * last; - pointer to polygon AFTER last one freed (NULL = complete list). */ { POLY *pp; /* pointer to polygon */ HCVE *pv; /* pointer to edge/vertex */ for( pp=first; ; pp=pp->next ) { #if( DEBUG > 0 ) if( !pp ) error( 3, __FILE__, __LINE__, "Polygon PP not defined", "" ); if( !pp->firstVE ) error( 3, __FILE__, __LINE__, "FirstVE not defined", "" ); #endif pv = pp->firstVE->next; /* free vertices (circular list) */ while( pv->next != pp->firstVE ) /* find "end" of vertex list */ pv = pv->next; pv->next = _nextFreeVE; /* reset vertex links */ _nextFreeVE = pp->firstVE; if( pp->next == last ) break; } pp->next = _nextFreePD; /* reset polygon links */ _nextFreePD = first; #if( DEBUG > 0 ) NullPointerTest( __FILE__, __LINE__ ); #endif } /* end of FreePolygons */ /*** NewPolygonStack.c *****************************************************/ /* Start a new stack (linked list) of polygons. */ void NewPolygonStack( void ) { _nextUsedPD = NULL; /* define bottom of stack */ } /* end NewPolygonStack */ /*** TopOfPolygonStack.c ***************************************************/ /* Return pointer to top of active polygon stack. */ POLY *TopOfPolygonStack( void ) { return _nextUsedPD; } /* end TopOfPolygonStack */ /*** GetPolygonVrt2D.c *****************************************************/ /* Get polygon vertices. Return number of vertices. * Be sure polyVrt is sufficiently long. */ IX GetPolygonVrt2D( const POLY *pp, VERTEX2D *polyVrt ) { HCVE *pv; /* pointer to HC vertices/edges */ IX j=0; /* vertex counter */ pv = pp->firstVE; do{ polyVrt[j].x = pv->x; polyVrt[j++].y = pv->y; pv = pv->next; } while( pv != pp->firstVE ); return j; } /* end of GetPolygonVrt2D */ /*** GetPolygonVrt3D.c *****************************************************/ /* Get polygon vertices. Return number of vertices. * Be sure polyVrt is sufficiently long. */ IX GetPolygonVrt3D( const POLY *pp, VERTEX3D *polyVrt ) { HCVE *pv; /* pointer to HC vertices/edges */ IX j=0; /* vertex counter */ pv = pp->firstVE; do{ polyVrt[j].x = pv->x; polyVrt[j].y = pv->y; polyVrt[j++].z = 0.0; pv = pv->next; } while( pv != pp->firstVE ); return j; } /* end of GetPolygonVrt3D */ /*** InitPolygonMem.c ******************************************************/ /* Initialize polygon processing memory and globals. */ void InitPolygonMem( const R4 epsdist, const R4 epsarea ) { if( _memPoly ) /* clear existing polygon structures data */ _memPoly = Clr_EC( _memPoly ); else /* allocate polygon structures heap pointer */ _memPoly = Alc_ECI( 2000, "memPoly" ); _epsDist = epsdist; _epsArea = epsarea; _nextFreeVE = NULL; _nextFreePD = NULL; _nextUsedPD = NULL; #if( DEBUG > 1 ) fprintf( _ulog, "InitPolygonMem: epsDist %g epsArea %g\n", _epsDist, _epsArea ); #endif } /* end InitPolygonMem */ /*** FreePolygonMem.c ******************************************************/ /* Free polygon processing memory. */ void FreePolygonMem( void ) { if( _memPoly ) _memPoly = (I1 *)Fre_EC( _memPoly, "memPoly" ); } /* end FreePolygonMem */ /*** Alc_ECI.c *************************************************************/ /* Block initialization for Alc_EC. */ I1 *Alc_ECI( UX size, I1 *name ) /* size; size (bytes) of block being allocated. * name; name of block being allocated. */ { I1 *p; /* pointer to the block */ MEMBLOCK *mb; p = (I1 *)Alc_E( size, name ); mb = (MEMBLOCK *)(void *)p; mb->priorBlock = NULL; mb->nextBlock = NULL; mb->blockSize = size; mb->dataOffset = sizeof(MEMBLOCK); return p; } /* end of Alc_ECI */ /*** Clr_EC.c **************************************************************/ /* Clr_EC: Clear (but do not free) blocks allocated by Alc_EC. */ I1 *Clr_EC( I1 *block ) /* block; pointer to current memory block. */ { IX header; /* size of header data */ I1 *p; /* pointer to the block */ MEMBLOCK *mb, *nb; header = sizeof(MEMBLOCK); mb = (MEMBLOCK *)(void *)block; while( mb ) { p = (void *)mb; nb = mb->priorBlock; memset( p + header, 0, mb->blockSize - header ); mb->dataOffset = header; mb = nb; } return p; } /* end of Clr_EC */ /*** Fre_EC.c **************************************************************/ /* Free blocks allocated by Alc_EC. */ void *Fre_EC( I1 *block, I1 *name ) /* block; pointer to current memory block. * name; name of structure being freed. */ { MEMBLOCK *mb, *nb; block = Clr_EC( block ); mb = (MEMBLOCK *)(void *)block; if( mb ) while( mb->nextBlock ) /* guarantee mb at end of list */ mb = mb->nextBlock; else error( 3, __FILE__, __LINE__, "null block pointer, call George", "" ); while( mb ) { nb = mb->priorBlock; Fre_E( mb, mb->blockSize, name ); mb = nb; } return (NULL); } /* end of Fre_EC */ /*** LimitPolygon.c ********************************************************/ /* This function limits the polygon coordinates to a rectangle which encloses * the base surface. Vertices may be in clockwise or counter-clockwise order. * The polygon is checked against each edge of the window, with the portion * inside the edge saved in the tempVrt or polyVrt array in turn. * The code is long, but the loops are short. * Return the number of number of vertices in the clipped polygon * and the clipped vertices in polyVrt. */ IX LimitPolygon( IX nVrt, VERTEX2D polyVrt[], const R4 maxX, const R4 minX, const R4 maxY, const R4 minY ) { VERTEX2D tempVrt[MAXNV2]; /* temporary vertices */ IX n, m; /* vertex index */ /* test vertices against maxX */ polyVrt[nVrt].x = polyVrt[0].x; polyVrt[nVrt].y = polyVrt[0].y; for( n=m=0; n<nVrt; n++ ) { if( polyVrt[n].x < maxX) { tempVrt[m].x = polyVrt[n].x; tempVrt[m++].y = polyVrt[n].y; if( polyVrt[n+1].x > maxX) { tempVrt[m].x = maxX; tempVrt[m++].y = polyVrt[n].y + (maxX - polyVrt[n].x) * (polyVrt[n+1].y - polyVrt[n].y) / (polyVrt[n+1].x - polyVrt[n].x); } } else if( polyVrt[n].x > maxX ) { if ( polyVrt[n+1].x < maxX ) { tempVrt[m].x = maxX; tempVrt[m++].y = polyVrt[n].y + (maxX - polyVrt[n].x) * (polyVrt[n+1].y - polyVrt[n].y) / (polyVrt[n+1].x - polyVrt[n].x); } } else { tempVrt[m].x = polyVrt[n].x; tempVrt[m++].y = polyVrt[n].y; } } /* end of maxX test */ nVrt = m; if( nVrt < 3 ) return 0; /* test vertices against minX */ tempVrt[nVrt].x = tempVrt[0].x; tempVrt[nVrt].y = tempVrt[0].y; for( n=m=0; n<nVrt; n++ ) { if( tempVrt[n].x > minX) { polyVrt[m].x = tempVrt[n].x; polyVrt[m++].y = tempVrt[n].y; if( tempVrt[n+1].x < minX) { polyVrt[m].x = minX; polyVrt[m++].y = tempVrt[n].y + (minX - tempVrt[n].x) * (tempVrt[n+1].y - tempVrt[n].y) / (tempVrt[n+1].x - tempVrt[n].x); } } else if( tempVrt[n].x < minX ) { if ( tempVrt[n+1].x > minX ) { polyVrt[m].x = minX; polyVrt[m++].y = tempVrt[n].y + (minX - tempVrt[n].x) * (tempVrt[n+1].y - tempVrt[n].y) / (tempVrt[n+1].x - tempVrt[n].x); } } else { polyVrt[m].x = tempVrt[n].x; polyVrt[m++].y = tempVrt[n].y; } } /* end of minX test */ nVrt = m; if( nVrt < 3 ) return 0; /* test vertices against maxY */ polyVrt[nVrt].y = polyVrt[0].y; polyVrt[nVrt].x = polyVrt[0].x; for( n=m=0; n<nVrt; n++ ) { if( polyVrt[n].y < maxY) { tempVrt[m].y = polyVrt[n].y; tempVrt[m++].x = polyVrt[n].x; if( polyVrt[n+1].y > maxY) { tempVrt[m].y = maxY; tempVrt[m++].x = polyVrt[n].x + (maxY - polyVrt[n].y) * (polyVrt[n+1].x - polyVrt[n].x) / (polyVrt[n+1].y - polyVrt[n].y); } } else if( polyVrt[n].y > maxY ) { if ( polyVrt[n+1].y < maxY ) { tempVrt[m].y = maxY; tempVrt[m++].x = polyVrt[n].x + (maxY - polyVrt[n].y) * (polyVrt[n+1].x - polyVrt[n].x) / (polyVrt[n+1].y - polyVrt[n].y); } } else { tempVrt[m].y = polyVrt[n].y; tempVrt[m++].x = polyVrt[n].x; } } /* end of maxY test */ nVrt = m; if( nVrt < 3 ) return 0; /* test vertices against minY */ tempVrt[nVrt].y = tempVrt[0].y; tempVrt[nVrt].x = tempVrt[0].x; for( n=m=0; n<nVrt; n++ ) { if( tempVrt[n].y > minY) { polyVrt[m].y = tempVrt[n].y; polyVrt[m++].x = tempVrt[n].x; if( tempVrt[n+1].y < minY) { polyVrt[m].y = minY; polyVrt[m++].x = tempVrt[n].x + (minY - tempVrt[n].y) * (tempVrt[n+1].x - tempVrt[n].x) / (tempVrt[n+1].y - tempVrt[n].y); } } else if( tempVrt[n].y < minY ) { if ( tempVrt[n+1].y > minY ) { polyVrt[m].y = minY; polyVrt[m++].x = tempVrt[n].x + (minY - tempVrt[n].y) * (tempVrt[n+1].x - tempVrt[n].x) / (tempVrt[n+1].y - tempVrt[n].y); } } else { polyVrt[m].y = tempVrt[n].y; polyVrt[m++].x = tempVrt[n].x; } } /* end of minY test */ nVrt = m; if( nVrt < 3 ) return 0; return nVrt; /* note: final results are in polyVrt */ } /* end of LimitPolygon */ #if( DEBUG > 0 ) /*** DumpHC.c **************************************************************/ /* Print the descriptions of sequential polygons. */ void DumpHC( I1 *title, const POLY *pfp, const POLY *plp ) /* pfp, plp; pointers to first and last (NULL acceptable) polygons */ { const POLY *pp; HCVE *pv; IX i, j; fprintf( _ulog, "%s\n", title ); for( i=0,pp=pfp; pp; pp=pp->next ) /* polygon loop */ { fprintf( _ulog, " pd [%p]", pp ); fprintf( _ulog, " area %.4g", pp->area ); fprintf( _ulog, " trns %.3g", pp->trns ); fprintf( _ulog, " next [%p]", pp->next ); fprintf( _ulog, " fve [%p]\n", pp->firstVE ); if( ++i >= 100 ) error( 3, __FILE__, __LINE__, "Too many surfaces", "" ); j = 0; pv = pp->firstVE; do{ /* vertex/edge loop */ fprintf( _ulog, " ve [%p] %10.7f %10.7f %10.7f %10.7f %13.8f\n", pv, pv->x, pv->y, pv->a, pv->b, pv->c ); pv = pv->next; if( ++j >= MAXNVT ) error( 3, __FILE__, __LINE__, "Too many vertices", "" ); } while( pv != pp->firstVE ); if( pp==plp ) break; } fflush( _ulog ); } /* end of DumpHC */ /*** DumpFreePolygons.c *****************************************************/ void DumpFreePolygons( void ) { POLY *pp; fprintf( _ulog, "FREE POLYGONS:" ); for( pp=_nextFreePD; pp; pp=pp->next ) fprintf( _ulog, " [%p]", pp ); fprintf( _ulog, "\n" ); } /* end DumpFreePolygons */ /*** DumpFreeVertices.c *****************************************************/ void DumpFreeVertices( void ) { HCVE *pv; fprintf( _ulog, "FREE VERTICES:" ); for( pv=_nextFreeVE; pv; pv=pv->next ) fprintf( _ulog, " [%p]", pv ); fprintf( _ulog, "\n" ); } /* end DumpFreeVertices */ /*** DumpP2D.c *************************************************************/ /* Dump 2-D polygon vertex data. */ void DumpP2D( I1 *title, const IX nvs, VERTEX2D *vs ) { IX n; fprintf( _ulog, "%s\n", title ); fprintf( _ulog, " nvs: %d\n", nvs ); for( n=0; n<nvs; n++) fprintf( _ulog, " vs: %d %12.7f %12.7f\n", n, vs[n].x, vs[n].y ); fflush( _ulog ); } /* end of DumpP2D */ /*** DumpP3D.c *************************************************************/ /* Dump 3-D polygon vertex data. */ void DumpP3D( I1 *title, const IX nvs, VERTEX3D *vs ) { IX n; fprintf( _ulog, "%s\n", title ); fprintf( _ulog, " nvs: %d\n", nvs ); for( n=0; n<nvs; n++) fprintf( _ulog, " vs: %d %12.7f %12.7f %12.7f\n", n, vs[n].x, vs[n].y, vs[n].z ); fflush( _ulog ); } /* end of DumpP3D */ #endif /* end DEBUG */
C
void get_axes(VEC3F wp1, VEC3F wp2, VEC3F wp3, VEC3F tp1, VEC3F tp2, VEC3F tp3, VEC3F *A, VEC3F *B, VEC3F *C) { VEC3F wd1, wd2, wd3, td1, td2, td3; VEC3F wn = NORMALIZED_VEC3F(vec3f_normal(wp1, wp2, wp3)), tn = vec3f(0.0, 0.0, 1.0); tn.z = fabs(tn.z); float k; wd1 = VEC3F_DIFF(wp1, wp2); wd2 = VEC3F_DIFF(wp2, wp3); wd3 = wn; td1 = VEC3F_DIFF(tp1, tp2); td2 = VEC3F_DIFF(tp2, tp3); td3 = tn; k = 1.0 / (wd1.x * (wd2.y * wd3.z - wd3.y * wd2.z) - wd2.x * (wd1.y * wd3.z - wd3.y * wd1.z) - wd3.x * (wd2.y * wd1.z - wd1.y * wd2.z)); A->x = (wd1.y * (wd2.z * td3.x - wd3.z * td2.x) + wd1.z * (wd3.y * td2.x - wd2.y * td3.x) + td1.x * (wd2.y * wd3.z - wd3.y * wd2.z)) * k; A->y = -(wd2.x * (wd3.z * td1.x - wd1.z * td3.x) + wd2.z * (wd1.x * td3.x - wd3.x * td1.x) + td2.x * (wd1.z * wd3.x - wd1.x * wd3.z)) * k; A->z = (wd3.y * (wd2.x * td1.x - wd1.x * td2.x) + wd2.y * (wd1.x * td3.x - wd3.x * td1.x) - wd1.y * (wd2.x * td3.x - wd3.x * td2.x)) * k; B->x = (wd1.y * (wd2.z * td3.y - wd3.z * td2.y) + wd1.z * (wd3.y * td2.y - wd2.y * td3.y) + td1.y * (wd2.y * wd3.z - wd3.y * wd2.z)) * k; B->y = -(wd2.x * (wd3.z * td1.y - wd1.z * td3.y) + wd2.z * (wd1.x * td3.y - wd3.x * td1.y) + td2.y * (wd1.z * wd3.x - wd1.x * wd3.z)) * k; B->z = (wd3.y * (wd2.x * td1.y - wd1.x * td2.y) + wd2.y * (wd1.x * td3.y - wd3.x * td1.y) - wd1.y * (wd2.x * td3.y - wd3.x * td2.y)) * k; C->x = (wd1.y * (wd2.z * td3.z - wd3.z * td2.z) + wd1.z * (wd3.y * td2.z - wd2.y * td3.z) + td1.z * (wd2.y * wd3.z - wd3.y * wd2.z)) * k; C->y = -(wd2.x * (wd3.z * td1.z - wd1.z * td3.z) + wd2.z * (wd1.x * td3.z - wd3.x * td1.z) + td2.z * (wd1.z * wd3.x - wd1.x * wd3.z)) * k; C->z = (wd3.y * (wd2.x * td1.z - wd1.x * td2.z) + wd2.y * (wd1.x * td3.z - wd3.x * td1.z) - wd1.y * (wd2.x * td3.z - wd3.x * td2.z)) * k; } void transform_to_space(VEC3F A, VEC3F B, VEC3F C, VEC3F wp1, VEC3F tp1, VEC3F wp, VEC3F *tp) { VEC3F v = VEC3F_DIFF(wp, wp1); tp->x = tp1.x + VEC3F_DOT_PRODUCT(v, A); tp->y = tp1.y + VEC3F_DOT_PRODUCT(v, B); tp->z = tp1.z + VEC3F_DOT_PRODUCT(v, C); }
C
//**************************************************// //**This Header File is used in combination********// //**with a dynamic Library and must be rewritten**// //**if you want to use it for another purpose****// //**********************************************// //******************************************// //**Credits: Razzile & HackJack**// //****************************************// //********************************************// //**Usage: vm_writeData(0xOFFSET, 0xDATA,SIZE)**// //******************************************// //importing and including files #include <Foundation/Foundation.h> #include <mach/mach.h> #include <mach-o/dyld.h> #include <mach/mach_traps.h> /* This Function checks if the Application has ASLR enabled. It gets the mach_header of the Image at Index 0. It then checks for the MH_PIE flag. If it is there, it returns TRUE. Parameters: nil Return: Wether it has ASLR or not */ bool hasASLR() { const struct mach_header *mach; mach = _dyld_get_image_header(0); if (mach->flags & MH_PIE) { //has aslr enabled return TRUE; } else { //has aslr disabled return FALSE; } } /* This Function gets the vmaddr slide of the Image at Index 0. Parameters: nil Return: the vmaddr slide */ long long get_slide() { return _dyld_get_image_vmaddr_slide(0); } /* This Function calculates the Address if ASLR is enabled or returns the normal offset. Parameters: The Original Offset Return: Either the Offset or the New calculated Offset if ASLR is enabled */ long long calculateAddress(long long offset) { if (hasASLR()) { long long slide = get_slide(); return (slide + offset); } else { return offset; } } /* This function calculates the size of the data passed as an argument. It returns 1 if 4 bytes and 0 if 2 bytes Parameters: data to be written Return: True = 4 bytes/higher or False = 2 bytes */ bool getType(unsigned int data) { int a = data & 0xffff8000; int b = a + 0x00008000; int c = b & 0xffff7fff; return c; } /* This is the main Function. This is where the writing takes place. It declares the port as mach_task_self, calculates the offset. Then it changes the Protections at the offset to be able to write to it. After that it sets the Protections back so the Apps runs as before Then it vm_writes either 4 Byte or 2 to the address. Parameters: the address and the data to be written Return: True = Success or False = Failed */ bool vm_writeData(long long offset, unsigned int data) { //declaring variables kern_return_t err; mach_port_t port = mach_task_self(); long long address = calculateAddress(offset); //set memory protections to allow us writing code there err = vm_protect(port, (long long) address, sizeof(data), NO,VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY); //check if the protection fails if (err != KERN_SUCCESS) { return FALSE; } //vm_write code to memory if(getType(data)) { data = CFSwapInt32(data); err = vm_write(port, address, (long long)&data, sizeof(data)); } else { data = (unsigned short)data; data = CFSwapInt16(data); err = vm_write(port, address, (long long)&data, sizeof(data)); } if (err != KERN_SUCCESS) { return FALSE; } //set the protections back to normal so the app can access this address as usual err = vm_protect(port, (long long)address, sizeof(data), NO,VM_PROT_READ | VM_PROT_EXECUTE); return TRUE; }
C
#include "holberton.h" #include <stdlib.h> /** * _strdup - Returns pointer to copy of string given as param * @str: Source string * * Return: NULL if insufficient memory, ptr to new string otherwise */ char *_strdup(char *str) { char *new_str; int i; int length = 0; if (!str) return (NULL); for (i = 0; str[i]; i++) length++; new_str = malloc(sizeof(char) * (length + 1)); if (!new_str) return (NULL); for (i = 0; str[i]; i++) new_str[i] = str[i]; new_str[length] = '\0'; return (new_str); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #define FLAGSIZE 64 /* gcc rand_word.c -zexecstack -fno-stack-protector -o ctf_binary -m32 */ /* V1: always chooses the same "random" word and format str vuln */ char* choose_random_word(const char *filename) { FILE *f; size_t lineno = 0; size_t selectlen; char selected[256]; /* Arbitrary, make it whatever size makes sense */ char current[256]; selected[0] = '\0'; /* Don't crash if file is empty */ f = fopen(filename, "r"); /* Add your own error checking */ while (fgets(current, sizeof(current), f)) { if (drand48() < 1.0 / ++lineno) { strcpy(selected, current); } } fclose(f); selectlen = strlen(selected); if (selectlen > 0 && selected[selectlen-1] == '\n') { selected[selectlen-1] = '\0'; } return strdup(selected); } void flag() { char buf[FLAGSIZE]; FILE *f = fopen("/home/ctf/flag.txt","r"); if (f == NULL) { printf("'flag.txt' missing in the current directory!\n"); exit(0); } fgets(buf,FLAGSIZE,f); printf(buf); } int main() { setvbuf(stdout, NULL, _IONBF, 0); srand((unsigned) time(NULL)); char *filename = "/usr/share/dict/american-english"; char *word = choose_random_word(filename); printf("What's my word?\n"); char str[120]; fgets(str,120,stdin); str[strcspn(str, "\n")] = '\0'; if (strcmp(word,str) == 0) { printf("yay, you got me\n"); flag(); } else { printf("nay, you wrong\nThe correct word was not "); printf(str); } return 0; }
C
/* Author: Pakkpon Phongthawee LANG: C Problem: Rhombus */ #include<stdio.h> int main(){ int i,j,input,n,m; scanf("%d",&input); for(i=0;i<=input/2;i++){ for(j=i;j<input/2;j++){ printf(" "); } for(j=0;j<i*2+1;j++){ printf("*"); } printf("\n"); } for(i=input/2-1;i>=0;i--){ for(j=i;j<input/2;j++){ printf(" "); } for(j=0;j<i*2+1;j++){ printf("*"); } printf("\n"); } return 0; }
C
#include <stdlib.h> #include <stdio.h> int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } int main(int argc, char **argv) { int n = atoi(argv[1]); printf("factorial(%d) = %d\n", n, factorial(n)); }
C
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; //~ A left rotation operation on an array of size shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2]. //~ Given an array of integers and a number, d , perform d left rotations on the array. Then print the updated array as a single line of space-separated integers. //~ Input Format //~ The first line contains two space-separated integers denoting the respective values of n(the number of integers) and d (the number of left rotations you must perform). //~ The second line contains n space-separated integers describing the respective elements of the array's initial state. vector<int> array_left_rotation(vector<int> a, int n, int k) { int it = k; int count = 0; int val; vector<int> b; while(count < a.size()){ if(it == a.size()){ it = 0; }else{ val = a.at(it); b.push_back(val); it++; count++; } } return b; } int main(){ int n; int k; cin >> n >> k; vector<int> a(n); for(int a_i = 0;a_i < n;a_i++){ cin >> a[a_i]; } vector<int> output = array_left_rotation(a, n, k); for(int i = 0; i < n;i++) cout << output[i] << " "; cout << endl; return 0; }
C
/* C Programming A Modern Approach * Chapter 5 * Exercise 2 * *Asks the user for a 24-hour time, then displays the time in 12-hour form. * * Author: Alex Perkins * Date: 28-May-2020 */ #include <stdio.h> #include <inttypes.h> int main(void) { uint16_t hour = 0, minute = 0; printf("Enter a 24-hour time: "); scanf("%hu:%hu", &hour, &minute); if(hour > 12) { hour -= 12; printf("Equivalent 12-hour time: %hu:%02hu PM\n", hour, minute); } else if(hour == 0) { hour = 12; printf("Equivalent 12-hour time: %hu:%02hu AM\n", hour, minute); } else { printf("Equivalent 12-hour time: %hu:%02hu AM\n", hour, minute); } return 0; }
C
#include<stdio.h> unsigned replace_byte(unsigned x,unsigned char b,int i); int main() { unsigned x=0x12345678; char b=0xab; printf("%#x\n",replace_byte(x,b,0)); printf("%#x\n",replace_byte(x,b,2)); return 0; } unsigned replace_byte(unsigned x,unsigned char b,int i) { x&=~(0xff<<(i*8)); x+=((int)b)<<i*8; return x; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <pthread.h> #define ORDER 9 typedef enum{false, true}bool; typedef struct{int x; int y;}point; int matrix[ORDER][ORDER]; int emptys_size; point* emptys; bool volatile foundSolution; bool volatile finishProgram; int volatile id_first; int convertChar(char c){ if (c == 'X') return 0; else return c - '0'; } void readMatrixFromFile(){ FILE *fin = fopen ("sudoku-c.in", "r"); int i,j; char c; for (i=0; i<ORDER; ++i){ for(j=0; j<ORDER; ++j){ fscanf(fin," %c",&c); matrix[i][j] = convertChar(c); } } } void printMatrix(int m[][ORDER]){ int i,j; for (i=0; i<ORDER; ++i){ for(j=0; j<ORDER; ++j){ printf("%d ",m[i][j]); } printf("\n"); } } void setArrayWithEmptyPositions(){ emptys = malloc(sizeof(point)*(ORDER*ORDER)); emptys_size = 0; int i,j; for(i=0; i<ORDER; ++i){ for(j=0; j<ORDER; ++j){ if(matrix[i][j] == 0){ point p; p.x = i; p.y = j; emptys[emptys_size++] = p; } } } } point getPositionForStartPosition(int pos, int startPos){ point actuallyPos = emptys[(pos + startPos)%emptys_size]; return actuallyPos; } bool checkRow(int m[][ORDER], int row, int value){ int j; for(j=0; j<ORDER; ++j) if (m[row][j] == value) return false; return true; } bool checkColumn(int m[][ORDER], int column, int value){ int i; for(i=0; i<ORDER; ++i) if (m[i][column] == value) return false; return true; } bool checkQuadrant(int m[][ORDER], point pos, int value){ int row = pos.x; int column = pos.y; int order_sqrt = sqrt(ORDER); int initialRowPosition = row/order_sqrt * order_sqrt; int initialColumnPosition = column/order_sqrt * order_sqrt; int i,j; for(i = initialRowPosition; i < initialRowPosition + order_sqrt; ++i) for(j = initialColumnPosition; j < initialColumnPosition + order_sqrt; ++j) if(m[i][j] == value) return false; return true; } bool isInsertionValid(int m[][ORDER], point p, int value){ return ( checkRow(m,p.x,value) && checkColumn(m,p.y,value) && checkQuadrant(m,p,value) ); } void solveRec(int m[][ORDER], int startPos, int num_pos, int value){ point p = getPositionForStartPosition(num_pos, startPos); if(!foundSolution){ for(;value<=ORDER && !isInsertionValid(m,p,value); ++value); if(value <= ORDER){ m[p.x][p.y] = value; if(num_pos + 1 >= emptys_size){ id_first = startPos; foundSolution = true; // JA FINALIZEI O PREECHIMENTO } else{ solveRec(m,startPos,num_pos + 1,1); //VOLTA if(!foundSolution){ value = m[p.x][p.y] + 1; m[p.x][p.y] = 0; solveRec(m,startPos,num_pos,value); } } } } } void* solveSudoku(void* start){ int matrix_copy[ORDER][ORDER]; int i,j; int startPosition = *((int*)start); for(i=0; i<ORDER; ++i){ for(j=0; j<ORDER; ++j){ matrix_copy[i][j] = matrix[i][j]; } } double clockA = clock(); solveRec(matrix_copy, startPosition,0,1); if (!foundSolution && id_first == -1){ id_first = startPosition; printf("\nMATRIZ INVALIDA! A THREAD PARTINDO DA POSICAO %d FOI A PRIMEIRA A CONSTATAR! (%lf s) \n\n",startPosition,(clock()-clockA)/CLOCKS_PER_SEC); finishProgram = true; } else if(foundSolution && id_first == startPosition){ printf("\nA THREAD PARTINDO DA POSICAO %d FOI A PRIMEIRA A TERMINAR! (%lf s) \n\n",startPosition,(clock()-clockA)/CLOCKS_PER_SEC); printMatrix(matrix_copy); finishProgram = true; } return NULL; } int main(){ readMatrixFromFile(); printMatrix(matrix); setArrayWithEmptyPositions(); finishProgram = false; pthread_t thr[emptys_size]; int starts[emptys_size]; id_first = -1; int startPos; for(startPos=0; startPos<emptys_size; ++startPos){ starts[startPos] = startPos; pthread_create(&thr[startPos],NULL,solveSudoku,(void*) &starts[startPos]); } while(!finishProgram); return 0; }
C
3.6 Loops - Do -While itoa : 숫자를 문자로 변환하는 프로그램 #include <stdio.h> //함수정의 : 정수n과 문자형배열s를 인자로 가지고 있는 itoa함수 void itoa (int n, char s[]) { //변수 i는 do문의 인덱스 값으로 시작 위치값을 알려준다 //변수 sign는 변환하고자 하는 정수값을 가지고있다 int i, sign; // 배열개수n을 sign에 저장시킨 값이 0보다 작으면 -n을 n에 저장시켜라 // 음수이면 양수로 만든다 if ((sign = n) < 0) n = -n; // i의 시작값을 0으로 해준다 i=0; //역순으로 숫자를 생성한다 if ((sign = n) < 0) n = -n; //배열s의 i가하나 증가된 위치에 정수n을 10으로 나눈 값의 기수에 캐릭턱'0'수를 더한다 do { s[i++] = n % 1 + '0'; } // 정수 n에 n을 10으로 나눈 값을 넣은 n이 0보다 크면 계속 실행한다 while ((n /= 10) >0); //sign이 0보다 작으면 '-'를 s배열 i를 하나 증가 시킨 자리에 저장한다 if(sign <0) s[i++] = '-'; //s열 i번째에 null을 저장하라 s[i] = '\0'; //reverse 함수에 s를 넣어라 reverse(s); }
C
/* COMPILE WITH -lreadline you'll also need to install libreadline-dev */ #include "hash-table.h" #include <stdio.h> #include <stdlib.h> #include <readline/readline.h> #include <readline/history.h> int _main(table t) { char *line, *instr, *key, *val; node *n; while ((line = readline("> ")) != NULL) { instr = strtok(line, " "); if (instr == NULL) return 0; if (strcmp(instr, "i") == 0) { key = strtok(NULL, " "); val = strtok(NULL, " "); if (key == NULL || val == NULL) return 1; if (insert(t, key, val) == NULL) return -1; } else if (strcmp(instr, "l") == 0) { if ((key = strtok(NULL, " ")) == NULL) return 1; if ((n = lookup(t, key)) == NULL) { printf("Not found \n"); } else { printf("%s\n", n->val); } } else { return 1; } free(line); } return 0; } int main(void) { int m; table t = init_table(); while ((m = _main(t)) == 1) { printf("Usage error\n" "Each line should be either \n" "\t'i <key> <val>' for insert or \n" "\t'l <key>' for lookup\n"); } if (m == -1) { printf("Memory error\n"); } free_table(t); return m; }
C
#include "holberton.h" /** * reverse_array - Short description, single line * @a: Description of parameter n * @n: Description of parameter n * Return: 0 */ void reverse_array(int *a, int n) { int i = n - 1, j = 0, tmp = 0, tmp2 = 0; for ( ; i > (n / 2); i--, j++) { tmp = a[i]; tmp2 = a[j]; a[i] = tmp2; a[j] = tmp; } }
C
#include <stdio.h> #include <stdlib.h> int main() { int i =10; int *ptr_i = &i; int **ptr_pi = &ptr_i; printf("The value at pointer of i is : %d\n",*ptr_i); printf("The address at pointer of i is %u \n", ptr_i); printf("The value of pointer of pointer of i at 2* is : %d\n",**ptr_pi); printf("The value of pointer of pointer of i at 1* is : %d\n",*ptr_pi); printf("The address at pointer to pointer of i is : %u\n",ptr_pi); return 0; }
C
#include "kernel/param.h" #include "kernel/types.h" #include "kernel/stat.h" #include "user/user.h" #include "kernel/fs.h" #include "kernel/fcntl.h" #include "kernel/syscall.h" #include "kernel/memlayout.h" #include "kernel/riscv.h" // // Tests xv6 system calls. usertests without arguments runs them all // and usertests <name> runs <name> test. The test runner creates for // each test a process and based on the exit status of the process, // the test runner reports "OK" or "FAILED". Some tests result in // kernel printing usertrap messages, which can be ignored if test // prints "OK". // #define BUFSZ ((MAXOPBLOCKS+2)*BSIZE) char buf[BUFSZ]; void func(){ printf("user_sig_test succsess\n"); } void func2(){ for(;;){printf("");} } void func3(){ printf("intterupt\n"); } void user_sig_test_failsignum(char *s){ struct sigaction new; struct sigaction old; new.sa_handler=(void*)&func; new.sigmask = 0; if(sigaction(50,&new,&old) >= 0){ printf("sigaction faild\n"); exit(1); } } void user_sig_test_kill(char *s){ struct sigaction new; struct sigaction old; new.sa_handler=(void*)&func; new.sigmask = 0; if (sigaction(2,&new,&old) < 0){ printf("sigaction faild\n"); exit(1); } if(kill(getpid(),2) < 0){ printf("kill faild\n"); exit(1); } } void user_sig_test_multiprocsignals(char *s){ int pid= fork(); if(pid == 0){ struct sigaction new; struct sigaction old; new.sa_handler=(void*)&func; new.sigmask = 0; if (sigaction(2,&new,&old) < 0){ printf("sigaction faild\n"); exit(1); } }else{ if(kill(pid,2) < 0){ printf("kill faild\n"); exit(1); } wait(0); } } void user_sig_test_restore(char *s){ struct sigaction new; struct sigaction old; struct sigaction old2; new.sa_handler=(void*)&func; new.sigmask = 0; if (sigaction(2,&new,&old) < 0){ printf("sigaction faild\n"); exit(1); } if(sigaction(2,&old,&old2) < 0){ printf("kill faild\n"); exit(1); } if(old2.sa_handler != new.sa_handler){ printf("restore faild\n"); exit(1); } } // if stuck here the test fails. void kernel_sig_test_ignore(char *s){ sigprocmask((1<<SIGSTOP)); if(kill(getpid(),SIGSTOP) < 0){ printf("kill faild\n"); exit(1); } } void kernel_sig_test_stop_cont(char *s){ int pid = fork(); if(pid < 0){ printf("fork failed\n"); exit(1); } if(pid == 0){ kill(getpid(),SIGSTOP); sleep(10); exit(1); }else{ int status; sleep(50); kill(pid,SIGCONT); wait(&status); } } void kernel_sig_test_failignorekill(char *s){ struct sigaction new; struct sigaction old; new.sa_handler=(void*)&func; new.sigmask=0; if(sigaction(SIGKILL,&new,&old) >= 0){ printf("sigaction failed\n"); exit(1); } if(sigaction(SIGKILL,&new,0) >= 0){ printf("sigaction failed\n"); exit(1); } if(sigaction(SIGKILL,0,&old) >= 0){ printf("sigaction failed\n"); exit(1); } } void final_sig_test(char *s){ struct sigaction new; struct sigaction old; new.sa_handler=(void*)&func2; new.sigmask=0; struct sigaction new2; struct sigaction old2; new2.sa_handler=(void*)&func3; new2.sigmask=0; int pid = fork(); if (pid < 0){ printf("fork failed\n"); exit(1); } if(pid == 0){ if(sigaction(2,&new,&old) < 0) { printf("sigaction failed\n"); exit(1); } if(sigaction(7,&new2,&old2) < 0) { printf("sigaction failed\n"); exit(1); } if(kill(getpid(),2) < 0){ printf("kill failed\n"); exit(1); } }else{ sleep(10); if(kill(pid,7) < 0){ printf("kill failed\n"); exit(1); } sleep(10); kill(pid,SIGKILL); } } // // use sbrk() to count how many free physical memory pages there are. // touches the pages to force allocation. // because out of memory with lazy allocation results in the process // taking a fault and being killed, fork and report back. // int countfree() { int fds[2]; if(pipe(fds) < 0){ printf("pipe() failed in countfree()\n"); exit(1); } int pid = fork(); if(pid < 0){ printf("fork failed in countfree()\n"); exit(1); } if(pid == 0){ close(fds[0]); while(1){ uint64 a = (uint64) sbrk(4096); if(a == 0xffffffffffffffff){ break; } // modify the memory to make sure it's really allocated. *(char *)(a + 4096 - 1) = 1; // report back one more page. if(write(fds[1], "x", 1) != 1){ printf("write() failed in countfree()\n"); exit(1); } } exit(0); } close(fds[1]); int n = 0; while(1){ char c; int cc = read(fds[0], &c, 1); if(cc < 0){ printf("read() failed in countfree()\n"); exit(1); } if(cc == 0) break; n += 1; } close(fds[0]); wait((int*)0); return n; } // run each test in its own process. run returns 1 if child's exit() // indicates success. int run(void f(char *), char *s) { int pid; int xstatus; printf("%s: \n", s); if((pid = fork()) < 0) { printf("runtest: fork error\n"); exit(1); } if(pid == 0) { f(s); exit(0); } else { wait(&xstatus); if(xstatus != 0) printf("FAILED\n"); else printf("OK\n"); return xstatus == 0; } } int main(int argc, char *argv[]) { int continuous = 0; char *justone = 0; if(argc == 2 && strcmp(argv[1], "-c") == 0){ continuous = 1; } else if(argc == 2 && strcmp(argv[1], "-C") == 0){ continuous = 2; } else if(argc == 2 && argv[1][0] != '-'){ justone = argv[1]; } else if(argc > 1){ printf("Usage: usertests [-c] [testname]\n"); exit(1); } struct test { void (*f)(char *); char *s; } tests[] = { {user_sig_test_failsignum, "user_sig_test_failsignum"}, {user_sig_test_kill, "user_sig_test_kill"}, {user_sig_test_multiprocsignals, "user_sig_test_multiprocsignals"}, {user_sig_test_restore, "user_sig_test_restore"}, {kernel_sig_test_ignore, "kernel_sig_test_ignore"}, {kernel_sig_test_stop_cont, "kernel_sig_test_stop_cont"}, {kernel_sig_test_failignorekill, "kernel_sig_test_failignorekill"}, {final_sig_test, "final_sig_test"}, { 0, 0}, }; if(continuous){ printf("continuous usertests starting\n"); while(1){ int fail = 0; int free0 = countfree(); for (struct test *t = tests; t->s != 0; t++) { if(!run(t->f, t->s)){ fail = 1; break; } } if(fail){ printf("SOME TESTS FAILED\n"); if(continuous != 2) exit(1); } int free1 = countfree(); if(free1 < free0){ printf("FAILED -- lost %d free pages\n", free0 - free1); if(continuous != 2) exit(1); } } } printf("sig_usertests starting\n"); int free0 = countfree(); int free1 = 0; int fail = 0; for (struct test *t = tests; t->s != 0; t++) { if((justone == 0) || strcmp(t->s, justone) == 0) { if(!run(t->f, t->s)) fail = 1; } } if(fail){ printf("SOME TESTS FAILED\n"); exit(1); } else if((free1 = countfree()) < free0){ printf("FAILED -- lost some free pages %d (out of %d)\n", free1, free0); exit(1); } else { printf("ALL TESTS PASSED\n"); exit(0); } }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> int main(){ int loop=0; FILE * file; char filename[255]; char str[1024]; printf("Veuillez introduire le nom de fichier\n"); scanf(" %[^\n]",filename); file = fopen(filename,"w"); if(file != NULL){ fclose(file); }else{ printf("erreur de lecture"); return 0; } while(loop ==0){ fopen(filename,"a"); printf("Veuillez saisir une phrase : \n"); scanf(" %[^\n]",str); if(strcmp(str,"")==0){ printf("erreur dans la valeur introduite\n"); loop=1; }else{ fputs(str,file); fclose(file); strcpy(str, ""); } } return 0; }
C
#include <unistd.h> #include <stdio.h> int main(void) { int pid; pid = get_plog_size(); printf("returned: %d\n",pid); return 0; }
C
#include<stdio.h> int main() { //&연산자 &(주소값을 계산할 데이터) /*int* p; int a; p = &a; printf("%p", p);*/ /*int a; a = 2; printf("%p", &a);*/ /*int* p; int a; p = &a; printf("포인터 p에 들어 있는 값 : %x \n", p); printf("int 변수 a 가 저장된 주소 : %x \n", &a); printf("int 변수 a 가 저장된 주소 : %x \n", &a+1);*/ //*연산자의 이용 //int* p; //int a; //p = &a; //a = 2; //printf("a 의 값 : %d \n", a); //printf("*p 의 값 : %d \n", *p); //printf("*p 의 값 : %p \n", *p); //printf("*p 의 값 : %d \n", p); //printf("*p 의 값 : %p \n", p); //*연산자 (나를 나에게 저장된 주소값에 위치한 데이터) //int* p; //int a; //p = &a; //*p = 3; //printf("a 의 값 : %d \n", a); //printf("*p 의 값 : %d \n", *p); //int p; //int a; //p = &a; //a = 3; //printf("*p 의 값? : %d \n", *p); //간접 참조가 잘못되어 있다. //printf("*p 의 값? : %d \n", p); //이렇게 해야한다~~ //포인터도 변수이다. /*int a, b; int* p; p = &a; *p = 2; p = &b; *p = 4; 포인터도 변수 이다 즉, 포이†� 들어간 주소값이 바뀔 수 있다는 것이다. a -> b로 주소값이 바뀔 수 있다. printf("a : %d \n", a); printf("b : %d \n", b);*/ //상수 포인터 //int a, b; //const int* pa = &a; ////*pa = 3; //올바르지 않은 문장 //pa = &b; //올바른 문장 //int* const pa = &a; //*pa = 3; // 올바른 문장 //pa = &b; //올바르지 않은 문장 //const int* const pa = &a; //*pa = 3; // 둘다 올바르지 않다. //pa = &b; //포인터의 덧셈 //int a; //int* pa; //pa = &a; //printf("pa의 값 : %d \n", pa); //int가 4비트 이므로 더해짐 //printf("(pa + 1) 의 값 : %d \n", pa + 1); //int a; //char b; //double c; //int* pa = &a; //char* pb = &b; //double* pc = &c; //printf("pa 의 값 : %d \n", pa); // int는 4비트 //printf("(pa + 1) 의 값 : %d \n", pa + 1); //printf("pb 의 값 : %d \n", pb); // char은 1비트 //printf("(pb + 1) 의 값 : %d \n", pb + 1); //printf("pc 의 값 : %d \n", pc); // double은 8비트 //printf("(pc + 1) 의 값 : %d \n", pc + 1); //포인터 뺄셈 //int a; //int* pa = &a; //printf("pa 의 값 : %d \n", pa); //printf("(pa - 1) 의 값 : %d \n", pa - 1); //포인터의 대입 /*int a; int* pa = &a; int* pb; *pa = 3; pb = pa; printf("pa 가 가리키고 있는 것 : %d \n", *pa); printf("pb 가 가리키고 있는 것 : %d \n", *pb);*/ //배열 /*int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; int i; for (i = 0; i < 10; i++) { printf("arr[%d] 의 주소값 : %d \n", i + 1, &arr[i]); }*/ /*int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; int* parr; int i; parr = &arr[0]; for (i = 0; i < 10; i++) { printf("arr[%d] 의 주소값 ; %x ", i, &arr[i]); printf("(parr + %d) 의 값 : %x ", i, (parr + i)); if (&arr[i] == (parr + i)) { printf("--> 일치 \n"); } else { printf("--> 불일치 \n"); } }*/ /*int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; int* parr; int i; parr = &arr[0]; for (;;) { printf("값을 입력하시오"); scanf_s("%d", &i); printf("arr[i] = %d, *(parr + i) = %d \n", arr[i], *(parr + i)); if (i == 10) break; }*/ //1차원 배열 가리키기 /*int arr[3] = { 1,2,3 }; int* parr; parr = arr; printf("arr[1] : %d \n", arr[1]); printf("parr[1] : %d \n", parr[1]);*/ //int arr[10] = { 100, 98, 97, 95, 89, 76, 92, 96, 100, 99 }; //int* parr = arr; //int sum = 0; //while (parr - arr <= 9) { // sum += (*parr); // parr++; //} //printf("내 시험 점수 평균 : %d \n", sum / 10); /*int a; int* pa; int** ppa; pa = &a; ppa = &pa; a = 3; printf("a : %d // *pa : %d // **pa : %d \n", a, *pa, **ppa); printf("a : %d // pa : %d // *ppa : %d \n", &a, pa, *ppa); printf("&pa : %d // ppa : %d \n ", &pa, ppa);*/ //2차원 배열의 []연산자 /*int arr[2][3];*/ //printf("arr[0] : %x \n", arr[0]); //printf("&arr[0][0] : %x \n", &arr[0][0]); //printf("arr[1] : %x \n", arr[1]); //printf("&arr[1][0] : %x \n", &arr[1][0]); /*printf("arr[0] : %x \n", &arr[0]); printf("arr : %x \n", arr);*/ //1증가 /*int arr[2][3] = { {1,2,3,},{4,5,6,} }; printf("arr : %x, arr + 1 : %x \n", arr, arr + 1); */ //배열의 포인터 //int arr[2][3] = { {1,2,3},{4,5,6} }; //int(*parr)[3]; //parr = arr; //printf("parr[1][2] : %d, arr[1][2] : %d \n", parr[1][2], arr[1][2]); //배열 포인터 예제 //int arr[2][3] = { {1,2,3} , {4,5,6}}; //int brr[10][3]; //int crr[2][5]; //int(*parr)[3]; //parr = arr; //parr = brr; //parr = crr; //오류 열의 개수가 안맞음 //printf("%d, %d ", arr[1][2], parr[1][2] //포인터 배열 //int* arr[3]; //int a = 1, b = 2, c = 3; //arr[0] = &a; //arr[1] = &b; //arr[2] = &c; //printf("a : %d, *arr[0] : %d &a : %p \n", a, *arr[0], &a); //printf("b : %d, *arr[1] : %d &b : %p \n", b, *arr[1], &b); //printf("b : %d, *arr[2] : %d &c : %p \n", c, *arr[2], &c); //printf("&a : %p, *arr[0] : %d \n", &a, arr[0]); int* p = (int*)malloc(sizeof(int)); *p = 9; printf("&a :p, *arr[0] : %p \n", p); printf("&a : p, *arr[0] : %d \n", *p); printf("&a : p, *arr[0] : %p \n", &p); return 0; }
C
/*Escreva uma função que dado dois números retorne o maior.*/ int main(void) { int a, b; printf ("Digite um número:\t"); scanf ("%d", &a); printf ("Digite outro número:\t"); scanf ("%d", &b); if (a > b){ printf ("%d é maior", a); }else{ if ( b > a){ printf ("%d é maior", b); }else{ printf ("%d e %d são iguais", a, b); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *print_message_func( void *ptr ); int main() { pthread_t thread1, thread2; const char *msg1 = "Thread 1"; const char *msg2 = "Thread 2"; int ret1, ret2; ret1 = pthread_create( &thread1, NULL, print_message_func, (void *)msg1); if (ret1) { fprintf(stderr, "Pthread_create return value: %d\n", ret1); exit(EXIT_FAILURE); } ret2 = pthread_create( &thread2, NULL, print_message_func, (void *)msg2); if (ret2) { fprintf(stderr, "Pthread_create return value: %d\n", ret2); exit(EXIT_FAILURE); } pthread_join( thread1, NULL); pthread_join( thread2, NULL); exit(EXIT_SUCCESS); } void * print_message_func( void *ptr ) { char *msg; msg = (char *)ptr; fprintf(stdout, "%s \n", msg); }
C
#include<stdio.h> #include<conio.h> #include<alloc.h> struct node { int data; struct node *next; }; struct node *temp,*start,*head=0; int n; int ch; void main() { void cr(); void printlist(); while(1) { printf("\n\t\t\t MENU"); printf("\n \t\t----------"); printf("\n 1.CREATE NODE"); printf("\n 2.PRINTlIST"); printf("\n 3.Exit"); printf("\n\t Enter your choice(1-3);-"); fflush(stdin); scanf("%d",&ch); switch(ch) { case 1:cr(); break; case 2: printlist(); break; case 3: exit(1); break; default: printf("Invalid input"); } } getch(); } // Creat a link list void cr() { temp=(struct node *)malloc(sizeof(struct node)); if(temp==NULL) { printf("memoy not initialis;"); return ; } else { printf("Enter any no.:-"); scanf("%d",&n); temp->data=n; temp->next=NULL; if(head==0) { head=start=temp; } else { while(start->next!=NULL) { start=start->next; } start->next=temp; } } } //printf the link list void printlist() { start=head; printf("status of link list:"); while(start!=NULL) { n= start->data; start=start->next; printf("%d\n",n); } }
C
#include<stdio.h> #include<stdlib.h> #include"mckp.h" int P_inc,C_inc; int main(void){ int i; Fraction *t_profit; Vector **R; structures_init(); DP_prepare(); DP_solve(); R = MCKP_prepare(); solve(R); if( debug )printf("\n----------------------------Problem Solved!----------------------------\n\n"); t_profit = frac_init(P_inc,LCM); printf("\ntotal_profit="); print_frac(t_profit); printf(", total_cost=%d\n\n",C_inc); for(i=0;i<Num_Group;i++){ print_solution(DP_solutions[i]); putchar('\n'); } return 0; } void solve(Vector **R){ if( debug )printf("\n---------------------------------Solve---------------------------------\n\n"); int i,ifs_idx,P_cp=0; Vector **vec; Fraction *P_cpr,*W_cpr; vec = Algorithm1(R); //Algorithm1を実行 ifs_idx = R_feasible(R,&P_cpr,&W_cpr); //解として成立するか,しないならその原因のindex for(i=0;i<Num_Group;i++){ //繰り下げ解の準備 ifs_idx以外の和 if( i==ifs_idx ) continue; Node *node = (Node*)(vec[i]->data); P_cp += node->item->profit; } if( ifs_idx == Num_Group ){ //X_CP_r is integer? update(vec,NULL,Num_Group); free(vec); free(P_cpr); free(W_cpr); all_free(R); return ; } else if( ifs_idx == -1 ){ //W_cpr <= W ? no->retrun; P_cpr > P_inc ? no->return; free(vec); free(P_cpr); free(W_cpr); all_free(R); return; } Vector **R_left; //左問題のR 右問題はRを再利用 Node *right = (Node*)(vec[ifs_idx]->data),*left = (Node*)((vec[ifs_idx]->next)->data); //LP解の左右ノード Fraction *border,*min_slope,*max_slope,*cur_slope; //min_slopeはLP解の左側最小 max_slopeは右側最大 border = frac_plus( mul_int(right->x,right->item->weight) , mul_int(left->x,left->item->weight) ,1 ); if( debug ){ printf("border = "); print_frac(border); putchar('\n'); } min_max_slope(R,&min_slope,&max_slope,ifs_idx); //Rを辿り最大,最小の傾きを求める ifs_idxは除く cur_slope = right->slope; //left~rightの傾き if( debug ){ printf("Current slope : "); print_frac(cur_slope); putchar('\n'); } R_left = relaxation2(R,border,right,ifs_idx); //子問題のRを作成 Rは再利用に留意 無駄となるデータは削除 P_cp += ((Node*)(R_left[ifs_idx]->data))->item->profit; //整数近似解の完成 if( debug ){ printf("\nSeparate :\nRight Side--------------------\n"); for(i=0;i<Num_Group;i++){ print_nodes(R[i]); putchar('\n'); } printf("Left Side---------------------\n"); for(i=0;i<Num_Group;i++){ print_nodes(R_left[i]); putchar('\n'); } printf("------------------------------\n\n"); } //calc_penalty pq+ , pq- Fraction *penal_plus,*penal_minus; //子問題における価値の"上昇量" ->下落するためマイナス値 calc_penalty(R,R_left,&penal_plus,&penal_minus,border,max_slope,min_slope,cur_slope,ifs_idx); free(cur_slope); free(border); //cur_slope,borderはいらない ここでifs_idxのrightノードは不要な限り全て削除済み //max_slope,min_slopeはRのどこかの傾きであるためfreeしない if( cmp_left_over(penal_minus,penal_plus) ){ P_cpr=frac_plus(P_cpr,penal_minus,1); free(penal_plus); } else { P_cpr = frac_plus(P_cpr,penal_plus,1); free(penal_minus); } if( debug ){ printf("P_cpr="); print_frac(P_cpr); printf(", P_inc=%d\n\n",P_inc); } if( int_less_frac(P_inc,P_cpr) ){ //P_cp>P_inc if( P_cp > P_inc ) update(vec,left,ifs_idx); //update(P_inc); 繰り上げ価値 R_leftを暫定解とする free(P_cpr); free(W_cpr); free(vec); //二つの子問題をとく if( debug ) printf("Solve the Right Side"); solve(R); if( debug ) printf("Solve the Left Side"); solve(R_left); }else{ if( debug ) printf("More optimal solution is NOT exist at next problem.\n"); free(P_cpr); free(W_cpr); free(vec); all_free(R); all_free(R_left); } } Vector** MCKP_prepare(void){ int i; //Vector *vec_ptr; Vector **Rk; P_inc = 0; //近似解の価値の初期値は0ここから上げていく Rk = (Vector**)malloc(Num_Group*sizeof(Vector*)); for( i=0;i<Num_Group;i++){ Rk[i] = NULL; //vec_ptr = DP_solutions[i]; //Candidate List vec_append(&Rk[i],(void*)(node_init(null_item,frac_zero)));//null_nodeは使えない 個々のグループで特有のノード rx_left(&Rk[i],frac_inf,i); //INF以下とすることで全ての擬似アイテムをたどる if( debug ){ printf("\n----------------------------------------------------------------------\n"); printf("R[%d]'s Lelax.\n",i); print_nodes(Rk[i]); } } if( debug ) printf("-----------------------MCKP Programing : READY------------------------\n\n"); return Rk; } Vector** Algorithm1(Vector **R){ int i,w=0,w_bar,min_idx,yq; Node *node; Fraction *min; Vector **vec; vec = (Vector**)malloc(Num_Group*sizeof(Vector*)); for( i=0;i<Num_Group;i++ ){ vec[i] = R[i]; w += ((Node*)(vec[i]->data))->item->weight; //重み和 } w_bar = w-Max_W; //改善するべき重み if( w_bar <= 0 ){ return vec; } //これ以上の改善はない while(1){ min_idx = -1; min=frac_inf; yq=0; for( i=0;i<Num_Group;i++ ){ //傾き最小を見つける node = (Node*)(vec[i]->data); if( node->slope == frac_inf ) continue; //傾きがINFならその次にノードが存在しない if( cmp_left_over(min,node->slope) ){ min_idx = i; min = node->slope; yq = node->width; } } if( min_idx==-1 ){ //解なし all x->0 総価値が0という扱い Rk_feasibleでは-1が返る if( debug )printf("This problem has no solution.\n"); for(i=0;i<Num_Group;i++){ ((Node*)(vec[i]->data))->x = frac_zero; } return vec; } else if( w_bar==yq ){ //frac_one,frac_zeroの特殊ケース ((Node*)(vec[min_idx]->data))->x = frac_zero; vec[min_idx] = vec[min_idx]->next; ((Node*)(vec[min_idx]->data))->x = frac_one; return vec; } else if( (w_bar-yq) < 0 ){ //LP解が得られた ((Node*)(vec[min_idx]->data))->x = frac_init( yq-w_bar , yq ); ((Node*)((vec[min_idx]->next)->data))->x = frac_init( w_bar , yq ); return vec; //vec[min_idx]はrightのアドレス } else{ w_bar -= yq; ((Node*)(vec[min_idx]->data))->x = frac_zero; vec[min_idx] = vec[min_idx]->next; ((Node*)(vec[min_idx]->data))->x = frac_one; } } } int R_feasible(Vector **R,Fraction **t_profit,Fraction **t_cost){ int ifs_idx=-1,i,flag; *t_profit = frac_init(0,1); *t_cost = frac_init(0,1); for( i=0;i<Num_Group;i++ ){ Fraction *profit,*cost; flag = Rk_pandc(R[i],&profit,&cost); //flagが1なら全ての係数が1または0で整数解 if( debug ){ print_nodes(R[i]); printf("total: profit->"); print_frac(profit); putchar(' '); printf(" cost->"); print_frac(cost); printf("\n"); } *t_profit = frac_plus(*t_profit,profit,1); *t_cost = frac_plus(*t_cost,cost,1); if( flag==0 ){ ifs_idx = i; if( debug ) printf("Not Integer\n"); } if( debug ) putchar('\n'); } if( debug ){ printf("\nLP Total: profit->"); print_frac(*t_profit); putchar(' '); printf(" cost->"); print_frac(*t_cost); putchar('\n'); } if( int_less_frac(Max_W,*t_cost) || int_less_frac(P_inc,*t_profit)==0 ){ if( debug ) printf("INFEASIBLE Max_W < total_cost:%d, P_inc < t_profit:%d\n",int_less_frac(Max_W,*t_cost),int_less_frac(P_inc,*t_profit) ); return -1; }else if( ifs_idx==-1 ){ if( debug ) printf("All conditions are met.\n"); return Num_Group; }else{ if( debug )printf("Class%d is not Integer.\n",ifs_idx); return ifs_idx; } } Vector** relaxation2(Vector **R,Fraction *border,Node *right,int group){ int i; Vector *R_right,**R_left,*vec; //return R_left; right,leftは必ず存在 Node *node; R_right = R[group]; R_left = (Vector**)malloc(Num_Group*sizeof(Vector*)); for(i=0;i<Num_Group;i++){ if( i==group ) continue; R_left[i] = copy_R(R[i]); ((Node*)(R[i]->data))->x = frac_one; } if( (Node*)(R_right->data) != right ){ //R_rightのnextがrightになるまで while( (Node*)((R_right->next)->data) != right){ R_right = R_right->next; } //R_leftはR_rightの隣の隣 R_left[group] = (R_right->next)->next; vec = R_right->next; node = (Node*)(vec->data); free(node->x); free(node); free(vec); R_right->next = NULL; //next->node->x とnext->nodeはfreeしてOK vectorとしてもいらん slopeはcur_slope }else{ R_left[group] = R_right->next; node = (Node*)(R_right->data); free( node->x ); //xを再定義する必要がないのはこのノードが先頭だからである R_right->next = NULL; //node->xはいらない node自体は再利用 vectorも再利用 } vec = R_left[group]; node=(Node*)(vec->data); free(node->x); //ここでright,leftのxは二つとも消えているとしていい さらにR[group]の先頭xはfrac_oneに ((Node*)(R[group]->data))->x = frac_one; //分離完了 rx_right(R_right,border,group); //先頭が変わらない rx_left(&R_left[group],border,group); //先頭が変わる return R_left; } void rx_right(Vector *R,Fraction *border,int group){ Vector *Nk=DP_solutions[group] ; Vector *n,*nn; Node *node,*pre_node; Item *right = ((Node*)(R->data))->item; //rightになるまで進める rightの次から判断すればよい while( ((Candidate*)(Nk->data))->item != right ){ Nk=Nk->next; } n = Nk->next; //nはNULLにならない Item *first=right,*second=((Candidate*)(n->data))->item,*third; while( (int_less_frac(second->weight,border))==0 ){ //second==borderの場合も入る nn = n->next; third=((Candidate*)(nn->data))->item; //nnはNULLにならない if( int_less_frac(third->weight,border) ){ node = node_init(second,frac_zero); vec_append(&R,(void*)node); break; } else if( turn_left(first,second,third) ){ node = node_init(second,frac_zero); vec_append(&R,(void*)node); first = second; } n=nn; second=third; } pre_node = (Node*)(R->data); if( R->next == NULL ) pre_node->width = 0; while( R->next!=NULL ){ R = R->next; node = (Node*)(R->data); //pre_nodeのy,rを計算 pre_node->width = (pre_node->item->weight) - (node->item->weight); pre_node->slope = frac_init( ( pre_node->item->profit - node->item->profit ),pre_node->width); pre_node = node; } pre_node->slope = frac_inf; //最後は傾き無限大 } void rx_left(Vector **R,Fraction *border, int group){ Vector *Nk=DP_solutions[group], *left_add=NULL; Item *left = ((Node*)((*R)->data))->item; Vector *n,*nn; Node *node,*pre_node; //Nk < border while( int_less_frac( ((Candidate*)(Nk->data))->item->weight,border) == 0 ){ Nk=Nk->next; } Item *first=( (Candidate*)(Nk->data) )->item,*second,*third; if( first==left ){ ((Node*)((*R)->data))->x=frac_one; return ;} //left_nodeのx=frac_zeroが確定 ((Node*)((*R)->data))->x=frac_zero; node = node_init(first,frac_one); //firstに対応するNodeを作成 vec_prepend(&left_add,(void*)node); n = Nk->next; //nはNULLにならない first!=left second = ( (Candidate*)(n->data) )->item; while( second!=left ){ nn = n->next; third=((Candidate*)(nn->data))->item; //nnはNULLにならない if( turn_left(first,second,third) ){ node = node_init(second,frac_zero); vec_prepend(&left_add,(void*)node); first = second; } n=nn; second = third; } pre_node=(Node*)((*R)->data); while( left_add!=NULL ){ node = (Node*)(left_add->data); //nodeのy,rを計算 node->width = (node->item->weight) - (pre_node->item->weight); node->slope = frac_init( ( node->item->profit - pre_node->item->profit ),node->width); vec_prepend(R,(void*)node); vec_predel(&left_add); pre_node = node; } } Vector* copy_R(Vector *R){ Vector *vec,*cp_vec=NULL; Node *node,*cp_node; Fraction *slope; vec= R; while(vec!=NULL){ node = (Node*)(vec->data); if( node->x == frac_one ) node->x = frac_zero; //R側のxを初期化 if文である必要はないが1以外でのデバッグにはなる cp_node = node_init(node->item,frac_zero); cp_node->width = node->width; slope = node->slope; if( slope==frac_inf ) cp_node->slope = frac_inf; //傾きはノードごとに変化するので注意 else cp_node->slope = frac_init(slope->molecule,slope->denominator); vec_append(&cp_vec,(void*)cp_node); vec = vec->next; } ((Node*)(cp_vec->data))->x = frac_one; //先頭xを1に return cp_vec; } int Rk_pandc(Vector *Rk,Fraction **r_profit,Fraction **r_cost){ *r_profit = frac_init(0,1); *r_cost = frac_init(0,1); //消される運命 int flag = 1; while( Rk!=NULL ){ Node *node = (Node*)(Rk->data); Item *item = node->item; if( node->x!=frac_zero ){ Fraction *p_trans,*c_trans; p_trans = mul_int(node->x,item->profit); c_trans = mul_int(node->x,item->weight); *r_profit = frac_plus(*r_profit,p_trans,1); *r_cost = frac_plus(*r_cost,c_trans,1); if( node->x!=frac_one ) flag = 0; else { return flag; } } Rk = Rk->next; } return flag; } void min_max_slope(Vector **R,Fraction **min,Fraction **max,int group){ int i; Vector *vec; Node *node; *min = frac_inf; *max = frac_zero; for(i=0;i<Num_Group;i++){ if( i==group ) continue; vec = R[i]; node = (Node*)(vec->data); if( node->x==frac_one ){ if( cmp_left_over(*min,node->slope) )*min=node->slope; continue; } while( ((Node*)(vec->next))->x == frac_zero ){ vec = vec->next; node=(Node*)(vec->data); } if( cmp_left_over(node->slope,*max) ) *max=node->slope; vec = vec->next; node=(Node*)(vec->data); if( cmp_left_over(*min,node->slope) ) *min=node->slope; } if( debug ){ printf("Max-slope="); print_frac(*max); printf(" Min-slope="); print_frac(*min); putchar('\n'); } } void calc_penalty(Vector **R,Vector **R_left,Fraction **penal_plus,Fraction **penal_minus,Fraction *border,Fraction *max_slope,Fraction* min_slope,Fraction *cur_slope,int ifs_idx){ Vector *min_right=R[ifs_idx],*max_left=R_left[ifs_idx]; while( min_right->next != NULL ){ min_right = min_right->next; } if( debug ){ printf("Right Min : \n"); print_node((Node*)(min_right->data)); printf("Left Max : \n"); print_node((Node*)(max_left->data)); } Node *right_min=(Node*)(min_right->data), *left_max=(Node*)(max_left->data); Fraction *range,*tmp; tmp = frac_init(left_max->item->weight,1); //print_frac(tmp); putchar('\n'); range = frac_minus(border , tmp); free(tmp); //print_frac(range); putchar('\n'); tmp = frac_minus(max_slope , cur_slope); //printf("%p ",&tmp); print_frac(tmp); putchar('\n'); *penal_minus = frac_mul(range,tmp); free(range); free(tmp); tmp = frac_init(right_min->item->weight,1); //print_frac(tmp); putchar('\n'); range = frac_minus(border,tmp); free(tmp); //print_frac(range); putchar('\n'); tmp = frac_minus(min_slope,cur_slope); //print_frac(tmp); putchar('\n'); *penal_plus = frac_mul(range,tmp); free(range); free(tmp); if( debug ){ printf("P_minus = "); print_frac(*penal_minus); putchar(' '); printf("P_plus = "); print_frac(*penal_plus); putchar('\n'); } } void update(Vector **R,Node *left,int ifs_idx){ int i,t_profit=0,t_cost=0; Vector *Nk; for(i=0;i<Num_Group;i++){ Item *item; Nk=DP_solutions[i]; if( i!=ifs_idx ){ item = ((Node*)(R[i]->data))->item; } else{ item = left->item; } while( ((Candidate*)(Nk->data))->item != item ){ ((Candidate*)(Nk->data))->use=0; Nk=Nk->next; } t_profit += (item->profit); t_cost += (item->weight); ((Candidate*)(Nk->data))->use=1; Nk=Nk->next; while( Nk!=NULL ){ ((Candidate*)(Nk->data))->use=0; Nk=Nk->next; } } P_inc = t_profit; C_inc = t_cost; if( debug ) printf("Update : total_profit=%d, total_cost=%d\n",t_profit,t_cost); } void all_free(Vector **R){ int i; if( debug )printf("All Free R----------------\n"); for(i=0;i<Num_Group;i++){ while( R[i]!=NULL ){ //R_leftではnull_nodeじゃない可能性 if( debug ){ printf("free: %p\n",R[i]); print_node((Node*)(R[i]->data)); } Node *node=(Node*)(R[i]->data); if( node->x!=frac_zero && node->x!=frac_one ) free(node->x); if( node->slope!=frac_inf ) free(node->slope); if( node!=null_node ) free(node); vec_predel(&R[i]); } } if( debug )printf("All Free END--------------\n"); }
C
#include "util.h" enum { DT_UNKNOWN = 0, # define DT_UNKNOWN DT_UNKNOWN DT_FIFO = 1, # define DT_FIFO DT_FIFO DT_CHR = 2, # define DT_CHR DT_CHR DT_DIR = 4, # define DT_DIR DT_DIR DT_BLK = 6, # define DT_BLK DT_BLK DT_REG = 8, # define DT_REG DT_REG DT_LNK = 10, # define DT_LNK DT_LNK DT_SOCK = 12, # define DT_SOCK DT_SOCK DT_WHT = 14 # define DT_WHT DT_WHT }; #define SYS_WRITE 4 #define SYS_READ 3 #define SYS_OPEN 5 #define SYS_CLOSE 6 #define SYS_GETDENTS 141 #define STDERR 2 #define STDOUT 1 #define STDIN 0 #define O_RDONLY 0 #define O_WRONLY 1 #define O_CREAT 64 extern int system_call(); extern void infection(void); extern void infector(char* name); struct linux_dirent { unsigned long d_ino; /* Inode number */ unsigned long d_off; /* Offset to next linux_dirent */ unsigned short d_reclen; /* Length of this linux_dirent */ char d_name[]; /* Filename (null-terminated) */ }; char* getType(char d_type) { char* type = (d_type == DT_REG) ? "regular" : (d_type == DT_DIR) ? "directory" : (d_type == DT_FIFO) ? "FIFO" : (d_type == DT_SOCK) ? "socket" : (d_type == DT_LNK) ? "symlink" : (d_type == DT_BLK) ? "block dev" : (d_type == DT_CHR) ? "char dev" : "???"; return type; } void printWithPrefix(char prefix) { const int BUF_SIZE = 8192; long bpos; int folderDescriptor,writeSucces; long nread; char buf[BUF_SIZE]; struct linux_dirent *d; char d_type; folderDescriptor = system_call(SYS_OPEN,".", O_RDONLY,0777); if (folderDescriptor < 0) { system_call(1,0x55,"",""); } nread = system_call(SYS_GETDENTS, folderDescriptor, buf, BUF_SIZE); if(nread < 0) { system_call(1,0x55,"",""); } for (bpos = 0; bpos < nread;) { d = (struct linux_dirent *) (buf + bpos); if(d->d_name[0] == prefix) { writeSucces = system_call(SYS_WRITE,STDOUT,d->d_name,strlen(d->d_name)); if(writeSucces != strlen(d->d_name)){ system_call(SYS_CLOSE,folderDescriptor,"",""); system_call(1,0x55,"",""); } system_call(SYS_WRITE,STDOUT," ",2); d_type = *(buf + bpos + d->d_reclen - 1); char* type = getType(d_type); writeSucces = system_call(SYS_WRITE,STDOUT,type,strlen(type)); if(writeSucces < 0) { system_call(SYS_CLOSE,folderDescriptor,"",""); system_call(1,0x55,"",""); } system_call(SYS_WRITE,STDOUT,"\n",1); } bpos += d->d_reclen; } system_call(SYS_CLOSE,folderDescriptor,"",""); } void printWithoutPrefix() { const int BUF_SIZE = 8192; long bpos; int folderDescriptor,writeSucces; long nread; char buf[BUF_SIZE]; struct linux_dirent *d; char d_type; folderDescriptor = system_call(SYS_OPEN,".", O_RDONLY,0777); if (folderDescriptor < 0) { system_call(1,0x55,"",""); } nread = system_call(SYS_GETDENTS, folderDescriptor, buf, BUF_SIZE); if(nread < 0) { system_call(1,0x55,"",""); } for (bpos = 0; bpos < nread;) { d = (struct linux_dirent *) (buf + bpos); writeSucces = system_call(SYS_WRITE,STDOUT,d->d_name,strlen(d->d_name)); if(writeSucces != strlen(d->d_name)){ system_call(SYS_CLOSE,folderDescriptor,"",""); system_call(1,0x55,"",""); } system_call(SYS_WRITE,STDOUT," ",2); d_type = *(buf + bpos + d->d_reclen - 1); char* type = getType(d_type); writeSucces = system_call(SYS_WRITE,STDOUT,type,strlen(type)); if(writeSucces < 0) { system_call(SYS_CLOSE,folderDescriptor,"",""); system_call(1,0x55,"",""); } system_call(SYS_WRITE,STDOUT,"\n",1); bpos += d->d_reclen; } system_call(SYS_CLOSE,folderDescriptor,"",""); } int main (int argc , char* argv[], char* envp[]) { infection(); infector("exp"); return 0; }
C
/* * thread.c * * Created on: Apr 27, 2018 * Author: j.zh */ #include "thread.h" #include "lteLogger.h" // ------------------------------- int ThreadCreate(void* pEntryFunc, ThreadHandle* pThreadHandle, ThreadParams* pThreadParams) { #ifdef OS_LINUX if (pThreadHandle == 0 || pEntryFunc == 0) { LOG_ERROR(ULP_LOGGER_NAME, "NULL pointer\n"); return 1; } pthread_attr_t attr; int ret = pthread_attr_init(&attr); if (ret != 0) { LOG_ERROR(ULP_LOGGER_NAME, "pthread_attr_init failure\n"); return 1; } pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); if (pThreadParams != 0) { if (pThreadParams->stackSize != 0) { pthread_attr_setstacksize(&attr, pThreadParams->stackSize); } if ((pThreadParams->priority > 0) && (pThreadParams->priority < 100)) { LOG_INFO(ULP_LOGGER_NAME, "Create RT thread, priority = %d, policy = %d\n", pThreadParams->priority, pThreadParams->policy); struct sched_param schedParam; schedParam.sched_priority = pThreadParams->priority; pthread_attr_setschedpolicy(&attr, pThreadParams->policy); pthread_attr_setschedparam(&attr, &schedParam); } } ret = pthread_create(pThreadHandle, &attr, pEntryFunc, 0); if (ret != 0) { LOG_ERROR(ULP_LOGGER_NAME, "pthread_create failure\n"); return 1; } LOG_TRACE(ULP_LOGGER_NAME, "pthread_create success\n"); return 0; #else if (pThreadParams == 0 || pThreadHandle == 0 || pEntryFunc == 0) { LOG_ERROR(ULP_LOGGER_NAME, "NULL pointer\n"); return 1; } Task_Params taskParams; Task_Params_init(&taskParams); taskParams.priority = pThreadParams->priority; taskParams.stackSize = pThreadParams->stackSize; taskParams.stack = pThreadParams->stack; *pThreadHandle = Task_create((ti_sysbios_knl_Task_FuncPtr)pEntryFunc, &taskParams, 0); return 0; #endif }
C
bool isPalindrome(char* s) { char *start = s, *end = s; if (*s == '\0') return 1; while (*(end+1) != '\0') end++; while (start <= end){ if (!(*start >= '0' && *start <= '9') && !(*start >= 'A' && *start <= 'Z') && !(*start >= 'a' && *start <= 'z')){ start++; continue; } if (!(*end >= '0' && *end <= '9') && !(*end >= 'A' && *end <= 'Z') && !(*end >= 'a' && *end <= 'z')){ end--; continue; } if (*start >= 'A' && *start <= 'Z') *start = *start + 32; if (*end >= 'A' && *end <= 'Z') *end = *end + 32; if (*start != *end) return 0; start++; end--; } return 1; }
C
/* * dio.c * * Created on: Aug 30, 2020 * Author: H */ #include "avr/io.h" #include "../Infra_Structure/AVR_Reg.h" #include "../Infra_Structure/Common_Macros.h" #include "../Infra_Structure/Std_Types.h" #include "DIO.h" #include "Dio_Cfg.h" //#define NULL 0 #ifndef NULL #define NULL ((void *) 0) #endif /*______________________________________________________________________________________________*/ /*Description: Set PORT Direction (INPUT or OUTPUT) * Input : Copy_u8PortNB (PORT Number) , Copy_u8Dir (PORT Direction) * Output : Return Error Status (Error or NO Error) * */ uint8_t DIO_u8Init_PORT(uint8_t Copy_u8PortNB,uint8_t Copy_u8Dir) { /* Implement Your Code */ switch(Copy_u8Dir){ case DIO_OUTPUT: switch(Copy_u8PortNB){ case DIRECTION_PORT0:DDRA=0xff;break; case DIRECTION_PORT1:DDRB=0xff;break; case DIRECTION_PORT2:DDRC=0xff;break; case DIRECTION_PORT3:DDRD=0xff;break; default:return ERROR; } break; case DIO_INPUT: switch(Copy_u8PortNB){ case DIRECTION_PORT0:DDRA=0;break; case DIRECTION_PORT1:DDRB=0;break; case DIRECTION_PORT2:DDRC=0;break; case DIRECTION_PORT3:DDRD=0;break; default:return ERROR; } break; default:return ERROR; } return NO_ERROR; } /*______________________________________________________________________________________________*/ /*Description: Set PIN Direction (INPUT or OUTPUT) * Input :Copy_u8PinNB (PIN Number) , Copy_u8Dir (PIN Direction) * Output : Return Error Status (Error or NO Error) * */ uint8_t DIO_u8Init_PIN(uint8_t Copy_u8PinN,uint8_t Copy_u8Dir) { /* Implement Your Code */ if(Copy_u8PinN > 30){/***************************************************************************************************************************/ return ERROR; } if(Copy_u8Dir!=DIO_OUTPUT && Copy_u8Dir!=DIO_INPUT){ return ERROR; } if(Copy_u8Dir==DIO_OUTPUT){/*********************************************************************************************************************/ if(Copy_u8PinN >= PIN_A0 && Copy_u8PinN <= PIN_A7){ SET_BIT(DDRA,Copy_u8PinN); } else if(Copy_u8PinN >= PIN_B0 && Copy_u8PinN <= PIN_B7){ SET_BIT(DDRB,(Copy_u8PinN-8)); } else if(Copy_u8PinN >= PIN_C0 && Copy_u8PinN <= PIN_C7){ SET_BIT(DDRC,(Copy_u8PinN-16)); } else{ SET_BIT(DDRD,(Copy_u8PinN-24)); } } if(Copy_u8Dir==DIO_INPUT){ if (Copy_u8PinN >= PIN_A0 && Copy_u8PinN <= PIN_A7) { CLR_BIT(DDRA,Copy_u8PinN); } else if (Copy_u8PinN >= PIN_B0 && Copy_u8PinN <= PIN_B7) { CLR_BIT(DDRB,(Copy_u8PinN-8)); } else if (Copy_u8PinN >= PIN_C0 && Copy_u8PinN <= PIN_C7) { CLR_BIT(DDRC,(Copy_u8PinN-16)); } else { CLR_BIT(DDRD,(Copy_u8PinN-24)); } } return NO_ERROR; } /*______________________________________________________________________________________________*/ /*Description: Set PORT Value (from 0 to 255) * Input : Copy_u8PortNB (PORT Number) , Copy_u8Value (Value) * Output : Return Error Status (Error or NO Error) * */ uint8_t DIO_u8SetPortValue(uint8_t Copy_u8PortNB,uint8_t Copy_u8Value) { /* Implement Your Code */ switch(Copy_u8PortNB){ case VALUE_PORT0: PORTA=Copy_u8Value; break; case VALUE_PORT1: PORTB=Copy_u8Value; break; case VALUE_PORT2: PORTC=Copy_u8Value; break; case VALUE_PORT3: PORTD=Copy_u8Value; break; default: return ERROR; } return NO_ERROR; } /*______________________________________________________________________________________________*/ /*Description: Set PIN Value (HIGH or LOW) * Input : Copy_u8PinNB (PIN Number) , Copy_u8Value (Value) * Output : Return Error Status (Error or NO Error) * */ uint8_t DIO_u8SetPinValue(uint8_t Copy_u8PinN,uint8_t Copy_u8Value) { /* Implement Your Code */ if(Copy_u8PinN>30){ return ERROR; } if(Copy_u8Value!=DIO_LOW&&Copy_u8Value!=DIO_HIGH){ return ERROR; } if (Copy_u8Value == DIO_HIGH) {/*********************************************************************************************************************/ if (Copy_u8PinN >= PIN_A0 && Copy_u8PinN <= PIN_A7) { SET_BIT(PORTA, Copy_u8PinN); } else if (Copy_u8PinN >= PIN_B0 && Copy_u8PinN <= PIN_B7) { SET_BIT(PORTB,(Copy_u8PinN - 8)); } else if (Copy_u8PinN >= PIN_C0 && Copy_u8PinN <= PIN_C7) { SET_BIT(PORTC,(Copy_u8PinN - 16)); } else { SET_BIT(PORTD,(Copy_u8PinN - 24)); } } if (Copy_u8Value == DIO_LOW) { if (Copy_u8PinN >= PIN_A0 && Copy_u8PinN <= PIN_A7) { CLR_BIT(PORTA,(Copy_u8PinN)); } else if (Copy_u8PinN >= PIN_B0 && Copy_u8PinN <= PIN_B7) { CLR_BIT(PORTB,(Copy_u8PinN - 8)); } else if (Copy_u8PinN >= PIN_C0 && Copy_u8PinN <= PIN_C7) { CLR_BIT(PORTC,(Copy_u8PinN - 16)); } else { CLR_BIT(PORTD,(Copy_u8PinN - 24)); } } return NO_ERROR; } /*______________________________________________________________________________________________*/ /*Description: Get PORT Value * Input : Copy_u8PortNB (PORT Number),*Copy_u8Value (Pointer to send value to it) * Output : Return Error Status (Error or NO Error) * */ uint8_t DIO_u8GetPortValue(uint8_t Copy_u8PortNB,uint8_t *Copy_u8Value) { /* Implement Your Code */ if (Copy_u8Value == NULL) { return ERROR; } switch(Copy_u8PortNB){ case VALUE_PORT0: *Copy_u8Value = PINA; break; case VALUE_PORT1: *Copy_u8Value = PINB; break; case VALUE_PORT2: *Copy_u8Value = PINC; break; case VALUE_PORT3: *Copy_u8Value = PIND; break; default:return ERROR; } return NO_ERROR; } /*______________________________________________________________________________________________*/ /*Description: Get PIN Value (HIGH or LOW) * Input : Copy_u8PinN (PIN Number) ,*Copy_u8Value (Pointer to send value to it) * Output : Return Error Status (Error or NO Error) * */ uint8_t DIO_u8GetPinValue(uint8_t Copy_u8PinN,uint8_t *Copy_u8Value) { /* Implement Your Code */ if (Copy_u8Value == NULL) { return ERROR; } if(Copy_u8PinN>30){ return ERROR; } if (Copy_u8PinN >= PIN_A0 && Copy_u8PinN <= PIN_A7) { *Copy_u8Value=GET_BIT(PINA,Copy_u8PinN); } else if (Copy_u8PinN >= PIN_B0 && Copy_u8PinN <= PIN_B7) { *Copy_u8Value=GET_BIT(PINB,(Copy_u8PinN-8)); } else if (Copy_u8PinN >= PIN_C0 && Copy_u8PinN <= PIN_C7) { *Copy_u8Value=GET_BIT(PINC,(Copy_u8PinN-16)); } else{ *Copy_u8Value=GET_BIT(PIND,(Copy_u8PinN-24)); } return NO_ERROR; } /*______________________________________________________________________________________________*/ /*Description: Set PORT Type in case of INPUT Direction (PULL UP or FLOATING) * Input : Copy_u8PortNB (PORT Number),Copy_u8InputType(1 for PULL UP and 0 for FLOATING) * Output : Return Error Status (Error or NO Error) * */ uint8_t DIO_u8SetPortInputType(uint8_t Copy_u8PortNB,uint8_t Copy_u8InputType) { /* Implement Your Code */ switch(Copy_u8InputType){ case 1: switch(Copy_u8InputType){ case VALUE_PORT0: { if(DDRA == 0x00) PORTA = 0xff; else return ERROR; }break; case VALUE_PORT1: { if (DDRB == 0x00) PORTB = 0xff; else return ERROR; }break; case VALUE_PORT2: { if (DDRC == 0x00) PORTC = 0xff; else return ERROR; }break; case VALUE_PORT3: { if (DDRD == 0x00) PORTD = 0xff; else return ERROR; }break; } break; case 0: switch (Copy_u8InputType) { case VALUE_PORT0: { if (DDRA == 0x00) PORTA = 0x00; else return ERROR; }break; case VALUE_PORT1: { if (DDRB == 0x00) PORTB = 0x00; else return ERROR; }break; case VALUE_PORT2: { if (DDRC == 0x00) PORTC = 0x00; else return ERROR; }break; case VALUE_PORT3: { if (DDRD == 0x00) PORTD = 0x00; else return ERROR; }break; } break; default:return ERROR; } return NO_ERROR; } /*______________________________________________________________________________________________*/ /*Description: Set PORT Type in case of INPUT Direction (PULL UP or FLOATING) * Input : Copy_u8PinN(PIN NO) ,Copy_u8InputType(1 for PULL UP and 0 for FLOATING) * Output : Return Error Status (Error or NO Error) * */ uint8_t DIO_u8SetPinInputType(uint8_t Copy_u8PinN,uint8_t Copy_u8InputType) { /* Implement Your Code */ if( Copy_u8PinN>30 ){ return ERROR; } if(Copy_u8InputType!=1 && Copy_u8InputType!=0){ return ERROR; } if(Copy_u8InputType==1){ if (Copy_u8PinN >= PIN_A0 && Copy_u8PinN <= PIN_A7) { if(!GET_BIT(DDRA,Copy_u8PinN)) SET_BIT(PORTA,Copy_u8PinN); else return ERROR; } else if (Copy_u8PinN >= PIN_B0 && Copy_u8PinN <= PIN_B7) { if (!GET_BIT(DDRB,(Copy_u8PinN-8))) SET_BIT(PORTB,(Copy_u8PinN-8)); else return ERROR; } else if (Copy_u8PinN >= PIN_C0 && Copy_u8PinN <= PIN_C7) { if (!GET_BIT(DDRC,(Copy_u8PinN - 16))) SET_BIT(PORTC,(Copy_u8PinN - 16)); else return ERROR; } else{ if (!GET_BIT(DDRD,(Copy_u8PinN - 24))) SET_BIT(PORTD,(Copy_u8PinN - 24)); else return ERROR; } } if(Copy_u8InputType==0){ if (Copy_u8PinN >= PIN_A0 && Copy_u8PinN <= PIN_A7) { if (!GET_BIT(DDRA, Copy_u8PinN)) CLR_BIT(PORTA, Copy_u8PinN); else return ERROR; } else if (Copy_u8PinN >= PIN_B0 && Copy_u8PinN <= PIN_B7) { if (!GET_BIT(DDRB,(Copy_u8PinN - 8))) CLR_BIT(PORTB,(Copy_u8PinN - 8)); else return ERROR; } else if (Copy_u8PinN >= PIN_C0 && Copy_u8PinN <= PIN_C7) { if (!GET_BIT(DDRC,(Copy_u8PinN - 16))) CLR_BIT(PORTC,(Copy_u8PinN - 16)); else return ERROR; } else{ if (!GET_BIT(DDRD,(Copy_u8PinN - 24))) CLR_BIT(PORTD,(Copy_u8PinN - 24)); else return ERROR; } } return NO_ERROR; }
C
#ifndef IO_H #define IO_H #include <stdint.h> inline void io_outb(uint16_t port, uint8_t val) { asm volatile( "outb %0, %1\n" : : "a"(val), "Nd"(port) ); } inline void io_outw(uint16_t port, uint16_t val) { asm volatile( "outw %0, %1\n" : : "a"(val), "Nd"(port) ); } inline void io_outl(uint16_t port, uint32_t val) { asm volatile( "outl %0, %1\n" : : "a"(val), "Nd"(port) ); } inline uint8_t io_inb(uint16_t port) { uint8_t val; asm volatile( "inb %1, %0\n" : "=a"(val) : "Nd"(port) ); return val; } inline uint16_t io_inw(uint16_t port) { uint16_t val; asm volatile( "inw %1, %0\n" : "=a"(val) : "Nd"(port) ); return val; } inline uint32_t io_inl(uint16_t port) { uint32_t val; asm volatile( "inl %1, %0\n" : "=a"(val) : "Nd"(port) ); return val; } inline void io_wait() { asm volatile( "outb %al, $0x80\n" ); } #endif
C
#include <stdio.h> #include <conf.h> #include <kernel.h> #include <proc.h> int c=0, sp=0; extern struct pentry proctab[NPROC]; void printprocstks(int priority) { printf("void printprocstks\(int priority\)\n"); for (c=0; c < NPROC; c++) { if (priority < proctab[c].pprio) { printf("Process [%s]\n", proctab[c].pname); printf("\tpid: %d\n",c); printf("\tpriority: %u\n", proctab[c].pprio); printf("\tbase: 0x%08x\n", proctab[c].pbase); printf("\tlimit: 0x%08x\n", proctab[c].plimit); printf("\tlen: %d\n", proctab[c].pstklen); if (c==currpid) { asm("movl %esp, sp"); printf("\tpointer: 0x%08x\n", sp); } else printf("\tpointer: 0x%08x\n", proctab[c].pesp); } } }
C
#include "lists.h" /** * get_dnodeint_at_index - finds the nth node of a linked list * * @head: pointer to head of list * @index: index of node to get * Return: node at index */ dlistint_t *get_dnodeint_at_index(dlistint_t *head, unsigned int index) { dlistint_t *temp; unsigned int i; for (temp = head, i = 0; i < index && temp != NULL; i++) { temp = temp->next; } if (temp == NULL) { return (NULL); } else { return (temp); } }
C
//ref: http://www1.cts.ne.jp/~clab/hsample/Math/Math5.html #include <stdio.h> #include <math.h> /* exp( )pow( )で必要 */ double CalPois(double a, double n); double Fact(double n); void test(void); /* a分間にn回起きる確率(ポアッソン分布)を計算する */ double CalPois(double lambda, double k) { return (exp(-lambda) * pow(lambda, k) / Fact(k)); } /* 階乗を計算する */ double Fact(double n) { return((n == 0.0 ) ? 1: n * Fact(n - 1.0)); } void test(void){ double pois; double n; double a = 1.0; printf("1 分間に平均で1回起きる現象が\n"); printf("n回\t起きる確率\n\n"); for (n = 0.0; n <= 10.0; n++) { pois = CalPois(a, n); printf("%2.0lf\t%10.8lf\n", n, pois); } } /* ref: https://bellcurve.jp/statistics/course/6984.html 製品Aを作る工場では平均して200個に1個の割合で不良品が発生します。製造された製品Aを10個抜き取る時、この中に不良品が含まれる個数がポアソン分布に従うとすると、不良品が1個含まれる(X = 1となる)確率はいくらでしょうか。 */ void test2(){ double pois; double k; double p = 1.0/200.0, n = 10; double lambda = 0.0; printf("200個に1個の割合で不良品が発生する現象が\n"); printf("製品Aを10個抜き取る時n個不良品が含まれる(X = 0,1,2..,nとなる)確率\n\n"); //不良品が発生する確率は p = 1/200 、抜き取り検査をした個数はn = 10 であることから、 lambda = n * p; printf("lambda = n * p = %f * %f = %f\n\n", n, p, lambda); for (k = 0.0; k <= 10.0; k++) { pois = CalPois(lambda, k); printf("%2.0lf\t%10.8lf\n", k, pois); } // lambdaの値を変える lambda = 1.0; printf("\n\nlambda = %f\n\n", lambda); for (k = 0.0; k <= 10.0; k++) { pois = CalPois(lambda, k); printf("%2.0lf\t%10.8lf\n", k, pois); } lambda = 2.0; printf("\n\nlambda = %f\n\n", lambda); for (k = 0.0; k <= 10.0; k++) { pois = CalPois(lambda, k); printf("%2.0lf\t%10.8lf\n", k, pois); } lambda = 3.0; printf("\n\nlambda = %f\n\n", lambda); for (k = 0.0; k <= 10.0; k++) { pois = CalPois(lambda, k); printf("%2.0lf\t%10.8lf\n", k, pois); } lambda = 5.0; printf("\n\nlambda = %f\n\n", lambda); for (k = 0.0; k <= 10.0; k++) { pois = CalPois(lambda, k); printf("%2.0lf\t%10.8lf\n", k, pois); } lambda = 10.0; printf("\n\nlambda = %f\n\n", lambda); for (k = 0.0; k <= 10.0; k++) { pois = CalPois(lambda, k); printf("%2.0lf\t%10.8lf\n", k, pois); } } int main(int argc, char const *argv[]) { // test(); test2(); return 0; }
C
/* ** EPITECH PROJECT, 2020 ** load_crosshair ** File description: ** load crosshair in sprite */ #include "my.h" void load_crosshair(window_t *window) { sfIntRect pos = {0, 0, 140, 140}; sfTexture *t_cross = sfTexture_createFromFile("assets/crosshair.png", &pos); window->s_crosshair = sfSprite_create(); sfSprite_setTexture(window->s_crosshair, t_cross, sfFalse); free(t_cross); sfSprite_setOrigin(window->s_crosshair, (sfVector2f) {70, 70}); sfSprite_setScale(window->s_crosshair, (sfVector2f) {0.3, 0.3}); } void load_level(window_t *window) { sfFont *font = sfFont_createFromFile("assets/Games.ttf"); window->level = sfText_create(); window->level_nv = sfText_create(); sfText_setString(window->level, "Level : "); sfText_setString(window->level_nv, my_int_to_str(window->lvl)); sfText_setFont(window->level, font); sfText_setFont(window->level_nv, font); sfText_setStyle(window->level, sfTextBold); sfText_setStyle(window->level_nv, sfTextBold); sfText_setColor(window->level, sfBlack); sfText_setColor(window->level_nv, sfRed); sfText_setScale(window->level, (sfVector2f) {1.5, 1.5}); sfText_setScale(window->level_nv, (sfVector2f) {1.5, 1.5}); sfText_setPosition(window->level, (sfVector2f) {800, 950}); sfText_setPosition(window->level_nv, (sfVector2f) {980, 950}); } void load_bullet(window_t *window) { sfTexture *t_sprite; window->s_bullet = sfSprite_create(); window->r_bullet = (sfIntRect) {0, 0, 160, 32}; t_sprite = sfTexture_createFromFile("assets/bullet.png", &window->r_bullet); sfSprite_setTexture(window->s_bullet, t_sprite, sfFalse); free(t_sprite); sfSprite_setOrigin(window->s_bullet, (sfVector2f) {32/2, 32/2}); sfSprite_setPosition(window->s_bullet, (sfVector2f) {370, 970}); sfSprite_setScale(window->s_bullet, (sfVector2f) {2.5, 2.5}); window->bullet = 5; window->fail = 0; } void update_bullet(window_t *window) { sfTexture *t_sprite; window->r_bullet.left += 31; window->bullet--; t_sprite = sfTexture_createFromFile("assets/bullet.png", &window->r_bullet); sfSprite_setTexture(window->s_bullet, t_sprite, sfFalse); window->fail = 0; }
C
#pragma once #ifndef NETWORKCOMMANDS_H #define NETWORKCOMMANDS_H #include "Drawing.h" #pragma region structures static enum command_ids { SHUTDOWN = 0, REGISTER, LOGIN, NEW_SOLO_GAME, NEW_DUO_GAME, NEW_MOVE, REGISTER_OK, REGISTER_ERROR, LOGIN_OK, LOGIN_ERROR, GAME_BEGIN, GAME_END, MOVE, MOVE_HIT, MOVE_MISS, SECOND_PLAYER_MOVE, MOVE_TIMEOUT, GAME_OVER, WINER, LOSER }CLIENT_COMMANDS; typedef struct user_st { char name[15]; char surname[15]; char username[15]; char password[15]; }USER; typedef struct register_user_st { char command_id; USER user; }register_command; typedef struct login_user_st { char command_id; char uname[15]; char pass[15]; }login_command; typedef struct start_game_st { char command_id; char mode; FIELD sparse_matrix[17]; //broj ukupno polja x velicina FIELD-a int matrix_size; }start_command; struct server_response { int code; char error[30]; }; typedef struct player_st { SOCKET socket; char username[10]; LIST *ships; }player; typedef struct duo_game_st { player player_one; player player_two; }duo_game; typedef struct player_move_command { int code; char move[3]; }move_command; #pragma endregion /*Sending packet in smaller pieces if buffer doesn't have enough space * @param socket @param message memory location of my message @param messageSize size of my message @return 1 if message was successfully sent and -1 if sended message is bigger than forwarded size */ int SendPacket(SOCKET socket, char * message, int messageSize); /*Receiving packet in smaller pieces if buffer doesn't have enough space * @param socket @param message memory location of my message @param messageSize size of my message @return 1 if message was successfully sent and -1 is buffer doesn't have enough space to store message */ int RecievePacket(SOCKET socket, char * recvBuffer, int length); /*Validating the players move, it is case insensitive and can handle wrong order but not wrong characters and longer/shorter message * @return true if validation was succesfull, otherwise it returns false */ bool validate_move(char move[]); /*Thread for solo game(server vs client) * @return true if validation was succesfull, otherwise it returns false */ DWORD WINAPI solo_game_thread(LPVOID lpParam); /*Thread for duo game(client vs client) * @return true if validation was succesfull, otherwise it returns false */ DWORD WINAPI duo_game_thread(LPVOID lpParam); /*Thread for solo game(server vs client) * @param socket for communication @return true if validation was succesfull, otherwise it returns false */ DWORD WINAPI solo_game_thread_test(LPVOID lpParam); /*Initilize windows socket @return true if initlized was succesfull, otherwise returns false */ bool InitializeWindowsSockets(); /*Seting socket to listen mode @param listenSocket Pointer to listen socket which will be set in listen mode */ int setToListenSocket(SOCKET *listenSocket); /**/ bool acceptNewClient(SOCKET *listenSocket, SOCKET *clientSocket); int BindServerSocket(SOCKET *listenSocket, int SERVER_PORT); #endif // /* NETWORKCOMMANDS_H */
C
#include<stdio.h> #include<stdlib.h> #include<signal.h> #include<sys/types.h> #include<unistd.h> #include "consulta.h" //include the typedef of Consulta, defined in file consulta.h int waiting_list = 0; int n; int verificar_ficheiro_pedido_consultas_existe(){ FILE *file; file = fopen("PedidoConsulta.txt", "r"); //if the file is empy that means that it didn't existed before the fopen call if(file == NULL){ waiting_list = 1; return 0; } fclose(file); return 1; } void pedir_consulta(Consulta c){ FILE *file; file = fopen("PedidoConsulta.txt", "w"); //Escrever os dados no ficheiro PedidoConsulta.txt fprintf(file, "%d,%s,%d\n", c.tipo, c.descricao, c.pid_consulta); fclose(file); } //Get the pid of the server, writen in file SrvConsultas.pid int pid_of_SrvConsultas(){ int pid; FILE *file; file = fopen("SrvConsultas.pid", "r"); //if the file does not exists yet if(file == NULL){ printf("O ficheiro SrvConsultas.pid nao existe\n"); remove("PedidoConsulta.txt"); //Apagar o Pedido de Consulta e sair do programa se o Servidor nao tiver ativo exit(0); } //read the pid of the server fscanf(file, "%d", &pid); fclose(file); return pid; } //After receiving signal SIGHUP void consulta_iniciada(){ printf("Consulta iniciada para o processo: %d\n", getpid()); n = 1; pause(); } //After receiving signal SIGTERM void consulta_terminada(){ //Check if signal SIGHUP has already been sent if(n == 1){ printf("Consulta concluida para o processo: %d\n", getpid()); //n = 2; remove("PedidoConsulta.txt"); //Apagar o Pedido de Consulta apos o fim da consulta e nao no inicio //Ao apagar a consulta ao receber o SIGHUP, as consultas nao iriam ficar em lista de espera depois na alinea c8 return; } //Error if signal SIGHUP hasn't beem sent yet printf("Impossivel realizar operacao\n"); exit(0); } //After receiving signal SIGUSR2 void consulta_impossivel(){ printf("Consulta impossivel para o processo: %d\n", getpid()); //Remove file PedidoConsulta.txt remove("PedidoConsulta.txt"); exit(0); } void cancelar_espera(){ printf("\nConsulta cancelada para o processo: %d\n", getpid()); //Remove file PedidoConsulta.txt remove("PedidoConsulta.txt"); exit(0); } void sinal_alarme(int sinal){ if(waiting_list == 0){ printf("\nA tentar enviar sinal\n"); } } int main(){ Consulta c; //c1) Introduzir os dados printf("Introduza o tipo de consulta (1: Normal; 2: COVID-19; 3: Urgente):\n"); scanf("%d", &c.tipo); if(c.tipo != 1 && c.tipo != 2 && c.tipo != 3){ printf("Tipo Invalido!\n"); exit(0); } // Ler Descricao e garantir que le mesmo que tenha espacos em branco char descricao[100]; char aux; printf("Introduza a descricao da Consulta:\n"); scanf("%c", &aux); scanf("%[^\n]", descricao); memcpy(c.descricao,descricao,100); //PID consulta e o PID deste processo c.pid_consulta = getpid(); printf("Tipo: %d, Descricao: %s, PID= %d\n", c.tipo, c.descricao, c.pid_consulta); //Check if PedidoConsulta.txt already exists while(verificar_ficheiro_pedido_consultas_existe() != 0){ printf("\nO ficheiro ja existe... espere uns segundos...\n"); signal(SIGALRM, sinal_alarme); printf("\nEm espera...\n"); alarm(10); pause(); } //c2) Criar Pedido de Consulta pedir_consulta(c); //c3) Send signal SIGUSR1 to the server kill(pid_of_SrvConsultas(), SIGUSR1); //c4) signal(SIGHUP, consulta_iniciada); //c5) signal(SIGTERM, consulta_terminada); //c6) signal(SIGUSR2, consulta_impossivel); //c7) signal(SIGINT, cancelar_espera); //Waiting to receive a signal while(n == 0){ pause(); } return 0; }
C
#include <stdio.h> int main() { int xValue = 5; int yValue = 3; int result = xValue * yValue % 14 + yValue; int smallResult = 10 - yValue; printf("the result is: %i \n", result); printf("the small result is: %i \n", smallResult); return 0; }
C
#include <stdio.h> int main ( ) { //prompt for input and gets the key from the terminal int note; int i; printf("Enter a note (in pitch-class number,: 0 - 11): "); scanf("%d", &note); if (note < 0) { printf("Only positive number.\nEnter a note again (0 - 11): "); scanf("%d", &note); } if (note > 11) note = note - 12; //match the root and name it for (int i = 0; i < 7; i++) { if (note%12 == 0) printf("C"); else if (note%12 == 1) printf("Db"); else if (note%12 == 2) printf("D"); else if (note%12 == 3) printf("Eb"); else if (note%12 == 4) printf("E"); else if (note%12 == 5) printf("F"); else if (note%12 == 6) printf("Gb"); else if (note%12 == 7) printf("G"); else if (note%12 == 8) printf("Ab"); else if (note%12 == 9) printf("A"); else if (note%12 == 10) printf("Bb"); else if (note%12 == 11) printf("B"); if (i != 2) note += 2; //build the scale else note = note + 1; //catch the semitone in major scale } printf("\n"); return 0; }
C
#include <assert.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include "osstate.h" #include "command.h" #include "commands.h" #include "datecmds.h" /* Print out localtime in the current date format. */ HANDLECOM(date) { /* Time values. */ time_t clocktime; struct tm *datetime; /* String buffer for times. */ char outtime[255]; /* Amount of occupied buffer. */ size_t timesize; /* Handle CLI args. */ if(argc > 1) { return checkhelpargs(argc, argv, "Usage: date [-h] [--help]\n", ostate); } /* Get the time and stringize it in the proper format. */ timesize = strftime(outtime, 255, ostate->out_datefmt, ostate->datetime); /* Error if the format was too long. */ if(timesize == 0) { fprintf(ostate->output, "ERROR: Output for format '%s' is too long. It must be shorter than 255 characters when filled out\n", ostate->out_datefmt); return 1; } fprintf(ostate->output, "%s\n", outtime); return 0; } /* Display current time. */ HANDLECOM(time) { /* Time values. */ time_t clocktime; struct tm *datetime; /* String buffer for times. */ char outtime[255]; /* Amount of occupied buffer. */ size_t timesize; /* Handle CLI args. */ if(argc > 1) { return checkhelpargs(argc, argv, "Usage: time [-h] [--help]\n", ostate); } /* Update the time in our time struct. */ clocktime = time(NULL); datetime = localtime(&clocktime); ostate->datetime->tm_sec = datetime->tm_sec; ostate->datetime->tm_min = datetime->tm_min; ostate->datetime->tm_hour = datetime->tm_hour; /* Stringize the time in the proper format. */ timesize = strftime(outtime, 255, ostate->time_datefmt, ostate->datetime); /* Error if the format was too long. */ if(timesize == 0) { fprintf(ostate->output, "ERROR: Output for format '%s' is too long. It must be shorter than 255 characters when filled out\n", ostate->out_datefmt); return 1; } fprintf(ostate->output, "%s\n", outtime); return 0; } /* Configure the date format. */ HANDLECOM(datefmt) { /* Enum declarations for modes. */ enum setmode { SM_SET, SM_DISPLAY, }; enum fmtmode { FM_IN, FM_OUT, FM_TIME }; /* Whether to set or display the format. */ enum setmode set; /* The format to display/modify. */ enum fmtmode fmt; /* The format provided by the user. */ char *pszFormat; /* Set options to sensible defaults. */ set = SM_DISPLAY; fmt = FM_IN; pszFormat = NULL; /* Reinit getopt. */ optind = 1; /* Parse CLI args. */ while(1) { /* The current option, and the current long option */ int opt, optidx; /* Our usage message. */ static const char *usage = "Usage: datefmt [-stdioh] [--help] [--set|--display] [--time|--in|--out] [-f|--format <format>]\n"; /* The long options we take. */ static struct option opts[] = { /* Misc. options. */ {"help", no_argument, 0, 'h'}, {"format", no_argument, 0, 'f'}, /* Mode options. */ {"set", no_argument, 0, 's'}, {"display", no_argument, 0, 'd'}, /* Format picking options. */ {"time", no_argument, 0, 't'}, {"in", no_argument, 0, 'i'}, {"out", no_argument, 0, 'o'}, /* Terminating option. */ {0, 0, 0, 0} }; /* Get an option. */ opt = getopt_long(argc, argv, "f:stdioh", opts, &optidx); /* Break if we've processed every option. */ if(opt == -1) break; /* Handle options. */ switch(opt) { case 0: /* We picked a long option. */ switch(optidx) { /* * Long options are handled by corresponding * short options. */ default: fprintf(ostate->output, "\tERROR: Invalid command-line argument\n"); fprintf(ostate->output, "%s\n", usage); return 1; } break; case 'f': /* Free previous format. */ if(pszFormat != NULL) { free(pszFormat); } /* * @NOTE * Is this duplication necessary? */ pszFormat = (char *)strdup(optarg); break; case 's': set = SM_SET; break; case 't': fmt = FM_TIME; break; case 'd': set = SM_DISPLAY; break; case 'i': fmt = FM_IN; break; case 'o': fmt = FM_OUT; break; case 'h': fprintf(ostate->output, "%s\n", usage); return 0; default: fprintf(ostate->output, "\tERROR: Invalid command-line argument.\n"); fprintf(ostate->output, "%s\n", usage); return 1; } } if(set == SM_DISPLAY) { /* Display the format. */ switch(fmt) { case FM_IN: fprintf(ostate->output, "%s\n", ostate->in_datefmt); break; case FM_OUT: fprintf(ostate->output, "%s\n", ostate->out_datefmt); break; case FM_TIME: fprintf(ostate->output, "%s\n", ostate->time_datefmt); break; default: /* Shouldn't happen. */ assert(0); } } else { /* Read a format only if we need to. */ if(pszFormat == NULL) { /* Variables for format input. */ size_t lsize, lread, llen; /* Prompt/read the new format. */ fprintf(ostate->output, "Enter the new format: "); lread = getline(&pszFormat, &lsize, ostate->strem); if(lread < 1) { fprintf(ostate->output, "\tERROR: No input available\n"); return 1; } /* Trim trailing newline. */ llen = strlen(pszFormat); if(pszFormat[llen-1] == '\n') { pszFormat[llen-1] = '\0'; } /* Warn if truncation is going to occur. */ if(llen >= 256) { fprintf(ostate->output, "WARNING: Truncating format '%1$s' to '%1$.256s'\n", pszFormat); } } /* Set the format. */ switch(fmt) { case FM_IN: sprintf(ostate->in_datefmt, "%.256s", pszFormat); break; case FM_OUT: sprintf(ostate->out_datefmt, "%.256s", pszFormat); break; case FM_TIME: sprintf(ostate->time_datefmt, "%.256s", pszFormat); break; default: /* Shouldn't happen. */ assert(0); } /* Cleanup after ourselves. */ free(pszFormat); fprintf(ostate->output, "Format set\n"); } return 0; } HANDLECOM(setdate) { /* * @TODO 10/25/17 Ben Culkin :SetdateCLI * Convert this to use getopt for arg-handling and add the * following options: * - Specify the date as a CLI param * - Specify a custom format to use */ /* Variables for date input. */ char *line; size_t lsize, lread, llen; /* The time from the line, and any left-over bits. */ struct tm *datetime; char *leftovers; /* The official time. */ time_t clocktime; /* Handle CLI args. */ if(argc > 1) { return checkhelpargs(argc, argv, "Usage: setdate [-h] [--help]\n", ostate); } /* Get the current time. */ datetime = ostate->datetime; /* Prompt/read the new date. */ fprintf(ostate->output, "Enter the new date: "); lread = getline(&line, &lsize, ostate->strem); if(lread < 1) { fprintf(ostate->output, "\tERROR: No input provided.\n"); return 1; } /* Trim trailing newline. */ llen = strlen(line); if(line[llen-1] == '\n') line[llen-1] = '\0'; /* Parse the input according to the format. */ leftovers = (char *)strptime(line, ostate->in_datefmt, datetime); if(leftovers == NULL) { /* The format didn't match correctly. */ fprintf(ostate->output, "\tERROR: Input '%s' doesn't match format '%s'\n", line, ostate->in_datefmt); free(line); return 1; } else if(*leftovers != '\0') { /* There were trailing characters in the input. */ fprintf(ostate->output, "\tWARNING: Trailing input '%s' unused by format\n", leftovers); } /* Sanitize/set the time. */ clocktime = mktime(datetime); ostate->datetime = localtime(&clocktime); if(ostate->datetime == NULL) { fprintf(ostate->output, "\tFATAL ERROR: Date/time value overflowed."); free(line); return -1; } /* Cleanup. */ free(line); return 0; }
C
/* ** EPITECH PROJECT, 2020 ** NWP_myteams_2019 ** File description: ** logout */ #include "mylib.h" #include "command.h" void c_logout_ctrlc_exec(server_t *server, client_t *client, char *uuid, char *name) { uuid = client->user->uuid_str->to_str(client->user->uuid_str); name = client->user->name->to_str(client->user->name); c_logout_send_to_users(server, uuid, name); server_event_user_logged_out(uuid); free(uuid); free(name); } void c_logout_command_exec(server_t *server, client_t *client, char *uuid, char *name) { uuid = client->user->uuid_str->to_str(client->user->uuid_str); name = client->user->name->to_str(client->user->name); dprintf(client->socket, "%s [ANSW]: %s %s\n", keycodes.exit, uuid, name); c_logout_send_to_users(server, uuid, name); server_event_user_logged_out(uuid); free(uuid); free(name); } int c_logout_exec(server_t *server, client_t *client, lklist_str_t *pbuff) { char *uuid = NULL; char *name = NULL; if (client->user != NULL && client->logged == 1) client->user->logged = 0; if (match_str(pbuff->at(pbuff, 0), "^C") == 0) { if (client->user != NULL && client->logged == 1) c_logout_command_exec(server, client, uuid, name); else dprintf(client->socket, "%s\n", keycodes.exit); } else if (match_str(pbuff->at(pbuff, 0), "^C") == 1) { if (client->user != NULL && client->logged == 1) c_logout_ctrlc_exec(server, client, uuid, name); } return 1; } int c_logout_check_arg(client_t *client, lklist_str_t *pbuff) { if (pbuff->size(pbuff) != 1) return 0; if (match_str(pbuff->at(pbuff, 0), "/logout") == 0 && match_str(pbuff->at(pbuff, 0), "^C") == 0) return 0; return 1; } int c_logout(server_t *server, client_t *client, lklist_str_t *pbuff) { int check = 0; check = c_logout_check_arg(client, pbuff); if (check == 0) return check; return c_logout_exec(server, client, pbuff); }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<unistd.h> #include <unistd.h> #include <sys/wait.h> char *commands[] = { "cd", "help", "exit"}; //Commands to be searched in bin //Iterate through commands to see what user is asking for int check_command(char **args){ for(int commandNumber = 0; commandNumber > strlen(commands); commandNumber++){ //string compare, if return 0 that means that it is in the commands list if(strcmp(args[0], commands[commandNumber]) == 0){ //If user command matches a known command, return true. return commandNumber; } } return -1; //Else, command is not vaild } int run_user_command(int commandNumber, char **args){ // switch(commandNumber){ case 0: run_cd(args); break; case 1: run_help(); break; case 2: exit(0); default: //Do something break; } }