language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include "threads.h"
int factorial(int n) {
return n == 0 ? 1 : n * factorial(n-1);
}
void fun_with_threads(void * arg) {
printf("** In fun_with_threads() function **\n");
int i = 0;
int n = *(int *) arg;
for(;i < 10; ++i) {
printf("** Loop %d **\n", i);
printf("** %d! = %d **\n", n+i, factorial(n+i));
printf("** Yielding from fun_with_threads() **\n");
yield();
}
}
void thread_wrap() {
printf("*** Starting thread_wrap ***\n");
current_thread->initial_function(current_thread->initial_argument);
printf("*** Yeilding from thread_wrap() ***\n");
yield();
}
void yield() {
printf("\n**** In yield function ****\n");
thread * temp = current_thread;
current_thread = inactive_thread;
inactive_thread = temp;
printf("**** Calling thread_switch ****\n");
thread_switch(inactive_thread, current_thread);
}
|
C
|
/*
虚拟内存实验
*/
/*
实验思路:
1.先把物理页数量减少至1,便于观察实验
2.剩余1个页,我们要在1个页的基础上再给进程分配10个页(即10*4096的进程空间)
3.循环访问分配的10个页:每次访问都先要换出一个页,再把之前写到磁盘的页换入
实验效果:
1.物理页从剩余数量为690,减少至1
2.除第一次分配不用换出外,后面的9次分配都要换出,一共换出9次
3.每次访问,先换出一个页(腾出一个物理页),再换入之前在磁盘的物理页数据
*/
#include "types.h"
#include "stat.h"
#include "user.h"
void
mem(void){
char *adTable[11]; // 存储页的第一个地址
for(int i = 0; i < 4; i++){
adTable[i] = sbrk(4096);// 延迟分配页帧
}
printf(1,"---------------------------------------\n");
for(int i = 0 ; i < 4; i ++){
adTable[i][1] = 'a' + i ; //这时候就出现缺页,需要换出一个页(腾出一个位置) ,并且给页的第一个字节赋值为字母a~d
}
printf(1,"---------------------------------------\n");
printf(1,"访问第4个页,其内容是 %c, 不发生缺页异常\n\n",adTable[3][1]);
printf(1,"下面展示缺页异常的交换功能:\n");
for(int i = 0,cnt = 1; cnt <= 4; i= (i+1) % 4 ,cnt++){
printf(1,"第%d个页的内容是: %c\n\n",i+1,adTable[i][1]);//访问第i个页
sleep(100*3);//进程休眠,便于观察
}
}
int
main(void)
{
bstat();
for(int i = 1 ; i <= 689; i++)
sbrk(4096)[1] = 1;//把物理页分配出去,为实验做准备
bstat();
mem();
exit();
}
|
C
|
#pragma once
#include "defs.h"
#include "str.h"
typedef enum {
TStyle_bold, // : sfn('1', '1', '22'),
TStyle_italic, // : sfn('3', '3', '23'),
TStyle_underline, // : sfn('4', '4', '24'),
TStyle_inverse, // : sfn('7', '7', '27'),
TStyle_white, // : sfn('37', '38;2;255;255;255', '39'),
TStyle_grey, // : sfn('90', '38;5;244', '39'),
TStyle_black, // : sfn('30', '38;5;16', '39'),
TStyle_blue, // : sfn('34', '38;5;75', '39'),
TStyle_cyan, // : sfn('36', '38;5;87', '39'),
TStyle_green, // : sfn('32', '38;5;84', '39'),
TStyle_magenta, // : sfn('35', '38;5;213', '39'),
TStyle_purple, // : sfn('35', '38;5;141', '39'),
TStyle_pink, // : sfn('35', '38;5;211', '39'),
TStyle_red, // : sfn('31', '38;2;255;110;80', '39'),
TStyle_yellow, // : sfn('33', '38;5;227', '39'),
TStyle_lightyellow, // : sfn('93', '38;5;229', '39'),
TStyle_orange, // : sfn('33', '38;5;215', '39'),
_TStyle_MAX,
} TStyle;
const char* TStyleTable[_TStyle_MAX];
const char* TStyle_none;
const char* TStyle_noColor;
static inline Str TStyleBold(Str s) { return sdscat(s, TStyleTable[TStyle_bold]); }
static inline Str TStyleItalic(Str s) { return sdscat(s, TStyleTable[TStyle_italic]); }
static inline Str TStyleUnderline(Str s) { return sdscat(s, TStyleTable[TStyle_underline]); }
static inline Str TStyleInverse(Str s) { return sdscat(s, TStyleTable[TStyle_inverse]); }
static inline Str TStyleWhite(Str s) { return sdscat(s, TStyleTable[TStyle_white]); }
static inline Str TStyleGrey(Str s) { return sdscat(s, TStyleTable[TStyle_grey]); }
static inline Str TStyleBlack(Str s) { return sdscat(s, TStyleTable[TStyle_black]); }
static inline Str TStyleBlue(Str s) { return sdscat(s, TStyleTable[TStyle_blue]); }
static inline Str TStyleCyan(Str s) { return sdscat(s, TStyleTable[TStyle_cyan]); }
static inline Str TStyleGreen(Str s) { return sdscat(s, TStyleTable[TStyle_green]); }
static inline Str TStyleMagenta(Str s) { return sdscat(s, TStyleTable[TStyle_magenta]); }
static inline Str TStylePurple(Str s) { return sdscat(s, TStyleTable[TStyle_purple]); }
static inline Str TStylePink(Str s) { return sdscat(s, TStyleTable[TStyle_pink]); }
static inline Str TStyleRed(Str s) { return sdscat(s, TStyleTable[TStyle_red]); }
static inline Str TStyleYellow(Str s) { return sdscat(s, TStyleTable[TStyle_yellow]); }
static inline Str TStyleLightyellow(Str s) { return sdscat(s, TStyleTable[TStyle_lightyellow]); }
static inline Str TStyleOrange(Str s) { return sdscat(s, TStyleTable[TStyle_orange]); }
static inline Str TStyleNone(Str s) { return sdscat(s, TStyle_none); }
static inline Str TStyleNoColor(Str s) { return sdscat(s, TStyle_noColor); }
bool TSTyleStdoutIsTTY();
bool TSTyleStderrIsTTY();
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <stdlib.h>
#include "myhead.h"
int main(int argc, char *argv[]){
int server_sock = -1; //服务器socket
u_short port = 4000; //port
int client_sock = -1; //客户端socket
struct sockaddr_in client_name;
socklen_t client_name_len = sizeof(client_name);
server_sock = startup(&port); //封装的socket()
printf("http is runing... port: %d\n", port);
while(1){
client_sock = accept(server_sock,
(struct sockaddr *)&client_name,
&client_name_len);
if(client_sock == -1)
error_die("accept error");
}
close(server_sock);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "limits.h"
/**
* \brief Recibe el valor de dos numeros y calcula la suma
* \param numeroUno corresponde al primer numero ingresado por el usuario
* \param numeroDos corresponde al segundo numero ingresado por el usuario
* \param resultadoSuma corresponde a la suma de los numeros ingresados
* \return si el retorno es correcto[0] o erroneo[-1]
*
*/
float sumaEnteros (float numeroUno, float numeroDos, float* resultadoSuma)
{
float resultadoCalculo;
int retorno=-1;
resultadoCalculo=numeroUno+numeroDos;
if(resultadoCalculo< INT_MAX && resultadoCalculo> INT_MIN)
{
*resultadoSuma=resultadoCalculo;
retorno=0;
}
return retorno;
}
/**
* \brief Recibe el valor de dos numeros y calcula su division
* \param numeroUno corresponde al primer numero ingresado por el usuario
* \param numeroDos corresponde al segundo numero ingresado por el usuario
* \param resultadoDivision corresponde a la division de los numeros ingresados
* \return si el retorno es correcto[0] o erroneo[-1]
*
*/
float divisionEnteros(float numeroUno, float numeroDos,float *resultadoDivision)
{
double resultadoCalculo;
int retorno=-1;
resultadoCalculo=numeroUno/numeroDos;
if(numeroDos>0 && resultadoCalculo<INT_MAX &&resultadoCalculo>INT_MIN)
{
*resultadoDivision=resultadoCalculo;
retorno=0;
}
return retorno;
}
/**
* \brief Recibe el valor de dos numeros y calcula la multiplicacion
* \param numeroUno corresponde al primer numero ingresado por el usuario
* \param numeroDos corresponde al segundo numero ingresado por el usuario
* \param resultadoMultiplicacion corresponde a la multiplicacion de los numeros ingresados
* \return si el retorno es correcto[0] o erroneo[-1]
*
*/
float multiplicacionEnteros(float numeroUno, float numeroDos,float* resultadoMultiplicacion)
{
double resultadoCalculo;
int retorno=-1;
resultadoCalculo=numeroUno*numeroDos;
if(resultadoCalculo<INT_MAX && resultadoCalculo>INT_MIN )
{
*resultadoMultiplicacion=resultadoCalculo;
retorno=0;
}
return retorno;
}
/**
* \brief Recibe el valor de dos numeros y calcula la resta
* \param numeroUno corresponde al primer numero ingresado por el usuario
* \param numeroDos corresponde al segundo numero ingresado por el usuario
* \param resultadoResta corresponde a la multiplicacion de los numeros ingresados
* \return si el retorno es correcto[0] o erroneo[-1]
*
*/
float restaEnteros(float numeroUno, float numeroDos,float* resultadoResta)
{
double resultadoCalculo;
int retorno=-1;
resultadoCalculo=numeroUno-numeroDos;
if(resultadoCalculo>INT_MIN&&resultadoCalculo<INT_MAX)
{
*resultadoResta=resultadoCalculo;
retorno=0;
}
return retorno;
}
/**
* \brief Recibe el valor de un numero y calcula el factorial
* \param numeroUno corresponde al numero ingresado por el usuario
* \return el factorial del numero ingresado
*/
float factorial(float numeroUno)
{
int i;
float resultadoFactorial=1;
for(i=1;i<=numeroUno;i++)
{
resultadoFactorial=resultadoFactorial*i;
}
return resultadoFactorial;
}
|
C
|
#include "functions.h"
#include "mathematicalOperations.h"
void menu()
{
float x=0,y=0,suma=0,resta,multiplicacion,divicion;
int factorialA,factorialB,flag=0,flag1=0,flag2=0,option;
do
{
printf("1.Ingresar 1er operando (A=%.2f)\n",x);
printf("2.Ingresar 2do operando (B=%.2f)\n",y);
printf("3.Calcular todas las operacione\n");
printf("4.Informar resultados\n");
printf("5.Salir\n\n");
printf("Elija una opcion:");
scanf("%d",&option);
switch(option)
{
case 1:
flag2=0;
PedirNumero(&x);
flag=1;
break;
case 2:
flag2=0;
PedirNumero(&y);
flag1=1;
break;
case 3:
if(flag1!=1 && flag!=1)
{
printf("\nERROR. DEBE INGRESAR LOS DOS NUMERO ANTES DE CALCULAR ALGO..\n");
pausa();
}
else
{
borrar();
calcularOperaciones(x,y,&suma,&resta,&multiplicacion,&divicion,&factorialA,&factorialB);
flag2=1;
pausa();
}
break;
case 4:
if(flag1!=1 && flag!=1)
{
printf("\nERROR. DEBE INGRESAR LOS DOS NUMERO ANTES DE MOSTRAR ALGO..\n");
pausa();
}
else if(flag2==1)
{
borrar();
mostrarResultados(suma,resta,divicion,multiplicacion,factorialA,factorialB);
pausa();
}
else
{
printf("\nERROR. DEBE CALCULAR LOS NUMEROS ANTES DE PODER MOSTRARLOS..\n");
pausa();
}
break;
case 5:
printf("\nHASTA LUEGO..");
break;
default:
borrar();
printf("ERROR. Elija una opcion del 1-5\n");
pausa();
break;
}
borrar();
}
while(option!=5);
}
void calcularOperaciones(float numero1, float numero2, float* suma, float* resta, float* div,float* multiplcacion, int* factorialA, int* factorialB)
{
printf("Calculando Operaciones Matematicas\n");
if(sumador(numero1,numero2,suma))
{
printf("\ta)Calculada la suma (A+B).\n");
}
if(restador(numero1,numero2,resta))
{
printf("\tb)Calculada la resta (A-B)\n");
}
if(divicion(numero1,numero2,div))
{
printf("\tc)Calculada la division (A/B).\n");
}
else
{
printf("\tc)Error. Division no calculada (No se puede dividir por 0)\n");
*div=0;
}
if(multiplicador(numero1,numero2,multiplcacion))
{
printf("\td)Calculada la multiplicacion (A*B)\n");
}
if(factorial(numero1,factorialA))
{
printf("\te)Calculado el factorial (A!)\n");
}
if(factorial(numero2,factorialB))
{
printf("\te)Calculado el factorial (B!)\n");
}
}
void mostrarResultados(float suma, float resta, float divicion, float multiplicacion, int factorialA, int factorialB)
{
printf("\n\ta)El resultado de A+B es: %.2f\n",suma);
printf("\tb)El resultado de A-B es: %.2f\n",resta);
printf("\tc)El resultado de A/B es: %.2f\n",divicion);
printf("\td)El resultado de A*B es: %.2f\n",multiplicacion);
printf("\te)El factorial de A es: %d y El factorial de B es: %d\n",factorialA,factorialB);
}
void PedirNumero(float* numero)
{
printf("Ingrese el Numero:");
scanf("%f",numero);
}
void pausa(int option)
{
/*if(option==1)
{
system("read -p 'Press Enter to continue...' var");
}
else
{
system("pause");
}*/
system("read -p 'Press Enter to continue...' var");
}
void borrar(int option)
{
/*if(option==1)
{
system("clear");
}else
{
system("cls");
}*/
system("clear");
}
|
C
|
#include<stdio.h>
#include<conio.h>
int main()
{
int num;
printf("enter the number");
scanf("%d%",&num);
if(num%2==0)
{
printf("given number is even number");
}
else
{
printf("given number is odd number");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../header/tree_map.h"
int cstring_compare(void *o1, void *o2){
return strcmp((char*)o1, (char*)o2);
}
int int_compare(void *o1, void *o2){
return *((int*)o1) - *((int*)o2);
}
int* toPointer(int value){
int* temp = malloc(sizeof(int));
*temp = value;
return temp;
}
int main(){
char* a = "Brian";
char* b = "Julia";
char* c = "Rex";
TreeMap* map = tree_map_constructor(&cstring_compare);
tree_map_put(a, "Crafton", map);
tree_map_put(b, "O'brien", map);
tree_map_put(c, "Hoadly", map);
TreeMap* map1 = tree_map_constructor(&int_compare);
tree_map_put(toPointer(10), toPointer(13), map1);
tree_map_put(toPointer(11), toPointer(14), map1);
tree_map_put(toPointer(12), toPointer(15), map1);
printf("%d\n", tree_map_contains(a, map));
printf("%d\n", tree_map_contains("Julia", map));
printf("%d\n", tree_map_contains("hello", map));
printf("%s\n", (char*)tree_map_get(a, map));
printf("%s\n", (char*)tree_map_get("Julia", map));
printf("%d\n", tree_map_contains(toPointer(10), map1));
printf("%d\n", tree_map_contains(toPointer(11), map1));
printf("%d\n", tree_map_contains(toPointer(144), map1));
printf("%d\n", *((int*)tree_map_get(toPointer(10), map1)));
printf("%d\n", *((int*)tree_map_get(toPointer(11), map1)));
}
|
C
|
#ifndef LIST_H_
#define LIST_H_
typedef void (*list_element_free)(void *v);
// This function shall return 0 if v1 and v2 are equal, -1 otherwise
typedef int (*list_element_cmp)(void *v1, void *v2);
typedef struct _list_element {
void *v;
struct _list_element *next;
} list_element;
typedef struct _list {
list_element_free free_fn;
list_element_cmp cmp_fn;
list_element *elements;
} list;
list* list_new(list_element_free free_fn, list_element_cmp cmp_fn);
void list_add(list *l, void *element);
void list_free(list *l);
void* list_find(list *l, void *what);
#endif
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int fd, fd1;
int flag;
fd = open(argv[1], O_WRONLY | O_CREAT);
if (fd == -1)
{
return -1;
}
printf("O_CREAT = %#o\n", O_CREAT);
flag = fcntl(fd, F_GETFL);
if (flag == -1)
{
return -1;
}
printf("fd = %d\n", fd);
printf("flag = %#o\n", flag);
flag |= O_APPEND;
printf("flag = %#o\n", flag);
flag = fcntl(fd, F_SETFL, flag);
write(fd, "test program", 12);
close(fd);
return 0;
}
|
C
|
#include "Mean.h"
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
void messageOfTheDay()
{
char * msgs[] = { "Scott is not great...", "Mario is much better than Kast.", "Wade is much better than Kast.", "BIG (Brandon is great)",
"Generic mean message; be upset." , "KING (Kast is not good)" , "Happy Birthday! Not!" , "Kast is my third favorite teacher, any I only have two professors" ,
"Brandon > Kast" , "Kast > Brandon? Of course not, this is a mean message." };
srand(time(NULL));
printf("%s\n", msgs[rand() % 10]);
}
char letterGrade(int a)
{
if (a >= 96)
return 'A';
else if (a <= 95 && a >= 91)
return 'B';
else if (a <= 90 && a >= 86)
return 'C';
else if (a <= 85 && a >= 81)
return 'D';
else
return 'F';
}
|
C
|
#include<stdio.h>
void main()
{
int num;
do
{
printf("Enter a positive number: ");
scanf("%d",&num);
}while(num<0);
int factorial,i;
for(i=1;i<=num;factorial*=i,i++);
printf("%d! = %d\n",num,factorial);
}
|
C
|
#include "uart_485.h"
#include "delay.h"
#include "usart.h"
#include "config.h"
#ifdef USART_485_RX_EN //ʹ˽
//ջ
u8 RS485_RX_BUF[100]; //ջ,64ֽ.
//յݳ
u8 RS485_RX_CNT=0;
void USART3_IRQHandler(void)
{
u8 res;
if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET) //յ
{
res =USART_ReceiveData(USART3); //ȡյ
// USART1->DR = res;
if(RS485_RX_CNT<100)
{
RS485_RX_BUF[RS485_RX_CNT]=res; //¼յֵ
RS485_RX_CNT++; //1
}
}
}
#endif
void USART3_Init(u32 bound)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);//ʹGPIOA,Gʱ
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3,ENABLE);//ʹUSART2ʱ
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; //PG9˿
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; //PA2
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;//PA3
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //
GPIO_Init(GPIOB, &GPIO_InitStructure);
RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3,ENABLE);//λ2
RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3,DISABLE);//ֹͣλ
#ifdef USART_485_RX_EN //ʹ˽
USART_InitStructure.USART_BaudRate = bound;//һΪ9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;//8λݳ
USART_InitStructure.USART_StopBits = USART_StopBits_1;//һֹͣλ
USART_InitStructure.USART_Parity = USART_Parity_No;///żУλ
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//Ӳ
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;//շģʽ
USART_Init(USART3, &USART_InitStructure); ; //ʼ
NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn; //ʹܴ2ж
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //ռȼ2
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2; //ȼ2
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //ʹⲿжͨ
NVIC_Init(&NVIC_InitStructure); //NVIC_InitStructָIJʼNVICĴ
USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);//ж
USART_Cmd(USART3, ENABLE); //ʹܴ
#endif
USART_485_TX_EN=0; //ĬΪģʽ
}
//RS485lenֽ.
//buf:ַ
//len:͵ֽ(Ϊ˺ͱĽƥ,ィ鲻Ҫ64ֽ)
void RS485_Send_Data(u8 *buf,u8 len)
{
u8 t;
USART_485_TX_EN=1; //Ϊģʽ
for(t=0;t<len;t++) //ѭ
{
while(USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET);
USART_SendData(USART3,buf[t]);
}
while(USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET);
RS485_RX_CNT=0;
USART_485_TX_EN=0; //Ϊģʽ
}
//RS485ѯյ
//buf:ջַ
//len:ݳ
void RS485_Receive_Data(u8 *buf,u8 *len)
{
u8 rxlen=RS485_RX_CNT;
u8 i=0;
*len=0; //ĬΪ0
delay_ms(10);
// if(rxlen==RS485_RX_CNT&&rxlen)//յ,ҽ
// {
if (RS485_RX_CNT>=7)
{
for(i=0;i<RS485_RX_CNT;i++)
{
buf[i]=RS485_RX_BUF[i];
}
*len=RS485_RX_CNT; //¼ݳ
RS485_RX_CNT=0; //
}
}
//©ˮ10
u8 water_err (void)
{
u8 length;
u8 buff[20]={0};
buff[0]=0x01;
buff[1]=0x04;
buff[2]=0x00;
buff[3]=0x01;
buff[4]=0x00;
buff[5]=0x01;
buff[6]=0x60;
buff[7]=0x0a;
RS485_Send_Data(buff,8);
buff[0]=0;
RS485_Receive_Data(buff,&length);
if (buff[0])
{
if (!buff[4])
{
WARN_WATER=0;//ޱ
return 0;
}
else
{
WARN_WATER=1;//©ˮ
return 1;
}
}
WARN_WATER=2;//ûн©ˮ
return 2;
}
|
C
|
#include "numerik_bespin_deutsch_linalg.h"
#include <stdlib.h>
#include <math.h>
MATRIX *matrix_alloc(int n) {
int i;
MATRIX *ret;
/* Allokiert ein Matrix-Struct */
if ( NULL == (ret = malloc(sizeof(MATRIX))) ) {
return NULL;
}
/* Speicher fuer die Matrixelemente */
if ( NULL == (ret->data = malloc(n * n * sizeof(double))) ) {
free(ret);
return NULL;
}
ret->n = n;
/* Darstellung als 2D-Array */
if ( NULL == (ret->elem = malloc(n * sizeof(double*))) ) {
free(ret);
free(ret->data);
return NULL;
}
for (i = 0; i < n; i++) {
ret->elem[i] = ret->data + i * n;
}
return ret;
}
void matrix_free(MATRIX *A) {
free(A->data);
free(A->elem);
free(A);
}
void matrix_swap_row(MATRIX *A, int i, int j) {
double *temp;
int n = A->n;
if ( i < n && j < n ) {
temp = A->elem[i];
A->elem[i] = A->elem[j];
A->elem[j] = temp;
}
}
VECTOR *vector_alloc(int n) {
VECTOR *ret;
if ( NULL == (ret = malloc(sizeof(VECTOR))) ) {
return NULL;
}
if ( NULL == (ret->elem = malloc(n * sizeof(double))) ) {
free(ret);
return NULL;
}
ret->n = n;
return ret;
}
void vector_free(VECTOR *v) {
free(v->elem);
free(v);
}
int LU_decomp(MATRIX *A, int *permutation) {
int i, j, k;
int n = A->n;
int piv, temp;
/* Spalte der Gauß-Elimination */
for (i = 0; i < n; i++) {
/* Berechnung des Pivot-Elements */
piv = pivot_row(A, i);
if ( piv != i ) {
/* Tauschen der Zeilen */
matrix_swap_row(A, i, piv);
/* Merken der Vertauschung */
temp = permutation[i];
permutation[i] = permutation[piv];
permutation[piv] = temp;
}
/* Berechnung der oberen Dreiecksmatrix U */
for (j = i; j < n; j++) {
for (k = 0; k < i; k++) {
A->elem[i][j] -= A->elem[i][k] * A->elem[k][j];
}
}
/* Ueberpruefung ob das Diagonalelement ausreichend von 0 verschieden ist,
* also die Matrix nicht singulaer bzw. fast singulaer ist */
if ( fabs(A->elem[i][i]) < 1E-10 ) {
return -1;
}
/* Berechnung der unteren Dreiecksmatrix L */
for (j = i + 1; j < n; j++) {
for (k = 0; k < i; k++) {
A->elem[j][i] -= A->elem[j][k] * A->elem[k][i];
}
A->elem[j][i] /= A->elem[i][i];
}
}
return 0;
}
int pivot_row(MATRIX *A, int k) {
int i, j;
int n = A->n;
int piv = k;
double max = 0;
double temp, sum;
/* Im letzten Schritt der Gauß-Elimination ist kein Zeilentausch moeglich */
if ( k == n - 1 ) return piv;
/* Iteration ueber alle moeglichen Pivot-Zeilen */
for (i = k; i < n; i++) {
sum = 0;
/* Berechnung des Terms, der maximiert werden soll */
for (j = k; j < n; j++) {
sum += fabs(A->elem[i][j]);
}
temp = A->elem[i][k] / sum;
if ( temp > max ) {
max = temp;
piv = i;
}
}
return piv;
}
int LU_solve(MATRIX *LU, VECTOR *Pb, VECTOR *sol) {
/* Es ist LUx = Pb zu loesen. */
VECTOR *y = vector_alloc(Pb->n);
/* Loese zuerst Ly = Pb mit y = Ux durch Vorwaertssubstitution */
LU_forward_sub(LU, Pb, y);
/* Loese Ux = y durch Rueckwaertssubstitution */
LU_back_sub(LU, y, sol);
vector_free(y);
return 0;
}
int LU_forward_sub(MATRIX *LU, VECTOR *b, VECTOR *sol) {
int i, j;
int n = LU->n;
if ( n != b->n ) return -1;
for (i = 0; i < n; i++) {
sol->elem[i] = b->elem[i];
for (j = 0; j < i; j++) {
sol->elem[i] -= LU->elem[i][j] * sol->elem[j];
}
/* Es wird hier nicht durch L[i][i] geteilt, da die Diagonalelemente der
* unteren Dreickecksmatrix 1 sind. */
}
return 0;
}
int LU_back_sub(MATRIX *LU, VECTOR *b, VECTOR *sol) {
int i, j;
int n = LU->n;
if ( n != b->n ) return -1;
for (i = n - 1; i >= 0; i--) {
sol->elem[i] = b->elem[i];
for (j = i + 1; j < n; j++) {
sol->elem[i] -= LU->elem[i][j] * sol->elem[j];
}
sol->elem[i] /= LU->elem[i][i];
}
return 0;
}
int linear_solve(MATRIX *A, VECTOR *b, VECTOR *sol) {
int i;
int n = A->n;
int *permutation = malloc(n * sizeof(int));
VECTOR *Pb = vector_alloc(n);
if ( A->n != b->n ) return -1;
/* Fuellt das Permutationsarray mit {0, 1, ..., n-1} */
for (i = 0; i < n; i++) {
permutation[i] = i;
}
/* LU-Zerlegung der Matrix */
if ( LU_decomp(A, permutation) == -1 ) {
return -2;
}
/* Permutation von b */
for (i = 0; i < n; i++) {
Pb->elem[i] = b->elem[permutation[i]];
}
/* Loesung des identischen Gleichungssystems LUx = Pb */
LU_solve(A, Pb, sol);
return 0;
}
|
C
|
#include "../include/core.h"
#include "../include/graph.h"
void init_graph() {
if (initscr() == NULL) {
perror("initscr");
return;
}
noecho();
curs_set(0);
keypad(stdscr, true);
cbreak();
start_color();
refresh();
getmaxyx(stdscr, rows, cols);
init_pair(1, COLOR_WHITE, COLOR_CYAN);
init_pair(2, COLOR_WHITE, COLOR_BLUE);
init_pair(3, COLOR_WHITE, COLOR_BLACK);
init_pair(4, COLOR_BLACK, COLOR_WHITE);
}
void init_workspace(DIR_INFO** ld, DIR_INFO** rd){
(*ld)->p_wnd = newwin(rows, cols/2, 0 ,0);
box((*ld)->p_wnd, '|', '-');
(*ld)->m_wnd = derwin((*ld)->p_wnd, rows-2, cols/2-2, 1, 1);
(*rd)->p_wnd = newwin(rows, cols/2, 0, cols/2);
box((*rd)->p_wnd, '|', '-');
(*rd)->m_wnd = derwin((*rd)->p_wnd, rows-2, cols/2-2, 1, 1);
wrefresh((*ld)->p_wnd);
wrefresh((*rd)->p_wnd);
}
void print_dir(DIR_INFO* di, int bg_c) {
FILE_INFO_LIST* p = NULL;
p = di->head_file;
wclear(di->m_wnd);
box(di->p_wnd, '|', '-');
wattron(di->p_wnd, A_BOLD);
wattron(di->p_wnd, COLOR_PAIR(4));
wmove(di->p_wnd, 0, cols / 4 - strlen(di->path) / 2);
wprintw(di->p_wnd, "~ %s ~", di->path);
wattroff(di->p_wnd, COLOR_PAIR(4));
wattroff(di->p_wnd, A_BOLD);
wrefresh(di->p_wnd);
wattron(di->m_wnd, A_BOLD);
while(p) {
if (p == di->current_file) {
wattron(di->m_wnd, COLOR_PAIR(bg_c));
wprintw(di->m_wnd, " %s \n", p->value.name);
wattroff(di->m_wnd, COLOR_PAIR(bg_c));
}
else {
wattron(di->m_wnd, COLOR_PAIR(3));
wprintw(di->m_wnd, " %s \n", p->value.name);
wattroff(di->m_wnd, COLOR_PAIR(3));
}
p = p->next;
}
wattroff(di->m_wnd, A_BOLD);
wprintw(di->m_wnd, "\n Count: %d\n", di->file_count);
wrefresh(di->m_wnd);
return;
}
void close_graph(){
echo();
endwin();
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtrim.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: stdenis <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/11 13:32:35 by stdenis #+# #+# */
/* Updated: 2018/11/13 18:22:57 by stdenis ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_spaces(char const *s)
{
int i;
i = 0;
while (s[i] == ' ' || s[i] == '\t' || s[i] == '\n')
i++;
return (i);
}
static int ft_count_reverse_spaces(char const *s, size_t len)
{
int i;
i = 0;
while (s[len] == ' ' || s[len] == '\t' || s[len] == '\n')
{
len--;
i++;
}
return (i);
}
char *ft_strtrim(char const *s)
{
int sp1;
int sp2;
int length;
char *new;
if (s == NULL)
return (NULL);
length = ft_strlen(s);
sp1 = ft_count_spaces(s);
if (sp1 < length)
sp2 = ft_count_reverse_spaces(s, length - 1);
else
sp2 = -1;
if (!(new = ft_strsub(s, sp1, length - sp1 - sp2)))
return (NULL);
return (new);
}
|
C
|
/*
* uart2.c
*
* Created on: Jun 3, 2014
* Author: reuben
*/
#include "mb90540.h"
/* globals */
unsigned char receive_data;
unsigned char ERROR = 0xC2; /* clears all data leds */
//unsigned char data[] = {0x00,0x02,0x40,0x42,0x80,0x82,0xC0};
unsigned char data[] = {'R','E','U','B','E','N','\n'};
unsigned short index = 0;
/* interrupt functions */
__interrupt void Uart1_Transmit (void)
{
SODR1 = data[index++]; /* sends data to the SOT1 */
if(index > 6)
index = 0;
}
__interrupt void Uart0_Transmit (void)
{
UODR0 = data[index++]; /* sends data the SOT0 */
if(index > 6)
index = 0;
}
__interrupt void Uart0_Receive (void)
{
if(USR0_ORFE)
{
UMC0_RFC = 0; /* clear error flags */
}
else
{
receive_data = UIDR0; /* write received data to buffer */
PDR4 = receive_data; /* buffer outputed to led's */
}
}
__interrupt void Uart1_Receive (void)
{
if(SSR1_ORE || SSR1_FRE)
{
SCR1_REC = 0; /* clear error flag */
}
else
{
receive_data = SIDR1; /* write received data to buffer */
PDR4 = receive_data; /* buffer outputed to led's */
}
}
/*============================== PROCEDURES ======================================*/
void uartInit(void)
{
/* initialize UART0 and UART1 with baud rate, mode, stop bits etc. */
/* initialize UART0 */
UMC0 = 0x5D; /* serial mode control register (01011101) */
USR0 = 0x0C; /* status register (00011100) */
URD0 = 0x4C; /* rate and data register (01001100) */
/* initialize UART1 */
SMR1 = 0x09; /* serial mode register (00001001) */
SCR1 = 0x33; /* serial control register (00110011) */
U1CDCR = 0x88; /* UART1 prescaler control (10001000) */
DDR4 = 0xE3; /* direction register of PORT4 (11100011) */
SSR1 = 0x03; /* serial status register (00001011) */
}
/************************************************************************************/
|
C
|
#include "asm80.h"
/* packToken - packs the token pointed by tokStart, with length toksiz into 4 bytes
packed version replaces original and toksize set to 4 bytes
*/
static byte Pack1(byte i)
{
return i >= tokenSize[0] ? 0 : tokStart[0][i] < 0x3f ? tokStart[0][i] - 0x2f : tokStart[0][i] - 0x34;
}
void PackToken()
{
*(wpointer)tokPtr = (Pack1(0) * 40 + Pack1(1)) * 40 + Pack1(2);
*(wpointer)(tokPtr + 2) = (Pack1(3) * 40 + Pack1(4)) * 40 + Pack1(5);
tokenSize[0] = 4;
}
|
C
|
#include <stdio.h>
int main(int argc, char **argv)
{
int myNum = 7;
int *myPtr;
myPtr = &myNum; //myPtr = address of myNum
printf("myNum = %i\n",myNum); //myNum = 7
printf("myPtr = %i\n",myPtr); //address of myPtr
printf("*myPtr = %i\n",*myPtr); //contents of what myPtr is pointing to (myNum) "dereferencing"
printf("&myPtr = %i\n",&myPtr); //contents of myPtr
*myPtr = 5; //changed contents of myNum to 5
printf("myNum = %i\n",myNum);
printf("myPtr = %i\n",myPtr);
printf("*myPtr = %i\n",*myPtr);
printf("&myPtr = %i\n",&myPtr);
return 0;
}
|
C
|
#include <string.h>
#include <minunit.h>
#include <titan-secure-volume/titan-secure-volume.h>
#include <titan-secure-volume/app.h>
void new_ramdisk (size_t len);
START_TEST (test_write0)
{
int err;
uint8_t mac_key[TSV_MAC_KEY_SIZE];
uint8_t encryption_key[TSV_ENCRYPTION_KEY_SIZE];
uint8_t buf[1024] = {0};
tsv_read_urandom (mac_key, sizeof (mac_key));
tsv_read_urandom (encryption_key, sizeof (encryption_key));
tsv_close ();
new_ramdisk (5*512);
mu_assert (!tsv_create (mac_key, encryption_key, 512, 1), "tsv_create should succeed in test_write.");
err = tsv_write (0, buf, 1);
mu_assert (err, "tsv_write should fail if the volume isn't open.");
mu_assert (!tsv_open (mac_key, encryption_key), "tsv_open should succeed in test_write.");
err = tsv_write (512, buf, 1);
mu_assert (err, "tsv_write should fail if writing outside disk.");
err = tsv_write (0, buf, 513);
mu_assert (err, "tsv_write should fail if writing outside disk.");
err = tsv_write (0, buf, 1);
mu_assert (!err, "tsv_write should succeed if writing inside the disk.");
}
END_TEST
char *test_write (void)
{
mu_run_test (test_write0);
return 0;
}
|
C
|
//
// Lab work #7, Count pi
//
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define ITERATIONS 2000000000
#define BILLION 1000000000.
typedef struct pi_state {
size_t pos;
size_t amount;
pthread_t thread;
double result;
} pi_state_t;
void* count_pi(void* arg) {
struct timespec start, stop;
pi_state_t* state = (pi_state_t*)arg;
clock_gettime(CLOCK_REALTIME, &start);
state->result = 0.0;
for (size_t i = state->pos; i <= ITERATIONS; i += state->amount) {
state->result += 1.0 / (i * 4.0 + 1.0);
state->result -= 1.0 / (i * 4.0 + 3.0);
}
clock_gettime(CLOCK_REALTIME, &stop);
double accum = (stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec) / BILLION;
printf("%lf\n", accum);
return &state->result;
}
int main(int argc, char* argv[]) {
pi_state_t* states;
int threads_count;
double pi = 0.;
void* value;
int result;
if (argc < 2) {
fprintf(stderr, "Need args: <threads>\n");
return -1;
}
threads_count = atoi(argv[1]);
if (threads_count < 1) {
fprintf(stderr, "Wrong threads number\n");
return -1;
}
states = (pi_state_t*)malloc(sizeof(pi_state_t) * threads_count);
for (size_t i = 0; i < threads_count; i++) {
states[i].pos = i;
states[i].amount = threads_count;
result = pthread_create(&states[i].thread, NULL, &count_pi, states + i);
if (result != 0) {
fprintf(stderr, "Cannot create thread: %s\n", strerror(result));
free(states);
return result;
}
puts("Created");
}
for (size_t i = 0; i < threads_count; i++) {
if ((result = pthread_join(states[i].thread, &value)) != 0) {
fprintf(stderr, "Cannot join thread: %s\n", strerror(result));
free(states);
return result;
}
pi += (*((double*)value));
puts("Joined");
}
free(states);
pi *= 4;
printf("pi: %.15lf\n", pi);
return 0;
}
|
C
|
#include "test.h"
static mat4 rnd = {{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
}};
static mat4 cns = {{
{ 1, 2, 3, 4 },
{ 1, 2, 3, 4 },
{ 1, 2, 3, 4 },
{ 1, 2, 3, 4 },
}};
static void test_mmmul() {
printf("test mmmul:\n");
mat4 a = midentity();
mat4 b = smmul(15, a);
mat4 scal = mmmul(a, b);
compare_mat_equal(scal, b, "identity preserves");
}
__attribute__((always_inline)) static inline vec4 mvmul_simple(const mat4 m, const vec4 v) {
return
m.cols[0] * vsplat(v, 0) +
m.cols[1] * vsplat(v, 1) +
m.cols[2] * vsplat(v, 2) +
m.cols[3] * vsplat(v, 3);
}
#define BENCH_ROUNDS 10000000
#define BENCH_MVMUL(_fn) \
NO_INLINE static vec4 loop_ ## _fn() { \
mat4 m = midentity(); \
vec4 v = vec(4, 3, 1, 5); \
for (int i = 0; i < BENCH_ROUNDS; ++i) { \
v = _fn(m, v); \
} \
return v; \
}
#define BENCH_MVMUL_COLS(_fn) \
NO_INLINE static vec4 loop_ ## _fn() { \
mat4 m = midentity(); \
vec4 v = vec(4, 3, 1, 5); \
for (int i = 0; i < BENCH_ROUNDS; ++i) { \
v = _fn(m.cols[0], m.cols[1], m.cols[2], m.cols[3], v); \
} \
return v; \
}
BENCH_MVMUL(mvmul)
BENCH_MVMUL(mvmul_simple)
BENCH_MVMUL_COLS(mvmul_add_cols)
BENCH_MVMUL_COLS(mvmul_madd_cols)
static void test_mvmul() {
printf("test mvmul:\n");
vec4 v = vec(1.0f, 2.0f, 3.0f, 4.0f);
mat4 b = smmul(15, midentity());
compare_vec_equal(v, mvmul(midentity(), v), "identity preserves");
compare_vec_equal(v * vscalar(15.0f), mvmul(b, v), "scaled");
vec4 one = vscalar(1.0f);
compare_vec_equal(vec(4,8,12,16), mvmul(cns, one), "constant column");
compare_vec_equal(vec(4,8,12,16), mvmul_add_cols(cns.cols[0], cns.cols[1], cns.cols[2], cns.cols[3], one), "constant column (column add)");
compare_vec_equal(vec(4,8,12,16), mvmul_madd_cols(cns.cols[0], cns.cols[1], cns.cols[2], cns.cols[3], one), "constant column (column madd)");
}
static void bench_mvmul() {
printf(BENCH_LINE "\n");
{
benchfn fns[] = { loop_mvmul_add_cols, loop_mvmul_simple, loop_mvmul, loop_mvmul_madd_cols };
const char *names[] = { "mvmul_add", "mvmul_simple", "mvmul", "mvmul_madd" };
benchmark(fns, names, NELEMS(fns));
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <syslog.h>
#include <errno.h>
#include <stdlib.h>
#define MAX_LISTEN_NUM 5
#define SEND_BUF_SIZE 100
#define RECV_BUF_SIZE 100
#define SERVER_PORT 11010
int main()
{
int sock_fd = 0;
char recvbuf[RECV_BUF_SIZE] = {0};
char sendbuf[SEND_BUF_SIZE] = {0};
int retlen = 0;
int leftlen = 0;
char *ptr = NULL;
struct sockaddr_in ser_addr;
memset(&ser_addr, 0, sizeof(ser_addr));
ser_addr.sin_family = AF_INET;
inet_aton("127.0.0.1", (struct in_addr *)&ser_addr.sin_addr);
ser_addr.sin_port = htons(SERVER_PORT);
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if(sock_fd < 0)
{
syslog(LOG_ERR, "%s:%d, create socket failed", __FILE__, __LINE__);
exit(1);
}
if(connect(sock_fd, (struct sockaddr *)&ser_addr, sizeof(ser_addr)) < 0)
{
syslog(LOG_ERR, "%s:%d, connect socket failed", __FILE__, __LINE__);
exit(1);
}
//receive data
ptr = recvbuf;
leftlen = RECV_BUF_SIZE -1;
//do
{
retlen = recv(sock_fd, ptr, leftlen, 0) ;
if(retlen < 0)
{
if(errno == EINTR)
retlen = 0;
else
exit(1);
}
leftlen -= retlen;
ptr += retlen;
}
printf("receive data is : %s\n", recvbuf);
sprintf(sendbuf, "hello server\n");
//send data
leftlen = strlen(sendbuf) + 1;
ptr = sendbuf;
while(leftlen)
{
retlen = send(sock_fd, ptr, leftlen, 0);
if(retlen < 0)
{
if(errno == EINTR)
retlen = 0;
else
exit(1);
}
leftlen -= retlen;
ptr += retlen;
}
close(sock_fd);
return 0;
}
|
C
|
// String util
// Unsigned int to BCD (range 0 to 9999)
uint16_t uint2bcd(uint16_t binary) {
if (binary >= 9999)
return 0x9999;
uint8_t i3 = binary / 1000;
uint8_t i2 = binary / 100 % 10;
uint8_t i1 = binary / 10 % 10;
uint8_t i0 = binary % 10;
return (i3<<12) | (i2<<8) | (i1<<4) | i0;
}
// BCD to unsigned int (range 0 to 999)
uint16_t bcd2uint(uint16_t bcd) {
uint16_t ans = bcd & 0x000F;
bcd = bcd >> 4;
ans += ( bcd & 0x000F ) * 10;
bcd = bcd >> 4;
ans += ( bcd & 0x000F ) * 100;
bcd = bcd >> 4;
ans += ( bcd & 0x000F ) * 1000;
return ans;
}
// BCD to OSD (On Screen Display module encoding)
uint16_t bcd2osd(uint8_t bcd) {
uint8_t h, l;
h = bcd >> 4;
if (!h) h = 0x0A; //Char code for 0 is 0x0A
l = bcd & 0x0F;
if (!l) l = 0x0A;
return (h<<8) | l;
}
|
C
|
#include <stdio.h>
int main(){
int k = 1048576;
int exec = 0;
while(k){
k /= 2;
exec++;
}
printf("%d\n", exec);
return 0;
}
|
C
|
/*
*
* File Name: Menu.c
* Name: Kensal J. Ramos
* Course: COP 2220C at Valencia College
* Instructor: David Stendel
* Description: This file will handle the processing of menus.
* Team Members: Kensal J. Ramos
* Date: November 21st - Menu file created
*
*
*/
#include <stdio.h>
#include <stdlib.h>
// Prototypes
void printMenu();
void printCMenu();
void printRMenu();
void printDMenu();
void printUMenu();
/*
* Name: printMenu()
* Parameters: None
* Return Value: None
*/
void printMenu() {
printf("\n-----------------------------------------\n");
printf("|\t\tAddress Book\t\t|\n");
printf("-----------------------------------------\n");
printf("|\t\t0) Exit |\n");
printf("|\t\t1) Create entry \t|\n");
printf("|\t\t2) Retrieve entry |\n");
printf("|\t\t3) Update entry \t|\n");
printf("|\t\t4) Delete entry \t|\n");
printf("|\t\t5) Display entries |\n");
printf("|\t\t6) Save File |\n");
printf("-----------------------------------------\n");
printf("Select option: ");
}
/*
* Name: printCMenu()
* Parameters: None
* Return Value: None
*/
void printCMenu() {
printf("\n-----------------------------------------\n");
printf("|\t\tCreate Entry\t\t|\n");
printf("-----------------------------------------\n");
printf("( Enter each piece of information as it comes up.\n");
printf(" If you would like that piece of information to\n remain empty enter 0 )\n");
printf("-----------------------------------------\n");
}
/*
* Name: printRMenu()
* Parameters: None
* Return Value: None
*/
void printRMenu() {
printf("\n-----------------------------------------\n");
printf("|\t\tRetrieve Entry\t\t|\n");
printf("-----------------------------------------\n");
}
/*
* Name: printUMenu()
* Parameters: None
* Return Value: None
*/
void printUMenu() {
printf("\n-----------------------------------------\n");
printf("|\t\tUpdate Entry\t\t|\n");
printf("-----------------------------------------\n");
}
/*
* Name: printDMenu()
* Parameters: None
* Return Value: None
*/
void printDMenu() {
printf("\n-----------------------------------------\n");
printf("|\t\tDelete Entry\t\t|\n");
printf("-----------------------------------------\n");
}
|
C
|
#include <uapi/machine/cpufunc.h>
#include <uapi/machine/io.h>
#include <uapi/console.h>
#include <string.h>
#define BACKSPACE 0x100
static void cga_putc(void *arg, int c)
{
uint16_t *crt = arg;
int pos;
/* cursor position: col + 80*row */
outb(PORT_CRT, 14);
pos = inb(PORT_CRT + 1) << 8;
outb(PORT_CRT, 15);
pos |= inb(PORT_CRT + 1);
if (c == '\n') {
pos += 80 - pos % 80;
} else if (c == BACKSPACE) {
if (pos > 0)
--pos;
} else {
crt[pos++] = (c & 0xff) | 0x0700; /* black on white */
}
if (pos < 0 || pos > 25 * 80)
panic("pos under/overflow");
if (pos / 80 >= 24) { /* scroll up */
memmove(crt, crt + 80, sizeof(crt[0]) * 23 * 80);
pos -= 80;
memset(crt + pos, 0, sizeof(crt[0]) * (24 * 80 - pos));
}
outb(PORT_CRT, 14);
outb(PORT_CRT + 1, pos >> 8);
outb(PORT_CRT, 15);
outb(PORT_CRT + 1, pos);
crt[pos] = ' ' | 0x0700;
}
void cga_write(void *arg, const char *s, size_t n)
{
size_t i;
for (i = 0; i < n; ++i)
cga_putc(arg, (uint8_t)s[i]);
}
void cga_init(void *arg)
{
#if ENABLED(CONFIG_CGA)
static struct console_device dev = {
.write = cga_write,
};
dev.arg = arg;
console_register(&dev);
#endif
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_len.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kperreau <kperreau@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/01/08 17:53:47 by kperreau #+# #+# */
/* Updated: 2015/01/15 19:02:39 by kperreau ### ########.fr */
/* */
/* ************************************************************************** */
#include "printf.h"
void ft_putspace(t_options *opt, int len, long long n)
{
char *str;
int size;
int i;
char c;
size = (opt->len > len) ? opt->len - len : 0;
if (opt->type == 3 && n < 0 && opt->precise == -1 && opt->zero \
&& !(opt->flags & 1))
{
opt->precise += opt->len;
return ;
}
if ((str = (char*)malloc(sizeof(char*) * size)) == NULL)
return ;
if (opt->type >= 2 && opt->type <= 11 && opt->precise != -1)
c = ' ';
else
c = (opt->zero && !(opt->flags & 1)) ? '0' : ' ';
i = 0;
while (i < size)
str[i++] = c;
str[i] = '\0';
write(1, str, size);
free(str);
}
void ft_putzero(t_options *opt, int len)
{
char *str;
int size;
int i;
size = ((len < 0) ? 1 : 0) + opt->precise - len;
if ((str = (char*)malloc(sizeof(char*) * size)) == NULL)
return ;
i = 0;
while (i < size)
str[i++] = '0';
str[i] = '\0';
write(1, str, size);
free(str);
}
void ft_putsigned(int flags, long long n)
{
if (n < 0)
write(1, "-", 1);
else if (flags & 2)
write(1, "+", 1);
else
write(1, " ", 1);
}
int ft_nbrlen2(unsigned long n)
{
return ((n > 9) ? ft_nbrlen2(n / 10) + 1 : 1);
}
int ft_searchpoint(char *str, int len)
{
while (str[len] != '.' && len >= 0)
--len;
if (str[len] != '.')
len = -1;
return (len);
}
|
C
|
typedef struct{
int posX;
int posY;
int ** movimientos;
int cantmovs;
}tipoF;
/*Guarda la posición de la ficha encontrada al azar y las direcciones en las que puede moverse.
**Sirve únicamente para el juego contra la computadora*/
struct infoTablero{
char **Mapa;
int Fil;
int Col;
};
/*Guarda la información del tablero*/
struct infoRecorrido{
int **recorrido;
int dimrecorrido;
};
/*Guarda la información del recorrido que realiza una ficha en un movimiento de capturas sucesivas*/
typedef struct infoTablero * tipoT;
typedef struct infoRecorrido * tipoR;
int guardarPartida(int modojuego, int turno, tipoT tablero, char * nombre);
/*Recibe como parámetros de entrada:
** -modojuego: indica si juegan 2 jugadores o 1 jugador contra la Pc
** -turno: indica a quién le toca mover
** -tablero.
** -nombre: es el nombre con el que se va a guardar el archivo
Devuelve en su nombre 1 si hubo error y 0 si se pudo guardar correctamente*/
int recuperarPartida(tipoT tablero, int * modojuego, int * turno, int fichas[], char * nom);
/*Recibe nom: el nombre del archivo que contiene la informacion de una partida que fue guardada.
**Devuelve en parámetros de salida, la información del tablero, modojuego, turno y la cantidad de fichas de cada jugador.
**Devuleve en su nombre 1 si hubo error y 0 si se cargo correctamente*/
void generarTablero( tipoT tablero );
/*Distribuye las fichas en un mapa de dimensiones ya establecidas*/
void aumentaRecorrido( tipoR rec, int orig[], int dest[], int *error );
/*Recibe: -Un recorrido, que contiene las posiciones por las que pasó una ficha en su movimiento de captura.
** -Un vector con la posición de origen, para el caso de que sea la primer captura del turno.
** -Un vector con la posición de destino, que se agrega al final del recorrido.
** -Un flag para indicar si hubo algun error en la función.*/
void disminuyeRecorrido(tipoR rec); /*Para el caso del UNDO*/
/*Remueve del final del recorrido, la última posición*/
void liberaRecorrido( tipoR rec );
/*Usada para liberar el espacio reservado para el recorrido, una vez finalizado el turno.*/
int controlaRecorrido( const tipoR rec, int orig[], int dest[], int chequeaorig );
/*Todos sus parámetros son de entrada.
**Verifica que la posición de destino de una fichas no esté en su recorrido de capturas de ese turno.
**Chequeaorig indica si se debe controlar, o no, que la posición de origen sea igual a la última posición de destino del movimiento
**Devuelve en su nombre 1 si el movimiento es válido, y 0, si no lo es*/
void elegirFichaAzar(int orig[], int dest[], const tipoT tablero, const tipoR rec, int *errormemoria);
/*Recibe el tablero y el recorrido.
**Devuelve en orig y dest, el movimiento a realizar elegido al azar, luego de verificar que es válido*/
int esEmpate( const tipoT tablero, char turno, const tipoR rec );
/*Verifica si se da la situación de empate. Los 3 parámetros son de entrada.
**Devuelve en su nombre 1 si hay empate, o 0 en caso de que no haya*/
void backup( char ** Mapa, int Fil, int Col, char** Aux );
/*Fil y Col son parámetros de entrada e indican las dimensiones del tablero.
**Mapa es de entrada y Aux de salida.
**Guarda un auxiliar del mapa en aux. En el caso de realizar Undo, se invierten Mapa y Aux al invocar.*/
int movida( const tipoT tablero, char* turno, int orig[], int dest[], char WoA, int fichas[], const tipoR rec, int * fichascomidas );
/*Son todos parámetros de entrada menos: -fichascomidas, que indica la cantidad de fichas que fueron capturadas en el movimiento.
** -Fichas: guarda la cantidad de fichas restantes de cada jugador.
**tablero, turno, rec, orig, dest, son los parámetros necesarios para realizar el movimiento.
**WoA indica si se quiere capturar por acercamiento o alejamiento. En el caso de no especificar, vale \0.
**Devuelve en su nombre el resultado del movimiento, que puede ser:
** -Sigueturno: Tiene capturas disponible con esa ficha.
** -Terminoturno: Ya no puede realizar mas capturas.
** -Terminojuego: algún jugador se quedo sin fichas.
** -Jugadainvalida: hubo algún error en el movimiento elegido.*/
|
C
|
#include <stdio.h>
//#include<conio.h>
#include <stdlib.h>
struct hash *ht = NULL;
int eCount = 0,ccount=0;
char l[100];
struct node {
int key;
struct node *next;
};
struct hash {
struct node *head;
int count;
};
struct node * createNode(int key)
{
struct node *newnode;
newnode = (struct node *)malloc(sizeof(struct node));
newnode->key = key;
newnode->next = NULL;
return newnode;
}
void insert(int key) {
int Index = key % eCount;
struct node *newnode = createNode(key);
if (!ht[Index].head)
{
ht[Index].head = newnode;
ht[Index].count = 1;
return;
}
newnode->next = (ht[Index].head);
ht[Index].head = newnode;
ht[Index].count++;
return;
}
void display() {
struct node *myNode;
int i;
for (i = 0; i < eCount; i++) {
if (ht[i].count == 0)
continue;
myNode = ht[i].head;
if (!myNode)
continue;
printf("\n\nData at index %d in Hash Table:\n", i);
printf("key \n");
printf("------\n");
ccount=0;
while (myNode != NULL) {
printf("%-12d", myNode->key);
ccount++;
myNode = myNode->next;
}
printf("\nlenght of chain : %d",ccount);
l[i]=ccount;
}
return;
}
int main() {
int n,x=1, key, ele,i,j,temp;
printf("Enter the number of elements:");
scanf("%d", &n);
eCount = n;
ht = (struct hash *)calloc(n, sizeof (struct hash));
while (x==1) {
printf("Enter the key value:");
scanf("%d", &key);
insert(key);
scanf("%d",&x);
}
display();
for(i=0;i<strlen(l);i++)
{
for(j=i+1;j<strlen(l);j++)
{
if(l[i]>l[j])
temp=(int)l[i];
}
}
printf("\nthe longest chain in the chaining is %d\n",temp);
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
int add(int a, int b);
int sub(int a, int b);
int mul(int a, int b);
int divi(int a, int b);
// TCP server
int main(){
// Create a socket
int sockfd=socket(PF_INET,SOCK_STREAM,0);
// prepare address
struct sockaddr_in addr;
addr.sin_family=PF_INET;
// Port numbers such as 8008 are reserved by larger companies and thus we have to create our own port number.
addr.sin_port= htons(12345);
//addr_sin_addr =("127.0.0.1")
inet_aton("127.0.0.1",&addr.sin_addr);
//3rd step is to bind socket and address
int res=bind(sockfd,(struct sockaddr*)&addr,sizeof(addr));
if(res==-1){
perror("[+] Bind failed");
exit(-1);
}
printf("[+] Bind successful\n");
//4th step is to listen to the client
if(listen(sockfd,100)==-1){
perror("listen failed");
exit(1);
}
printf("[+] Starting to listen \n");
// wait for client to connect, client addr stored in fromaddr
struct sockaddr_in fromaddr;
socklen_t len=sizeof(fromaddr);
int rd;
char *clientpacket[3];
char errormessage[] = "This is not a supported opperand";
int num1;
int num2;
int result;
int fd=accept(sockfd,(struct sockaddr*)&fromaddr,&len);
if (fd == -1){
perror("Accept failed");
}
else {
printf("[+] Client has successfully connected to the server\n");
}
while (1){
char buf[90] = {};
char serverpacket[100];
// read client information
rd=read(fd,buf,sizeof(buf));
buf[rd]='\0';
// tokenize client string using a delimiter " "
char *token = strtok(buf, " ");
int i = 0;
// While loop that tokenizes buffer for easier use
while(token != NULL){
clientpacket[i] = token;
token = strtok(NULL, " ");
i++;
}
// While loop that changes operand characters to lower case
i = 0;
while(i < 3){
clientpacket[0][i] = tolower(clientpacket[0][i]);
i++;
}
// check if the first index of the tokenized string is equal to "add"
if(strcmp(clientpacket[0],"add") == 0){
num1 = atoi(clientpacket[1]); // convert string to int
num2 = atoi(clientpacket[2]); // convert string to int
result = add(num1,num2); // call add method and pass in two variables num1 and num2
sprintf(serverpacket, "1: (%d) + (%d) = %d", num1, num2, result); // convert result into string type and store it in serverpacket buffer
write(fd,serverpacket,strlen(serverpacket)); // write the result back to the client
// check if the first index of the tokenized string is equal to "sub"
} else if(strcmp(clientpacket[0],"sub") == 0){
num1 = atoi(clientpacket[1]);
num2 = atoi(clientpacket[2]);
result = sub(num1,num2); // call sub method
sprintf(serverpacket, "1: (%d) - (%d) = %d", num1, num2, result);
write(fd,serverpacket,strlen(serverpacket));
// check if the first index of the tokenized string is equal to "mul"
} else if (strcmp(clientpacket[0],"mul") == 0){
num1 = atoi(clientpacket[1]);
num2 = atoi(clientpacket[2]);
result = mul(num1,num2); // call mul method
sprintf(serverpacket, "1: (%d) * (%d) = %d", num1, num2, result);
write(fd,serverpacket,strlen(serverpacket));
// check if the first index of the tokenized string is equal to "div"
} else if (strcmp(clientpacket[0],"div") == 0){
num1 = atoi(clientpacket[1]);
num2 = atoi(clientpacket[2]);
// if num2 is equal to 0 we know we will encounter a divide by 0 error
if (num2 == 0){
char serverpacket[] = "0: Cannot divide by 0";
write(fd,serverpacket,strlen(serverpacket)); // write back to client that divison by 0 is an error
} else {
result = divi(num1,num2); // else call div method
sprintf(serverpacket, "1: (%d) / (%d) = %d", num1, num2, result);
write(fd,serverpacket,strlen(serverpacket));
}
} else { // if the client did not enter in a valid operand we send them an error message
write(fd,errormessage,strlen(errormessage));
}
}
close(sockfd); // close socket
}
int add(int a, int b){
return (a+b);
}
int sub(int a, int b){
return (a-b);
}
int mul(int a, int b){
return (a*b);
}
int divi(int a, int b){
return (a/b);
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <errno.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define SHMKEY 0x40
#define SHMSIZE 100
main()
{
int shmid;
int* array;
int i;
if( (shmid = shmget( (key_t)SHMKEY , SHMSIZE , IPC_CREAT|IPC_EXCL|0666 )) < 0)
perror("Error");
array = (int*)shmat(shmid , 0 , 0);
for(i = 0; i < 100; i++)
array[i] = rand() % 1000;
printf("Array contents:\n");
for(i = 0; i < 100; i++)
printf("%d " , array[i]);
}
|
C
|
/*
* Copyright (c) 2006 Dustin Sallings <dustin@spy.net>
*/
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "tl_hashtable.h"
/* Table of 32 primes by their distance from the nearest power of two */
static size_t prime_size_table[] = {
3, 7, 13, 23, 47, 97, 193, 383, 769, 1531, 3067, 6143, 12289, 24571, 49157,
98299, 196613, 393209, 786433, 1572869, 3145721, 6291449, 12582917,
25165813, 50331653, 100663291, 201326611, 402653189, 805306357,
1610612741
};
#define TABLE_SIZE ((int)(sizeof(prime_size_table) / sizeof(int)))
struct genhash_entry_t {
/** The key for this entry */
void *key;
/** Size of the key */
size_t nkey;
/** The value for this entry */
void *value;
/** Size of the value */
size_t nvalue;
/** Pointer to the next entry */
struct genhash_entry_t *next;
};
struct _genhash {
size_t size;
struct tl_HASHOPS ops;
struct genhash_entry_t *buckets[];
};
static size_t estimate_table_size(size_t est);
static void *dup_key(tl_HASHTABLE *h, const void *key, size_t klen)
{
if (h->ops.dup_key != NULL) {
return h->ops.dup_key(key, klen);
} else {
return (void *)key;
}
}
static void *dup_value(tl_HASHTABLE *h, const void *value, size_t vlen)
{
if (h->ops.dup_value != NULL) {
return h->ops.dup_value(value, vlen);
} else {
return (void *)value;
}
}
static void free_key(tl_HASHTABLE *h, void *key)
{
if (h->ops.free_key != NULL) {
h->ops.free_key(key);
}
}
static void free_value(tl_HASHTABLE *h, void *value)
{
if (h->ops.free_value != NULL) {
h->ops.free_value(value);
}
}
static size_t estimate_table_size(size_t est)
{
size_t rv = 0;
while (prime_size_table[rv] < est && rv + 1 < TABLE_SIZE) {
rv++;
}
return prime_size_table[rv];
}
void tl_ht_free(tl_HASHTABLE *h)
{
if (h != NULL) {
tl_ht_clear(h);
free(h);
}
}
int tl_ht_store(tl_HASHTABLE *h, const void *k, size_t klen,
const void *v, size_t vlen)
{
size_t n = 0;
struct genhash_entry_t *p;
assert(h != NULL);
n = h->ops.hashfunc(k, klen) % h->size;
assert(n < h->size);
p = calloc(1, sizeof(struct genhash_entry_t));
if (!p) {
return -1;
}
p->key = dup_key(h, k, klen);
p->nkey = klen;
p->value = dup_value(h, v, vlen);
p->nvalue = vlen;
p->next = h->buckets[n];
h->buckets[n] = p;
return 0;
}
static struct genhash_entry_t *genhash_find_entry(tl_HASHTABLE *h,
const void *k,
size_t klen)
{
size_t n = 0;
struct genhash_entry_t *p;
assert(h != NULL);
n = h->ops.hashfunc(k, klen) % h->size;
assert(n < h->size);
p = h->buckets[n];
for (p = h->buckets[n]; p && !h->ops.hasheq(k, klen, p->key, p->nkey); p = p->next);
return p;
}
void *tl_ht_find(tl_HASHTABLE *h, const void *k, size_t klen)
{
struct genhash_entry_t *p;
void *rv = NULL;
p = genhash_find_entry(h, k, klen);
if (p) {
rv = p->value;
}
return rv;
}
enum tl_UPDATETYPE tl_ht_update(tl_HASHTABLE *h, const void *k, size_t klen,
const void *v, size_t vlen)
{
struct genhash_entry_t *p;
enum tl_UPDATETYPE rv = 0;
p = genhash_find_entry(h, k, klen);
if (p) {
free_value(h, p->value);
p->value = dup_value(h, v, vlen);
rv = MODIFICATION;
} else {
if (-1 == tl_ht_store(h, k, klen, v, vlen)) {
rv = ALLOC_FAILURE;
}
rv = NEW;
}
return rv;
}
enum tl_UPDATETYPE tl_ht_funupdate(tl_HASHTABLE *h,
const void *k,
size_t klen,
void * (*upd)(const void *,
const void *,
size_t *,
void *),
void (*fr)(void *),
void *arg,
const void *def,
size_t deflen)
{
struct genhash_entry_t *p;
enum tl_UPDATETYPE rv = 0;
size_t newSize = 0;
p = genhash_find_entry(h, k, klen);
if (p) {
void *newValue = upd(k, p->value, &newSize, arg);
free_value(h, p->value);
p->value = dup_value(h, newValue, newSize);
fr(newValue);
rv = MODIFICATION;
} else {
void *newValue = upd(k, def, &newSize, arg);
tl_ht_store(h, k, klen, newValue, newSize);
fr(newValue);
rv = NEW;
}
(void)deflen;
return rv;
}
static void free_item(tl_HASHTABLE *h, struct genhash_entry_t *i)
{
assert(i);
free_key(h, i->key);
free_value(h, i->value);
free(i);
}
int tl_ht_del(tl_HASHTABLE *h, const void *k, size_t klen)
{
struct genhash_entry_t *deleteme = NULL;
size_t n = 0;
int rv = 0;
assert(h != NULL);
n = h->ops.hashfunc(k, klen) % h->size;
assert(n < h->size);
if (h->buckets[n] != NULL) {
/* Special case the first one */
if (h->ops.hasheq(h->buckets[n]->key, h->buckets[n]->nkey, k, klen)) {
deleteme = h->buckets[n];
h->buckets[n] = deleteme->next;
} else {
struct genhash_entry_t *p = NULL;
for (p = h->buckets[n]; deleteme == NULL && p->next != NULL; p = p->next) {
if (h->ops.hasheq(p->next->key, p->next->nkey, k, klen)) {
deleteme = p->next;
p->next = deleteme->next;
}
}
}
}
if (deleteme != NULL) {
free_item(h, deleteme);
rv++;
}
return rv;
}
int tl_ht_delall(tl_HASHTABLE *h, const void *k, size_t klen)
{
int rv = 0;
while (tl_ht_del(h, k, klen) == 1) {
rv++;
}
return rv;
}
void tl_ht_iter(tl_HASHTABLE *h,
void (*iterfunc)(const void *key, size_t nkey,
const void *val, size_t nval,
void *arg), void *arg)
{
size_t i = 0;
struct genhash_entry_t *p = NULL;
assert(h != NULL);
for (i = 0; i < h->size; i++) {
for (p = h->buckets[i]; p != NULL; p = p->next) {
iterfunc(p->key, p->nkey, p->value, p->nvalue, arg);
}
}
}
int tl_ht_clear(tl_HASHTABLE *h)
{
size_t i = 0;
int rv = 0;
assert(h != NULL);
for (i = 0; i < h->size; i++) {
while (h->buckets[i]) {
struct genhash_entry_t *p = NULL;
p = h->buckets[i];
h->buckets[i] = p->next;
free_item(h, p);
}
}
return rv;
}
static void count_entries(const void *key,
size_t klen,
const void *val,
size_t vlen,
void *arg)
{
int *count = (int *)arg;
(*count)++;
(void)key;
(void)klen;
(void)val;
(void)vlen;
}
int tl_ht_size(tl_HASHTABLE *h)
{
int rv = 0;
assert(h != NULL);
tl_ht_iter(h, count_entries, &rv);
return rv;
}
int tl_ht_sizekey(tl_HASHTABLE *h, const void *k, size_t klen)
{
int rv = 0;
assert(h != NULL);
tl_ht_iterkey(h, k, klen, count_entries, &rv);
return rv;
}
void tl_ht_iterkey(tl_HASHTABLE *h, const void *key, size_t klen,
void (*iterfunc)(const void *key, size_t klen,
const void *val, size_t vlen,
void *arg), void *arg)
{
size_t n = 0;
struct genhash_entry_t *p = NULL;
assert(h != NULL);
n = h->ops.hashfunc(key, klen) % h->size;
assert(n < h->size);
for (p = h->buckets[n]; p != NULL; p = p->next) {
if (h->ops.hasheq(key, klen, p->key, p->nkey)) {
iterfunc(p->key, p->nkey, p->value, p->nvalue, arg);
}
}
}
int tl_ht_strhash(const void *p, size_t nkey)
{
int rv = 5381;
int i = 0;
char *str = (char *)p;
for (i = 0; i < (int)nkey; i++) {
assert(str[i]);
rv = ((rv << 5) + rv) ^ str[i];
}
return rv;
}
tl_HASHTABLE* tl_ht_new(size_t est, struct tl_HASHOPS ops) {
tl_HASHTABLE *rv = NULL;
size_t size = 0;
if (est < 1) {
return NULL ;
}
assert(ops.hashfunc != NULL);
assert(ops.hasheq != NULL);
assert((ops.dup_key != NULL && ops.free_key != NULL) || ops.free_key == NULL);
assert((ops.dup_value != NULL && ops.free_value != NULL) || ops.free_value == NULL);
size = estimate_table_size(est);
rv = calloc(1,
sizeof(tl_HASHTABLE)
+ (size * sizeof(struct genhash_entry_t*)));
if (rv == NULL ) {
return NULL ;
}
rv->size = size;
rv->ops = ops;
return rv;
}
/**
* Convenience functions for creating string-based hashes
*/
static int
hasheq_strp(const void *a, size_t na, const void *b, size_t nb)
{
if (na != nb) {
return 0;
}
return memcmp(a, b, na) == 0;
}
static struct tl_HASHOPS hashops_nocopy = {
tl_ht_strhash,
hasheq_strp,
NULL,
NULL,
NULL,
NULL
};
static int u32_hash(const void *p, size_t n)
{
(void)p;
return n;
}
static int u32_eq(const void *a, size_t na, const void *b, size_t nb)
{
(void)a; (void)b;
return na == nb;
}
static struct tl_HASHOPS hashops_u32 = {
u32_hash,
u32_eq,
NULL,
NULL,
NULL,
NULL
};
tl_pHASHTABLE
tl_ht_stringnc_new(size_t est)
{
return tl_ht_new(est, hashops_nocopy);
}
tl_pHASHTABLE
tl_ht_szt_new(size_t est)
{
return tl_ht_new(est, hashops_u32);
}
|
C
|
/*
============================================================================
Name : voiwel.c
Author : abubakr
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
int main(void) {
char a;
printf ("insert a letter\n");
scanf("%c",&a);
switch(a)
{
case 'a':
case 'e':
case 'o':
case 'i':
case 'u':
printf ("the letter %c is a voiwel letter\n", a);
break;
default:
printf ("the letter %c isn't a voiwel letter\n", a);
}
}
|
C
|
#include <stdio.h>
typedef struct student {
char name[20];
int Kor, eng, mat;
double ave;
} STUDENT;
void main() {
STUDENT s1 = { "", 100,100,100,0.0 };
STUDENT s2 = { "ڳ", 90,80,88,0.0 };
STUDENT s3 = { "̸", 45,32,44,0.0 };
STUDENT* std[] = { &s1, &s2, &s3 };
for (int i = 0; i < 3; i++) {
std[i]->ave = (double)(std[i]->Kor + std[i]->eng + std[i]->mat) / 3;
printf("%s %.2lf\n", std[i]->name, std[i]->ave);
}
}
|
C
|
#include<stdio.h>
int binarySearch(int arr[], int n, int key) {
int l=0,h=n-1,mid;
int bool = 0;
while(l<=h) {
mid = (l+h)/2;
if(key == arr[mid]) {
bool =1;
return mid;
}
else if(key > arr[mid]) {
l = mid +1;
}
else {
h = mid -1;
}
}
if(bool == 1) {
return mid;
}
else {
return -1;
}
}
int main(){
int n;
scanf("%d",&n);
int arr[n];// = {10,20,30,40,50,60,70,88,90,100};
//int n = sizeof(arr)/sizeof(arr[0]);
printf("Array elements:- ");
for(int i=0;i<n;i++) {
scanf("%d",&arr[i]);
}
int key;
//printf("Size Of array: %d\n",n);
printf("Key: ");
scanf("%d",&key);
key = binarySearch(arr,n,key);
if(key == -1) {
printf("Element not found!!!");
}
else{
printf("Element is found at : %d\n",key);
}
return 0;
}
|
C
|
//WAP to Bubble Sort.
#include <stdio.h>
int main(void)
{
int n;
printf("Enter the Number of elements in the array: ");
scanf("%d", &n);
int data[n], temp;
printf("Enter the elements of the array to be sorted: \n");
for(int i=0; i<n; i++)
{
scanf("%d", &data[i]);
}
for(int i=0; i<=n-2; i++)
{
for(int j=0; j <= n-2-i; j++)
{
if (data[j+1] < data[j])
{
temp = data[j];
data[j] = data[j+1];
data[j+1] = temp;
}
}
}
printf("Sorted array is: \n");
for(int k=0; k<n; k++)
{
printf("%d ", data[k]);
}
printf("\n");
}
|
C
|
/**************************************************************************/
/* INCLUDES */
/**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
/**************************************************************************/
/* IMPORT METHODS */
/**************************************************************************/
#include "neural-network.h"
// #include "mnist-master/mnist.h"
/**************************************************************************/
/* TYPE DEFINITIONS & VARIABLES */
/**************************************************************************/
#define DEBUG 0
// #define USE_MNIST_LOADER
// #define MNIST_DOUBLE
static matrices trainData[1];
/**************************************************************************/
/* METHODS */
/**************************************************************************/
mnist_data *importMnistData(){
mnist_data *data; //.data och .label
unsigned int cnt;
int ret = 0, x, y, i, currData = 1;
// Returns 0 when all is good
if ((ret = mnist_load("traindata/train-images.idx3-ubyte", "traindata/train-labels.idx1-ubyte", &data, &cnt))) {
printf("An error occured: %d\n", ret);
} else {
printf("image count: %d\n", cnt);
printf("\nLabel for matrix: %u\n", data[currData].label);
for(i = 0; i < 28; i++)
printf("%3d ", i);
printf("\n");
for(y = 0; y < 28; y++){
for(x = 0; x < 28; x++){
if(data[currData].data[y][x] != 0)
printf("1 ");
else
printf(" ");
}
printf("\n");
}
printf("\n");
// free(data);
}
return data;
}
int main(int argc, char const *argv[]){
mnist_data *data;
int i, x, y, countTD = 0;
trainData[0].number = 1;
trainData[0].id = 0;
if(DEBUG){
// Print matrix
printf("\nCountTD: %d\n", countTD);
printf("\nId for matrix: %d \tNumber for matrix: %d\n", trainData[countTD].id, trainData[countTD].number);
for(i = 0; i < MATRIXSIZE; i++)
printf("%2d ", i);
printf("\n");
for(y = 0; y < MATRIXSIZE; y++){
for(x = 0; x < MATRIXSIZE; x++){
printf("%2d ", trainData[countTD].matrix[x][y]);
}
printf("\n");
}
printf("\n");
}
data = importMnistData();
neuralNetwork(data);
return 0;
}
|
C
|
#include <elf/elf.h>
#include <string.h>
#include <inttypes.h>
int
elf32_checkFile(Elf32_Ehdr *file)
{
if (file->e_ident[EI_MAG0] != ELFMAG0
|| file->e_ident[EI_MAG1] != ELFMAG1
|| file->e_ident[EI_MAG2] != ELFMAG2
|| file->e_ident[EI_MAG3] != ELFMAG3)
return -1; /* not an elf file */
if (file->e_ident[EI_CLASS] != ELFCLASS32)
return -2; /* not 32-bit file */
return 0; /* elf file looks OK */
}
/*
* Returns the number of program segments in this elf file.
*/
unsigned
elf32_getNumSections(Elf32_Ehdr *elfFile)
{
return elfFile->e_shnum;
}
char *
elf32_getStringTable(Elf32_Ehdr *elfFile)
{
Elf32_Shdr *sections = elf32_getSectionTable(elfFile);
return (char *)elfFile + sections[elfFile->e_shstrndx].sh_offset;
}
/* Returns a pointer to the program segment table, which is an array of
* ELF32_Phdr_t structs. The size of the array can be found by calling
* getNumProgramSegments. */
Elf32_Phdr *
elf32_getProgramSegmentTable(Elf32_Ehdr *elfFile)
{
Elf32_Ehdr *fileHdr = elfFile;
return (Elf32_Phdr *) (fileHdr->e_phoff + (long) elfFile);
}
/* Returns the number of program segments in this elf file. */
uint16_t
elf32_getNumProgramHeaders(Elf32_Ehdr *elfFile)
{
Elf32_Ehdr *fileHdr = elfFile;
return fileHdr->e_phnum;
}
char *
elf32_getSectionName(Elf32_Ehdr *elfFile, int i)
{
Elf32_Shdr *sections = elf32_getSectionTable(elfFile);
char *str_table = elf32_getSegmentStringTable(elfFile);
if (str_table == NULL) {
return "<corrupted>";
} else {
return str_table + sections[i].sh_name;
}
}
uint32_t
elf32_getSectionSize(Elf32_Ehdr *elfFile, int i)
{
Elf32_Shdr *sections = elf32_getSectionTable(elfFile);
return sections[i].sh_size;
}
uint32_t
elf32_getSectionAddr(Elf32_Ehdr *elfFile, int i)
{
Elf32_Shdr *sections = elf32_getSectionTable(elfFile);
return sections[i].sh_addr;
}
uint32_t
elf32_getSectioniVirtulAddr(Elf32_Ehdr *elfFile, int i)
{
Elf32_Shdr *sections = elf32_getSectionTable(elfFile);
return (uint32_t)elfFile + sections[i].sh_addr;
}
void *
elf32_getSection(Elf32_Ehdr *elfFile, int i)
{
Elf32_Shdr *sections = elf32_getSectionTable(elfFile);
return (char *)elfFile + sections[i].sh_offset;
}
void *
elf32_getSectionNamed(Elf32_Ehdr *elfFile, char *str)
{
int numSections = elf32_getNumSections(elfFile);
int i;
for (i = 0; i < numSections; i++) {
if (strcmp(str, elf32_getSectionName(elfFile, i)) == 0) {
return elf32_getSection(elfFile, i);
}
}
return NULL;
}
char *
elf32_getSegmentStringTable(Elf32_Ehdr *elfFile)
{
Elf32_Ehdr *fileHdr = (Elf32_Ehdr *) elfFile;
if (fileHdr->e_shstrndx == 0) {
return NULL;
} else {
return elf32_getStringTable(elfFile);
}
}
#ifdef ELF_DEBUG
void
elf32_printStringTable(Elf32_Ehdr *elfFile)
{
int counter;
Elf32_Shdr *sections = elf32_getSectionTable(elfFile);
char * stringTable;
if (!sections) {
printf("No sections.\n");
return;
}
stringTable = ((void *)elfFile) + sections[elfFile->e_shstrndx].sh_offset;
printf("File is %p; sections is %p; string table is %p\n", elfFile, sections, stringTable);
for (counter=0; counter < sections[elfFile->e_shstrndx].sh_size; counter++) {
printf("%02x %c ", stringTable[counter],
stringTable[counter] >= 0x20 ? stringTable[counter] : '.');
}
}
#endif
int
elf32_getSegmentType (Elf32_Ehdr *elfFile, int segment)
{
return elf32_getProgramSegmentTable(elfFile)[segment].p_type;
}
void
elf32_getSegmentInfo(Elf32_Ehdr *elfFile, int segment, uint64_t *p_vaddr, uint64_t *p_addr, uint64_t *p_filesz, uint64_t *p_offset, uint64_t *p_memsz)
{
Elf32_Phdr *segments;
segments = elf32_getProgramSegmentTable(elfFile);
*p_addr = segments[segment].p_paddr;
*p_vaddr = segments[segment].p_vaddr;
*p_filesz = segments[segment].p_filesz;
*p_offset = segments[segment].p_offset;
*p_memsz = segments[segment].p_memsz;
}
uint32_t
elf32_getEntryPoint (Elf32_Ehdr *elfFile)
{
return elfFile->e_entry;
}
/*
* Debugging functions
*/
/*
* prints out some details of one elf file
*/
void
elf32_fprintf(FILE *f, Elf32_Ehdr *file, int size, const char *name, int flags)
{
Elf32_Phdr *segments;
unsigned numSegments;
Elf32_Shdr *sections;
unsigned numSections;
int i, r;
// char *str_table;
fprintf(f, "Found an elf32 file called \"%s\" located "
"at address %p\n", name, file);
if ((r = elf32_checkFile(file)) != 0) {
char *magic = (char*) file;
fprintf(f, "Invalid elf file (%d)\n", r);
fprintf(f, "Magic is: %2.2hhx %2.2hhx %2.2hhx %2.2hhx\n",
magic[0], magic[1], magic[2], magic[3]);
return;
}
/*
* get a pointer to the table of program segments
*/
segments = elf32_getProgramHeaderTable(file);
numSegments = elf32_getNumProgramHeaders(file);
sections = elf32_getSectionTable(file);
numSections = elf32_getNumSections(file);
if ((uintptr_t) sections > ((uintptr_t) file + size)) {
fprintf(f, "Corrupted elfFile..\n");
return;
}
/*
* print out info about each section
*/
if (flags & ELF_PRINT_PROGRAM_HEADERS) {
/*
* print out info about each program segment
*/
fprintf(f, "Program Headers:\n");
fprintf(f, " Type Offset VirtAddr PhysAddr "
"FileSiz MemSiz Flg Align\n");
for (i = 0; i < numSegments; i++) {
if (segments[i].p_type != 1) {
fprintf(f, "segment %d is not loadable, "
"skipping\n", i);
} else {
fprintf(f, " LOAD 0x%06" PRIx32 " 0x%08" PRIx32 " 0x%08" PRIx32 \
" 0x%05" PRIx32" 0x%05" PRIx32 " %c%c%c 0x%04" PRIx32 "\n",
//fprintf(f, " LOAD 0x%" PRIxPTR " 0x%" PRIxPTR " 0x%" PRIxPTR
// " 0x%" PRIxPTR" 0x%" PRIxPTR " %c%c%c 0x%" PRIxPTR "\n",
segments[i].p_offset, segments[i].p_vaddr,
segments[i].p_paddr,
segments[i].p_filesz, segments[i].p_memsz,
segments[i].p_flags & PF_R ? 'R' : ' ',
segments[i].p_flags & PF_W ? 'W' : ' ',
segments[i].p_flags & PF_X ? 'E' : ' ',
segments[i].p_align);
}
}
}
if (flags & ELF_PRINT_SECTIONS) {
// str_table = elf32_getSegmentStringTable(file);
printf("Section Headers:\n");
printf(" [Nr] Name Type Addr Off\n");
for (i = 0; i < numSections; i++) {
//if (elf_checkSection(file, i) == 0) {
fprintf(f, "[%2d] %s %"PRIx32" %"PRIx32"\n", i, elf32_getSectionName(file, i),
//fprintf(f, "[%2d] %-17.17s %-15.15s %x %x\n", i, elf32_getSectionName(file, i), " ",
///fprintf(f, "%-17.17s %-15.15s %08x %06x\n", elf32_getSectionName(file, i), " " /* sections[i].sh_type
// */ ,
sections[i].sh_addr, sections[i].sh_offset);
//}
}
}
}
//append ...
Elf32_Word
elf32_getMappingSize(Elf32_Ehdr *elfFile) {
Elf32_Half ph_num = 0, i = 0;
Elf32_Word m_size = 0; // total aligned size of all segements with PT_LOAD flag
Elf32_Phdr *elf_phdr = elf32_getProgramSegmentTable(elfFile);
ph_num = elf32_getNumProgramHeaders(elfFile);
//printf(" ::Program Header Table::\n");
for( i=0; i<ph_num; i++ ) {
//printf("[%04d] 0x%08x 0x%08x\n", i, elf_phdr[i].p_memsz, elf_phdr[i].p_align);
if( elf_phdr[i].p_type == PT_LOAD ) {
m_size += ALIGN_SIZE( (elf_phdr[i].p_offset % elf_phdr[i].p_align + elf_phdr[i].p_filesz),
elf_phdr[i].p_align );
}
}
return m_size;
}
|
C
|
#include "apue.h"
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
//#define SHM_MODE 0600 /* user read/write */
int main(int argc, char *argv[]) {
int row = atoi(argv[1]);
int columns = atoi(argv[2]);
int column = atoi(argv[3]);
char* charmat1 = argv[4];
char* charmat2 = argv[5];
int mat1[25];
int mat2[25];
int i;
char *token;
int myint;
/*printf("***%s***", argv[4]);
printf("***%s***", argv[5]);
printf("\n");
fflush(stdout);*/
/* for(i= 0; charmat1[i]!= '\0'; i++){
mat1[i] =charmat1[i]-'0';
//printf("Arg5:[%d,%d]: %d",row,column,mat1[i]);
fflush(stdout);
}
//printf("\n");*/
token = strtok(charmat1, " ");
i =0;
//printf("\nMat1: \n");
while((token != NULL))
{
myint =atoi(token);
mat1[i] =myint;
//printf("[%d]",mat1[i]);
//fflush(stdout);
token = strtok(NULL, " ");
i++;
}
// printf("\nMat2: \n");
token = strtok(charmat2, " ");
i =0;
int counter = 0;
while((token != NULL))
{
counter++;
myint =atoi(token);
mat2[i] =myint;
//printf("[%d]",mat2[i]);
//fflush(stdout);
token = strtok(NULL, " ");
i++;
}
int value = 0;
for (i = 0; i<counter; i++) {
//printf("\n[%d]x[%d]\n",mat2[i],mat1[i]);
value = value + mat2[i]*mat1[i];
//printf("\nValue[%d,%d]: %d\n",row,column,value);
}
//printf("\nValue[%d,%d]: %d\n",row,column,value);
int id_shmem = atoi(argv[0]);
int *matrix;
if((matrix = shmat(id_shmem,0,0)) == (void *) - 1) {
perror("Cannot access shared memory.\n");
exit(1);
}
matrix[row*columns + column] = value; // Equivalent to matrix[column][row]
exit(2);
}
|
C
|
#include <rest/curl_output.h>
size_t curl_output_write_data_overwrite(char* restrict buffer, size_t size, size_t nmemb, void* restrict userp) {
size_t input_size = size * nmemb;
curl_output* output = (curl_output*)userp;
if(input_size + 1 > output->allocation_length){
output->memory = (char*)realloc(output->memory, input_size + 1);
if(!output->memory) {
return 0;
}
output->allocation_length = input_size + 1;
}
output->size = input_size;
memset(output->memory, 0, output->allocation_length);
memcpy(output->memory, buffer, input_size);
return input_size;
}
|
C
|
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <pthread.h>
#include <dirent.h>
#include <errno.h>
#include <semaphore.h>
#define SOD "SOD"
#define EOD "EOD"
#define SOC "SOC"
#define EOC "EOC"
#define DMP "DMP"
int infoCheck(char path[]);
void doTrim(char input[], size_t size);
void * listdir(void *name);
int doSend(int sockFd, char *msg);
int doRead(int sockFd, char *buffer);
void * sendFile(void *path);
char** split(char* line, char delimiter);
int getSocket(char *host, char *port);
char *sortColumn;
char *host;
char *port;
char *clientPoolSize;
pthread_mutex_t countLock;
pthread_mutex_t socketLock;
sem_t client_pool;
const int MAX_THREADS = 4096;
static int threadCount;
int main(int argc, const char * argv[]) {
char cwd[1024];
const char* usageMsg ="Usage: sorter_client -c <column name> -h <host> -p <port> [-d <source directory>] [-o <output directory>]";
if (argc < 3) {
fprintf(stderr, "%s\n", usageMsg);
exit(1);
}
int c;
const char *sourceDir = NULL;
const char *outDir = NULL;
while ((c = getopt (argc, argv, "c:d:o:h:p:s")) != -1)
switch (c)
{
case 'c':
sortColumn = optarg;
break;
case 'd':
sourceDir = optarg;
break;
case 'h':
host = optarg;
break;
case 'o':
outDir = optarg;
break;
case 'p':
port = optarg;
break;
case 's':
clientPoolSize = optarg;
break;
case '?':
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}
if (sortColumn == NULL || host == NULL || port == NULL) {
fprintf(stderr,"%s\n", usageMsg);
exit(1);
}
if (sourceDir == NULL) {
getcwd(cwd, sizeof(cwd));
sourceDir = cwd;
}
if (clientPoolSize == NULL) {
clientPoolSize = "10";
}
if (pthread_mutex_init(&countLock, NULL) != 0)
{
int errnum = errno;
fprintf(stderr, "Failed to initialize countLock mutex: %s\n", strerror(errnum));
exit(1);
}
if (pthread_mutex_init(&socketLock, NULL) != 0)
{
int errnum = errno;
fprintf(stderr, "Failed to initialize rowLock mutex: %s\n", strerror(errnum));
exit(1);
}
fflush(stdout);
pthread_t tid = 0;
sem_init(&client_pool, 0, atoi(clientPoolSize));
pthread_create(&tid, NULL, listdir, (void *) sourceDir);
printf("%ld,", tid);
pthread_join(tid, NULL);
// listdir(sourceDir);
threadCount++; // add one for the initial thread
printf("\n\tTotal number of threads: %d\n", threadCount);
// printf("main is exiting\n");
pthread_mutex_destroy(&countLock);
pthread_mutex_destroy(&socketLock);
char *fileName = calloc(1024, sizeof(char *));
strcat(fileName, "AllFiles-sorted-");
strcat(fileName, sortColumn);
strcat(fileName, ".csv");
char *outFilename;
long len = 0;
if (outDir == NULL) {
outDir = sourceDir;
}
len = strlen(outDir) + strlen(fileName) + 30;
outFilename=calloc(len, sizeof(char *));
strncpy(outFilename, outDir, strlen(outDir));
strcat(outFilename, "/");
strncat(outFilename, fileName, fileName);
// printf("outFilename: %s\n", outFilename);
FILE* ofp = fopen(outFilename, "w");
if (ofp == NULL) {
int errnum = errno;
fprintf(stderr, "Failed to open %s (%s)\n", outFilename, strerror(errnum));
exit(1);
}
printf("writing to file: %s\n", outFilename);
sem_wait(&client_pool);
int sockfd = getSocket(host, port);
sem_post(&client_pool);
printf("Sending 'DMP' command\n");
doSend(sockfd, DMP);
char buffer[2048] = {0};
int moreData = 1;
while(moreData) {
int bytesRead = doRead(sockfd, buffer);
if (strcmp(buffer, EOD) == 0) {
moreData = 0;
}
else {
fprintf(ofp, "%s\n", buffer);
}
memset(buffer, '\0', sizeof(buffer));
}
fclose(ofp);
sem_destroy(&client_pool);
exit(0);
}
void * listdir(void * name) {
DIR *dir = NULL;
int i=0;
struct dirent *entry = NULL;
pthread_t tid[MAX_THREADS];
// char paths[2048][1024] = {{0}};
char ** paths=calloc(MAX_THREADS,sizeof(char *));
int count = 0;
if (!(dir = opendir(name)))
pthread_exit(name);
// printf("In listdir current tid is: %i\n", pthread_self());
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
char *path = calloc(1024, sizeof(char*));
//memset(path, '\0', 1024);
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
// sprintf(path, "%s/%s", thisPath, entry->d_name);
//printf("%*s[%s]\n", indent, "", entry->d_name);
sprintf(path, "%s/%s", name, entry->d_name);
paths[count] = path;
//sprintf(&paths[count], path, strlen(path));
pthread_create(&tid[count], NULL, listdir, paths[count]);
// pthread_join(tid[count], NULL);
// printf("listdir thread: %i has completed for dir %s\n", tid, path);
pthread_mutex_lock(&countLock);
threadCount = threadCount + 1;
count++;
pthread_mutex_unlock(&countLock);
} else if (strrchr(entry->d_name, '.') != NULL) {
if (strcmp(strrchr(entry->d_name, '.'), ".csv") == 0) {
char *path = calloc(2048, sizeof(char*));
//memset(path, '\0', 1024);
sprintf(path, "%s/%s", name, entry->d_name);
if (infoCheck(path) == 0) {
continue;
} else {
//memcpy(&paths[count], path, strlen(path));
// sprintf(paths[count], "%s/%s", name, entry->d_name);
paths[count] = path;
if (pthread_create(&tid[count], NULL, sendFile, paths[count]) != 0) {
perror("failed to created sorter2 thread");
pthread_exit(NULL);
}
pthread_mutex_lock(&countLock);
threadCount = threadCount + 1;
count++;
pthread_mutex_unlock(&countLock);
}
}
}
}
closedir(dir);
for (i =0; i < count; i++) {
pthread_join(tid[i], NULL);
// printf("thread: %ld has completed \n", tid[i]);
}
// printf("this thread id is %d\n", pthread_self());
pthread_exit(name);
}
void * sendFile(void *path) {
printf("sending file: %s\n", path);
int bytesRead;
char buffer[2048] = {0};
size_t buffSize=1024;
FILE * fp=fopen(path, "r");
sem_wait(&client_pool);
int sockfd = getSocket(host, port);
sem_post(&client_pool);
if (sockfd == -1) {
perror("Failed to get socket");
return NULL;
}
if (fp == NULL) {
perror("Failed to open file");
close(sockfd);
return NULL;
}
char *input=(char *) malloc(buffSize+1);
while((bytesRead=getline(&input, &buffSize, fp))!=-1){
doTrim(input, bytesRead);
doSend(sockfd, input);
}
doSend(sockfd, EOD);
fclose(fp);
doSend(sockfd, sortColumn);
doSend(sockfd, EOC);
//Wait for server to complete the sort
bytesRead = doRead(sockfd, buffer);
printf("%s\n", buffer);
close(sockfd);
free(input);
return 0;
}
int doSend(int sockFd, char *msg) {
char buffer[2048] = {0};
int msgLen = strlen(msg);
size_t netLen = htonl(msgLen);
memcpy(buffer, &netLen, sizeof(size_t));
memcpy(buffer + sizeof(size_t), msg, msgLen);
return send(sockFd, (void *)buffer, msgLen+ sizeof(size_t), 0);
}
int doRead(int sockFd, char *buffer) {
size_t len;
// char lenBuff[_SIZE_T] = {0};
ssize_t totalBytesRead = 0;
while (totalBytesRead < sizeof(len)) {
ssize_t bytesRead = read(sockFd, &len + totalBytesRead, sizeof(size_t) - totalBytesRead);
totalBytesRead += bytesRead;
}
len = ntohl(len);
// printf("read %d bytes msg length %d\n", bytesRead, len);
totalBytesRead = 0;
while(totalBytesRead < len) {
ssize_t bytesRead = read(sockFd, buffer + totalBytesRead, len - totalBytesRead);
totalBytesRead += bytesRead;
}
// printf("read %d bytes msg %s\n", bytesRead, buffer);
return totalBytesRead;
}
int getSocket(char *host, char *port) {
struct sockaddr_in serv_addr;
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(host, port, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return(-1);
}
memset(&serv_addr, '0', sizeof(serv_addr));
pthread_mutex_lock(&countLock);
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
perror("connect");
close(sockfd);
continue;
}
break; // if we get here, we must have connected successfully
}
pthread_mutex_unlock(&countLock);
if (p == NULL) {
// looped off the end of the list with no connection
fprintf(stderr, "failed to connect\n");
return -1;
}
return sockfd;
}
void doTrim(char input[], size_t size) {
if (input[size-1]=='\n'){
input[size-1]='\0';
}
if (input[size-2]=='\r'){
input[size-2]='\0';
}
}
int infoCheck(char path[]){
FILE * fp=fopen(path, "r");
if (fp == NULL) {
fprintf(stderr, "infoCheck: failed to open file: %s (%s)\n", path, strerror(errno));
exit(1);
}
size_t buffSize=1024;
char **cols;
char * input;
input=(char *) malloc(buffSize+1);
int bytesRead=getline(&input, &buffSize, fp);
fclose(fp);
if(bytesRead==-1){
return 0;
}
doTrim(input, bytesRead);
cols=split(input, ',');
int i=0;
while(cols[i]!=NULL){
i++;
}
if(i==28){
return 1;
}
return 0;
}
char** split(char* line, char delimiter){
char * p1,* p2,* p3=NULL;
char ** cols=calloc(1024,sizeof(char *));
// strchr returns pointer after a ',' is found
p2=strchr(line, delimiter);
// p1 receives original pointer
p1=line;
int colCount=0;
long len=0;
while(p2!=NULL){
// p2 has a larger address, byte difference plus one assigned to len
len=(p2-p1)+1;
// space allocated for column entry, memory assigned
p3= malloc(len*sizeof(char *));
memset(p3, '\0', len);
memcpy(p3, p1, len-1);
// specified location assigned for value
cols[colCount]=p3;
// pointers moved
p1=p2+1;
if(*p1=='"'){
p2=strchr(p1+1,'"');
if(p2!=NULL){
p2=strchr(p1,delimiter);
}
}
else{
p2=strchr(p1, delimiter);
}
colCount++;
}
// for getting the last value in a line
if(p1 !=NULL&&strlen(p1)>0){
len=strlen(p1)+1;
p3=malloc(len*sizeof(char *));
memset(p3, '\0', len);
memcpy(p3, p1, len-1);
cols[colCount]=p3;
}
return cols;
}
|
C
|
#include <stdio.h>
int main() {
char * p = " are going to the park.\n";
FILE * fp;
fp = fopen("output.txt", "w+");
fputs("Mary and Paul", fp);
fseek(fp, 5, SEEK_SET);
fputs("is", fp);
p += 4;
fputs(p, fp);
fclose(fp);
return(0);
}
|
C
|
#include"factory.h"
void send_file(int sfd)
{
data d;
int fd;
fd=open(DOWNLOAD,O_RDONLY);
if(-1==fd)
{
perror("open");
exit(-1);
}
memset(&d,0,sizeof(d));
d.len=strlen(DOWNLOAD);
strcpy(d.buf,DOWNLOAD);
send_n(sfd,(char*)&d,d.len+4);
while(1)
{
memset(&d,0,sizeof(d));
d.len=read(fd,d.buf,sizeof(d.buf));
if(d.len<=0)
{
d.len=0;
send_n(sfd,(char*)&d,4);
break;
}
send_n(sfd,(char*)&d,d.len+4);
}
printf("send file success!\n");
close(sfd);
}
|
C
|
#include <stdio.h>
#include <math.h>//因为sqrt属于math.h的工具,而stdio.h不含这个,所以要添加
int main(void)
{
//计算一元二次方程
int a = 1; //赋值
int b = -678;
int c = 5;
double delta; //deltac存放b^2—4*a*c
double x1;
double x2; //存放x1 x2的值
delta = b * b - 4 * a * c;
if (delta > 0)
{
x1 = ((-b) + sqrt(delta)) / (2 * a);//sqrt 容易搞成squrt,要注意
x2 = ((-b) - sqrt(delta)) / (2 * a);
printf("有两个解,x1 = %f, x2 = %f\n", x1, x2);
}
else if (delta == 0)
{
x1 = (-b) / (2 * a);
x2 = x1;
printf("只有一个解, x1 = x2 = %f\n",x1);
}
else
{
printf("无解\n");
}
return 0;
}
|
C
|
//Linked-List
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
int tot_blocks, n_files, empty_blocks;
int initialize(bool blocks[], int next[], int SB[], int EB[])
{
for (int i = 0; i < tot_blocks; i++)
{
blocks[i] = false; // 0 - block free
next[i] = -1; // gives next bl_no
}
for (int i = 0; i < n_files; i++)
{
SB[i] = -1; // Starting Block_nos
EB[i] = -1; //Ending Block_nos
}
return 0;
}
int getBN(bool blocks[])
{
int j = 0, val = -1;
srand(time(0));
while (j == 0 && empty_blocks > 0)
{
val = rand() % tot_blocks;
if (blocks[val] == false)
{
blocks[val] = true;
j = 1;
}
}
return val;
}
int main()
{
int i, j;
printf("\n Enter the total number of blocks : ");
scanf("%d", &tot_blocks);
printf(" Enter total number of files : ");
scanf("%d", &n_files);
bool blocks[tot_blocks];
int next[tot_blocks];
int SB[n_files];
int EB[n_files];
int fileLen[n_files]; //Contains length of each file
int val, prev;
empty_blocks = tot_blocks;
initialize(blocks, next, SB, EB);
printf("\n Enter the length of the each file : \n");
for (i = 0; i < n_files; i++)
{
printf(" File %d - ", i);
scanf("%d", &fileLen[i]);
}
for (i = 0; i < n_files; i++)
{
if (fileLen[i] <= empty_blocks)
{
j = 1;
SB[i] = getBN(blocks);
j++;
prev = SB[i];
while (j <= fileLen[i])
{
next[prev] = getBN(blocks);
prev = next[prev];
j++;
empty_blocks--;
}
EB[i] = prev;
}
}
printf("\n File no. Starting block Ending Block\n");
for (i = 0; i < n_files; i++)
{
if (SB[i] != -1)
printf(" %d %d %d\n", i, SB[i],
EB[i]);
else
printf(" %d Couldn't be allocated\n", i);
}
printf("\n File no.\t Path\n");
for (i = 0; i < n_files; i++)
{
printf(" %d\t ", i);
if (SB[i] != -1)
{
int p = SB[i];
while (p != -1)
{
printf(" %d -> ", p);
p = next[p];
}
printf(" NULL\n");
}
else
printf(" None");
}
printf("\n");
return 0;
}
|
C
|
/**
* グラフィック液晶モジュールAQM1248のテンプレートライブラリ
*/
#if defined(__AVR__)
# include <avr/pgmspace.h>
# include <util/delay.h>
#elif defined(__linux__)
# include <unistd.h>
# define pgm_read_byte(a) (*(a))
# define _delay_ms(x) usleep((x) * 1000)
#else
# error ""
#endif
#include "libglcd.h"
/*======================================================================
* 初期化
*/
void glcd_init(void)
{
glcd_select_cmd();
glcd_send_byte(0xae); /* display = off */
glcd_send_byte(0xa0); /* ADC(address counter?) = normal */
glcd_send_byte(0xc8); /* common output = reverse*/
glcd_send_byte(0xa3); /* LCD bias = 1/7 */
glcd_send_byte(0x2c); /* power control 1 */
_delay_ms(2);
glcd_send_byte(0x2e); /* power control 2 */
_delay_ms(2);
glcd_send_byte(0x2f); /* power control 3 */
glcd_send_byte(0x23);
glcd_send_byte(0x81);
glcd_send_byte(0x19);
glcd_send_byte(0xa4); /* display all point = normal*/
glcd_send_byte(0x40); /* display start line = 0 */
glcd_send_byte(0xa6); /* common output = normal */
glcd_send_byte(0xaf); /* display = on */
glcd_clear_vram();
}
/*======================================================================
* 低レベルコマンドの発行
* 呼び出し前にコマンド送信可能(SPI有効、SSアサート済、RS=コマンド)であること
*/
void glcd_display_on(void)
{
glcd_send_byte(0xae);
}
void glcd_display_off(void)
{
glcd_send_byte(0xaf);
}
void glcd_set_display_row(uint8_t row)
{
glcd_send_byte(0x40 | row);
}
void glcd_set_addr_page(uint8_t page)
{
glcd_send_byte(0xb0 | page);
}
void glcd_set_addr_col(uint8_t col)
{
glcd_send_byte(0x10 | (col >> 4));
glcd_send_byte(0x00 | (col & 0xf));
}
void glcd_set_resistor_ratio(uint8_t val)
{
glcd_send_byte(0x20 | val);
}
void glcd_set_contrast(uint8_t val)
{
glcd_send_byte(0x81);
glcd_send_byte(val);
}
void glcd_set_sleep_mode(void)
{
glcd_send_byte(0xac);
glcd_send_byte(0x00);
}
void glcd_leave_sleep_mode(void)
{
glcd_send_byte(0xad);
glcd_send_byte(0x00);
}
/*======================================================================
* ブロック書き込み・ブロックフィル
*/
/*
* ブロックデータを書き込む
*/
void glcd_write_block(uint8_t sx, uint8_t sy, uint8_t w, uint8_t h,
const uint8_t *p)
{
uint8_t x, y;
for(y = 0; y < h; y++) {
glcd_select_cmd();
glcd_set_addr_page(sy + y);
glcd_set_addr_col(sx);
glcd_select_data();
#ifdef HAVE_BLOCK_TRANSFER
glcd_send_block(p, w);
p += w;
#else
for(x = 0; x < w; x++)
glcd_send_byte(*p++);
#endif
}
glcd_select_cmd();
}
/*
* ブロックデータを書き込む
*/
void glcd_write_blockp(uint8_t sx, uint8_t sy, uint8_t w, uint8_t h,
const uint8_t *p)
{
uint8_t x, y;
for(y = 0; y < h; y++) {
glcd_select_cmd();
glcd_set_addr_page(sy + y);
glcd_set_addr_col(sx);
glcd_select_data();
#ifdef HAVE_BLOCK_TRANSFER
glcd_send_block(p, w);
p += w;
#else
for(x = 0; x < w; x++)
glcd_send_byte(pgm_read_byte(p++));
#endif
}
glcd_select_cmd();
}
/*
* 表示メモリを指定値でフィルする
*/
void glcd_fill_vram(uint8_t sx, uint8_t sy, uint8_t w, uint8_t h, uint8_t ptn)
{
uint8_t x, y;
for(y = 0; y < h; y++) {
glcd_select_cmd();
glcd_set_addr_page(sy + y);
glcd_set_addr_col(sx);
glcd_select_data();
for(x = 0; x < w; x++)
glcd_send_byte(ptn);
}
glcd_select_cmd();
}
/*
* 表示メモリをクリアする
*/
void glcd_clear_vram(void)
{
glcd_fill_vram(0, 0, GLCD_WIDTH, GLCD_VRAM_PAGES, 0);
}
|
C
|
#include "hash.h"
#include <stdio.h>
#define ERRO_NUMERO_DE_ARGUMENTOS 1
#define MAX_TAM_LINHA 1000000
#define MAX_TAM 2500
int comparPalavras(const void *p1, const void *p2)
{
const char **ip1 = (const char **)p1;
const char **ip2 = (const char **)p2;
return strcmp(*ip1, *ip2);
}
int main(int argc, char *argv[])
{
if(argc != 3)
{
printf("Uso: %s <arquivo-de-texto> <arquivo-de-palavras-chave>\n", argv[0]);
return ERRO_NUMERO_DE_ARGUMENTOS;
}
char Linha[MAX_TAM_LINHA];
char *palavrasChave[MAX_TAM];
FILE *arqPalavras = fopen(argv[2], "r");
//Criando hash map
const unsigned long tamHash = 1.33 * contaLinhas(argv[2]);
hash *hashMap = criarHash(tamHash);
//Inicializando hash
initHash(hashMap);
int tamanho = 0;
//Lendo palavras que serão pesquisadas e adicionando na hash
while (fgets(Linha, 256, arqPalavras) != NULL)
{
Linha[strlen(Linha)-1] = '\0';
addPalavraHash(hashMap, criaPalavra(Linha));
palavrasChave[tamanho] = malloc((strlen(Linha) + 1) * sizeof(char));
strcpy(palavrasChave[tamanho], Linha);
tamanho++;
}
//Lendo as palavras e contando ocorrencias
LePalavras("Alfabeto.txt", "Texto.txt", MODE_HASH, hashMap);
//Printar ocorrencias
int i;
qsort(palavrasChave, tamanho, sizeof(char *), comparPalavras);
for (i = 0; i < tamanho; i++)
{
printPalavra(buscaHash(hashMap, palavrasChave[i]));
}
//free na hash
freeHash(hashMap); //consertar o free de palavra
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int andar[3], a1, a2, a3;
scanf("%d %d %d", &a1, &a2, &a3);
andar[0] = 2 * a2 + 4 * a3;
andar[1] = 2 * a1 + 2 * a3;
andar[2] = 2 * a2 + 4 * a1;
if (andar[0] <= andar[1] && andar[0] <= andar[2])
{
printf("%d\n", andar[0]);
}
else if (andar[1] <= andar[0] && andar[1] <= andar[2])
{
printf("%d\n", andar[1]);
}
else
{
printf("%d\n", andar[2]);
}
return 0;
}
|
C
|
/*
* serveur.c
*
* Created on: 8 mars 2016
* Author: Quincy
*/
#include <stdio.h> /* printf */
#include <stdlib.h> /* system, NULL, EXIT_FAILURE */
#include <unistd.h>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/socket.h> /* socket, bind*/
#include <sys/select.h> /* select */
#include <sys/types.h>
#include <sys/un.h> /* sockaddr_un */
#include <signal.h>
#include <string.h> /* memset */
const char socketPath[14] = "/tmp/soquette";
int maxConnection = 4;
int maxSocketFd = -1;
int socketServerFd = -1;
int allSocketFd[4] = {-1, -1, -1, -1};
fd_set masterFdSet;
int addConnection(int socketId)
{
for(int index=1; index<maxConnection; index++)
{
printf("Checking allSocketFd[%d]= %d\n", index, allSocketFd[index]);
if(allSocketFd[index]==-1)
{
allSocketFd[index] = socketId;
return index;
}
}
return -1;
}
int main (int argc, char* argv[])
{
socketServerFd = socket(PF_LOCAL, SOCK_STREAM, 0); //In Mac PF_LOCAL=PF_UNIX
if(socketServerFd==-1)
perror("Create socket failed");
else
printf("Socket %d created.\n", socketServerFd);
unlink(socketPath);
struct sockaddr_un addr;
memset((void*)&addr, 0, sizeof(struct sockaddr_un));
addr.sun_family = AF_UNIX;
sprintf(addr.sun_path, socketPath);
int brc = bind(socketServerFd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un));
if(brc<0)
perror("Unable to bind socket");
int lrc = listen(socketServerFd, 0);
if(lrc<0)
perror("Unable to listen to socket");
else
printf("Server is now listening on socket %d...\n", socketServerFd);
FD_ZERO(&masterFdSet);
maxSocketFd = socketServerFd;
allSocketFd[0] = socketServerFd;
FD_SET(socketServerFd, &masterFdSet);
socklen_t addrLength;
int connCount = 0;
int temp = 5;
while(temp)
{
temp--;
fd_set readSet;
FD_COPY(&masterFdSet, &readSet);
int selectrc = select(maxSocketFd+1, &readSet, NULL, NULL, NULL);
if(selectrc==-1)
perror("Error on select");
for(int index=0; index<maxConnection; index++)
{
int oneSocketFd = allSocketFd[index];
if(oneSocketFd!=-1)
{
printf("Server checking FD(%d): %d\n", index, oneSocketFd);
if(FD_ISSET(oneSocketFd, &readSet))
{
if(oneSocketFd==socketServerFd)
{
int socketClient = accept(socketServerFd, (struct sockaddr *) &addr, &addrLength);
if(socketClient<0)
perror("Accept socket connection failed");
else
{
FD_SET(socketClient, &masterFdSet);
int nAddConnAt = addConnection(socketClient);
printf("Client %d connected. Stored in array[%d]/%d\n", socketClient, nAddConnAt, connCount);
if(socketClient>maxSocketFd)
maxSocketFd = socketClient;
connCount++;
}
}
else
{
char buffer[257];
int nRecievedBytes = recv(oneSocketFd, &buffer, 256, 0);
printf("Message size: %d\n", nRecievedBytes);
if(nRecievedBytes!=0)
{
buffer[nRecievedBytes] = 0; //Add end of string in the recieved message
printf("Message from client: %s\n", buffer);
}
else
{
allSocketFd[index] = -1;
printf("Client %d closed connection: %d\n", oneSocketFd, index);
}
}
}
}
}
}
unlink(socketPath);
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int arr[][3] = {1,2,3,4,5};
int (*p)[3] = arr;
printf("%d\n", *(*(p+1)+3));
long long int pop = 100000000000000023;
float f1 = 3.4E39,f2 = 1.2323212327812;
printf("%lld,%e,%f\n",pop,f1,f2);
getchar();
return 0;
}
|
C
|
/* mqtt4modbus
* modbus tcp/rtu via mqtt
* author: daixijiang@gmail.com
*/
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <modbus.h>
#include "common.h"
typedef struct
{
const char *address; /* ttySN*/
int baudrate;
modbus_t *ctx;
int slaveid;
} mbslave_t;
mbslave_t g_mbx={.address=NULL,.ctx=NULL,.slaveid=0};
void mb_connect(int slaveid)
{
mbslave_t *mbp = &g_mbx;
if (mbp->ctx) {
modbus_close(mbp->ctx);
modbus_free(mbp->ctx);
}
mbp->slaveid = slaveid;
printf("------- modbus: %s %d, 'N', 8, 1 slaveid=%d\r\n",mbp->address,mbp->baudrate, mbp->slaveid);
mbp->ctx = modbus_new_rtu(mbp->address, mbp->baudrate, 'N', 8, 1);
if (mbp->ctx == NULL) {
fprintf(stderr, "modbus_new_rtu: Call failed\n");
//exit(EXIT_FAILURE);
}
if (modbus_set_slave(mbp->ctx, mbp->slaveid) == -1) {
fprintf(stderr, "modbus_set_slave: %s on slave %d\n", modbus_strerror(errno), mbp->slaveid);
//exit(EXIT_FAILURE);
}
if (modbus_connect(mbp->ctx) == -1) {
fprintf(stderr, "modbus_connect: %s on slave %d \n", modbus_strerror(errno), mbp->slaveid);
//exit(EXIT_FAILURE);
}
/* Define a new timeout of 200ms */
modbus_set_response_timeout(mbp->ctx, 0, 200000);
modbus_set_debug(mbp->ctx, TRUE); //Dubugģʽ
modbus_set_error_recovery(mbp->ctx, MODBUS_ERROR_RECOVERY_LINK | MODBUS_ERROR_RECOVERY_PROTOCOL);
//modbus_flush(mbp->ctx);
}
void mb_cleanup(void)
{
if(g_mbx.ctx)
{
printf(">>> mb_cleanup\n");
modbus_close(g_mbx.ctx);
modbus_free(g_mbx.ctx);
g_mbx.ctx=NULL;
}
}
int mb_write_bit(int slaveid,int address, bool state)
{
int ret =-1;
mbslave_t *mbp = &g_mbx;
if (mbp->ctx&&mbp->slaveid!=slaveid) {
mbp->slaveid = slaveid;
modbus_set_slave(mbp->ctx, mbp->slaveid);
}
fprintf(stdout, "modbus: wite bit address(%d) on slave %d \n", address, mbp->slaveid);
if (mbp->ctx && (ret=modbus_write_bit(mbp->ctx, address, state) == -1)) {
fprintf(stderr, "modbus_write_bit: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
//exit(EXIT_FAILURE);
if (MODBUS_ENOBASE > errno) {
mb_connect(slaveid);
if (mbp->ctx && (ret=modbus_write_bit(mbp->ctx, address, state) == -1)) {
fprintf(stderr, "modbus_write_bit2: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
}
}
}
return ret;
}
int mb_write_bits(int slaveid,int address, int nb, const uint8_t *data)
{
int ret =-1;
mbslave_t *mbp = &g_mbx;
if (mbp->ctx&&mbp->slaveid!=slaveid) {
mbp->slaveid = slaveid;
modbus_set_slave(mbp->ctx, mbp->slaveid);
}
fprintf(stdout, "modbus: wite bit address(%d) on slave %d \n", address, mbp->slaveid);
if (mbp->ctx && (ret=modbus_write_bits(mbp->ctx, address,nb, data) == -1)) {
fprintf(stderr, "modbus_write_bits: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
//exit(EXIT_FAILURE);
if (MODBUS_ENOBASE > errno) {
mb_connect(slaveid);
if (mbp->ctx && (ret=modbus_write_bits(mbp->ctx, address,nb, data) == -1)) {
fprintf(stderr, "modbus_write_bits2: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
}
}
}
return ret;
}
int mb_write_register(int slaveid,int address, const uint16_t value)
{
int ret =-1;
mbslave_t *mbp = &g_mbx;
if (mbp->ctx&&mbp->slaveid!=slaveid) {
mbp->slaveid = slaveid;
modbus_set_slave(mbp->ctx, mbp->slaveid);
}
fprintf(stdout, "modbus: wite register address(%d) on slave %d \n", address, mbp->slaveid);
if (mbp->ctx && (ret=modbus_write_register(mbp->ctx, address, value) == -1)) {
fprintf(stderr, "mb_write_register: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
//exit(EXIT_FAILURE);
if (MODBUS_ENOBASE > errno) {
mb_connect(slaveid);
if (mbp->ctx && (ret=modbus_write_register(mbp->ctx, address, value) == -1)) {
fprintf(stderr, "mb_write_register2: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
}
}
}
return ret;
}
int mb_write_registers(int slaveid,int address, int nb, const uint16_t *data)
{
int ret =-1;
mbslave_t *mbp = &g_mbx;
if (mbp->ctx&&mbp->slaveid!=slaveid) {
mbp->slaveid = slaveid;
modbus_set_slave(mbp->ctx, mbp->slaveid);
}
if (mbp->ctx && (ret=modbus_write_registers(mbp->ctx, address,nb, data) == -1)) {
fprintf(stderr, "mb_write_registers: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
//exit(EXIT_FAILURE);
if (MODBUS_ENOBASE > errno) {
mb_connect(slaveid);
if (mbp->ctx && (ret=modbus_write_registers(mbp->ctx, address,nb, data) == -1)) {
fprintf(stderr, "mb_write_registers: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
}
}
}
return ret;
}
int mb_read_bits(int slaveid,int address, int nb, uint8_t *data)
{
int ret =-1;
mbslave_t *mbp = &g_mbx;
if (mbp->ctx&&mbp->slaveid!=slaveid) {
mbp->slaveid = slaveid;
modbus_set_slave(mbp->ctx, mbp->slaveid);
}
if (mbp->ctx && (ret=modbus_read_bits(mbp->ctx, address, nb, data) == -1)) {
fprintf(stderr, "modbus_read_bits: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
//exit(EXIT_FAILURE);
if (MODBUS_ENOBASE > errno) {
mb_connect(slaveid);
if (mbp->ctx && (ret=modbus_read_bits(mbp->ctx, address, nb, data) == -1)) {
fprintf(stderr, "modbus_read_bits 2: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
//exit(EXIT_FAILURE);
}
}
}
return ret;
}
int mb_read_input_bits(int slaveid,int address, int nb, uint8_t *data)
{
int ret =-1;
mbslave_t *mbp = &g_mbx;
if (mbp->ctx&&mbp->slaveid!=slaveid) {
mbp->slaveid = slaveid;
modbus_set_slave(mbp->ctx, mbp->slaveid);
}
if (mbp->ctx && (ret=modbus_read_input_bits(mbp->ctx, address, nb, data) == -1)) {
fprintf(stderr, "modbus_read_input_bits: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
//exit(EXIT_FAILURE);
if (MODBUS_ENOBASE > errno) {
mb_connect(slaveid);
if (mbp->ctx && (ret=modbus_read_bits(mbp->ctx, address, nb, data) == -1)) {
fprintf(stderr, "modbus_read_input_bits 2: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
//exit(EXIT_FAILURE);
}
}
}
return ret;
}
int mb_read_register(int slaveid,int address, int nb, uint16_t *data)
{
int ret =-1;
mbslave_t *mbp = &g_mbx;
if (mbp->ctx&&mbp->slaveid!=slaveid) {
mbp->slaveid = slaveid;
modbus_set_slave(mbp->ctx, mbp->slaveid);
}
if (mbp->ctx && (ret=modbus_read_registers(mbp->ctx, address, nb, data) == -1)) {
fprintf(stderr, "modbus_read_registers: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
//exit(EXIT_FAILURE);
if (MODBUS_ENOBASE > errno) {
mb_connect(slaveid);
if (mbp->ctx && (ret=modbus_read_registers(mbp->ctx, address, nb, data) == -1)) {
fprintf(stderr, "modbus_read_registers 2: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
//exit(EXIT_FAILURE);
}
}
}
return ret;
}
int mb_read_input_register(int slaveid,int address, int nb, uint16_t *data)
{
int ret =-1;
mbslave_t *mbp = &g_mbx;
if (mbp->ctx&&mbp->slaveid!=slaveid) {
mbp->slaveid = slaveid;
modbus_set_slave(mbp->ctx, mbp->slaveid);
}
if (mbp->ctx && (ret=modbus_read_input_registers(mbp->ctx, address, nb, data) == -1)) {
fprintf(stderr, "modbus_read_input_registers: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
//exit(EXIT_FAILURE);
if (MODBUS_ENOBASE > errno) {
mb_connect(slaveid);
if (mbp->ctx && (ret=modbus_read_input_registers(mbp->ctx, address, nb, data) == -1)) {
fprintf(stderr, "modbus_read_input_registers 2: %s(%d) on slave %d \n", modbus_strerror(errno), errno, mbp->slaveid);
//exit(EXIT_FAILURE);
}
}
}
return ret;
}
void mb_init(const char* uart,int baudrate,int slaveid)
{
g_mbx.address = uart;
g_mbx.baudrate = baudrate;
mb_connect(slaveid);
}
|
C
|
/* GROUP No. 29
2017A7PS0004P -- SUBHAM KUMAR DASH
2017A7PS0036P -- RAHUL JHA
2017A7PS0084P -- ANIRUDDHA JAYANT KARAJGI
2017A7PS0128P -- MEET KANANI
2017A7PS0193P -- AYUSH GARG
*/
#include "parser.h"
#include "lexer.h"
#include "ast.h"
#include "semanticAnalyzer.h"
#include "symbolTable.h"
#include "codegen.h"
#include <time.h>
extern Table *baseTb;
int main(int argc, char *argv[])
{
printf("\n\nLEVEL 4: Symbol table / Type Checking / Semantic rules modules works / handled static and dynamic arrays in type checking and code generation\n");
printf("------------------------------------------------------------------------------------------\n\n");
if (argc < 3)
{
printf(
"USAGE\n"
"=====\n\n"
"The command line arguments for execution of the driver should be as follows:\n\n"
"\t\t$./compiler testcase.txt code.asm\n\n");
exit(0);
}
Grammar *gm = initialize();
gm = make_table("grammar.txt", gm);
printf("-------Grammar Loaded into the appropriate data structure------------\n\n");
FirstAndFollow *firstFol = initializeFirstFollow();
ComputeFirstAndFollowSets(gm, firstFol);
printf("-------First and Follow Sets Created-------\n\n");
ParseTable *pt = initializeParseTable();
populateParseTable(firstFol, gm, pt);
printf("-------Parsing Table Populated-------\n\n");
ParseTree *pTree = NULL;
astNode *ast = NULL;
int code_parsed = 0;
int num_syn_err = 0; //number of syntax error
int num_sem_err = 0; //number of semantic error
int astCreated = 0;
while (1)
{
printf("\nPlease choose an option\n");
printf("========================= \n\n");
printf("0: For exiting.\n");
printf("1: For printing the token list generated by the lexer\n");
printf("2: For parsing to verify the syntactic correctness of the input source code and to produce parse tree\n");
printf("3: For printing the Abstract Syntax Tree in appropriate format\n");
printf("4: For displaying the amount of allocated memory and number of nodes to each of parse tree and abstract syntax tree\n");
printf("5: For printing the Symbol Table\n");
printf("6: For printing the total memory requirement for each module\n");
printf("7: For printing the type expressions and width of array variables\n");
printf("8: For compiling to verify the syntactic and semantic correctness of the input source code\n");
printf("9: For producing assembly code\n");
printf("\n\nYour Input: ");
int option;
scanf("%d", &option);
printf("\n");
printf("Selected option: %d\n", option);
printf("----------------------\n\n");
getchar();
switch (option)
{
case 0:
printf("Exiting...\n");
exit(0);
break;
case 1:
printTokens(argv[1]);
break;
case 2:
pTree = parseInputSourceCode(argv[1], pt, gm, firstFol, &num_syn_err);
if (pTree)
{
code_parsed = 1;
printf("------------------ Parse Tree Built --------------\n\n");
int temp;
printf("Do you want to print the Parse Tree : '1' for YES and '0' for NO: ");
scanf("%d", &temp);
if (temp == 1)
printParseTree_inorder(pTree->root);
}
break;
case 3:
// num_syn_err = 0;
// num_sem_err = 0;
// pTree = parseInputSourceCode(argv[1], pt, gm, firstFol, &num_syn_err);
if (code_parsed == 0)
printf("\n-----------Parse Tree not yet created. Select option 2 first ----------------\n");
else
{
if (num_syn_err)
printf("\n\nAST can't be constructed since the code has Syntax Errors\n\n");
else
{
ast = postOrder_ParseTree(pTree);
printf("\n\n-----------------------------------Printing AST (Preorder Traversal)----------------------------------\n\n");
printAst(ast);
printf("\n\n----------------------------AST Printed in Preorder Fashion (Node first, and then children)----------------------------\n\n");
astCreated = 1;
}
}
break;
case 4:
{
if (pTree == NULL || ast == NULL)
{
printf("\n--------ParseTree or AST not built yet------------\n");
}
else
{
Compression_Ratio_calc(pTree->root, ast);
}
}
break;
case 5:
if (baseTb == NULL)
{
if (pTree == NULL)
pTree = parseInputSourceCode(argv[1], pt, gm, firstFol, &num_syn_err);
if (ast == NULL)
ast = postOrder_ParseTree(pTree);
error_list *errors = init_errors();
Table *tb = populateSymbolTable(ast, errors);
printSymbolTable(tb);
}
else
{
printSymbolTable(baseTb);
}
break;
case 6:
{
if (baseTb == NULL)
{
printf("\n------------SymbolTable not yet built. Select option 5 first --------------\n");
}
else
{
calcMemoryofFunctions(baseTb);
}
}
break;
case 7:
if (baseTb == NULL)
{
if (pTree == NULL)
pTree = parseInputSourceCode(argv[1], pt, gm, firstFol, &num_syn_err);
if (ast == NULL)
ast = postOrder_ParseTree(pTree);
error_list *errors = init_errors();
Table *tb = populateSymbolTable(ast, errors);
printArrays(tb);
printf("\n------------SymbolTable not yet built. Select Option 5 first --------------\n");
}
else
{
// printf("Hello\n");
printArrays(baseTb);
}
break;
case 8:
{
num_syn_err = 0;
num_sem_err = 0;
clock_t start_time, end_time;
double total_CPU_time, total_CPU_time_in_seconds;
start_time = clock();
if (pTree == NULL)
pTree = parseInputSourceCode(argv[1], pt, gm, firstFol, &num_syn_err);
if (pTree)
{
if (num_syn_err)
printf("\n\n------------------------Syntax Errors Reported-----------------------\n\n");
else
{
printf("\n\n---------------------------Semantic Analysis Begins---------------------------\n\n");
if (ast == NULL)
ast = postOrder_ParseTree(pTree);
error_list *errors = init_errors();
Table *tb = populateSymbolTable(ast, errors);
traverse_AST(ast, errors);
if (errors->head != NULL)
{
num_sem_err = errors->err_total;
printf("\n\n------------------------Semantic Errors Reported -------------------------\n");
printSemanticErrors(errors);
}
else
{
printf("\n\n------------------No syntax or semantic errors----------------\n\n");
}
}
}
end_time = clock();
printf("\n");
printf("Execution Summary\n");
printf("=================\n");
printf("Start Time: \t\t\t %lf\n", (double)start_time);
printf("End Time: \t\t\t %lf\n", (double)end_time);
total_CPU_time = (double)(end_time - start_time);
total_CPU_time_in_seconds = total_CPU_time / (double)CLOCKS_PER_SEC;
printf("Total CPU time: \t\t %8.10f\n", total_CPU_time);
printf("Total CPU time (in sec): \t %8.10f \n", total_CPU_time_in_seconds);
}
break;
case 9:
{
num_syn_err = 0;
num_sem_err = 0;
if (pTree == NULL)
pTree = parseInputSourceCode(argv[1], pt, gm, firstFol, &num_syn_err);
if (pTree)
{
if (num_syn_err)
printf("\n\n------------------------Syntax Errors Reported-----------------------\n\n");
else
{
printf("\n\n---------------------------Semantic Analysis Begins---------------------------\n\n");
if (ast == NULL)
ast = postOrder_ParseTree(pTree);
error_list *errors = init_errors();
Table *tb = populateSymbolTable(ast, errors);
traverse_AST(ast, errors);
if (errors->head != NULL)
{
num_sem_err = errors->err_total;
printSemanticErrors(errors);
printf("\n\n------------------------Semantic Errors Reported : Unsuccessful Compilation-------------------------\n\n");
}
else
{
printf("\n\n------------------Compilation Successful----------------\n\n");
generate_assembly_code(ast, argv[2]);
printf("\n\n-------------------ASM Code Generated----------------\n");
}
}
}
}
break;
default:
printf("Invalid option provided....\n");
continue;
}
}
}
|
C
|
#include <stdio.h>
#include "user.h"
/*
ԴļʹõԶ庯
*/
extern int tot, N, vote_end;
extern struct user user[100];
extern int choice_main, choice_admin, choice_logon_regist, choice_user;
extern char name[20], phone[12], passwd[20];
extern char search_name[20];
/*
βΣuserûݵĽṹ飻totܳ
ֵ
ܣʾÿһͨûϢ
*/
void information_users(struct user user[], int tot)
{
int i;
printf(" ----------------------------------------------------- \n");
printf("| עûϢ |\n");
printf("| û\tֻ\t\tͶƱ |\n");
for (i=0; i<tot; i++)
{
if (user[i].user_type == 1)//user_type = 1 ˵ͨû
{
printf("| %s\t%s\t%d |\n", user[i].name, user[i].phone, user[i].vote_num);
}
}
printf(" ----------------------------------------------------- \n");
}
/*
βΣuserûݵĽṹ飻nܳȣuser_condidate洢ѡϢĽṹ
ֵuser_condidateṹij
ܣܵ洢ûϢĽṹɸѡѡߵϢuser_condidateṹУuser_condidate鰴vote_numԱӸߵ
*/
int sort(struct user user[], int n, struct user user_condidate[])
{
int i, j;
int m = 0;
struct user temp;
for (i=0; i<n; i++)
{
if (user[i].user_type == 0)
{
user_condidate[m] = user[i];
m++;
}
}
for (i=0; i<m; i++)//ѡյƱӸߵ
{
for (j=i + 1; j<m; j++)
{
if (user_condidate[i].vote_num < user_condidate[j].vote_num)
{
temp = user_condidate[i];
user_condidate[i] = user_condidate[j];
user_condidate[j] = temp;
}
}
}
return m;
}
/*
βΣuserûݵĽṹ飻totܳ
ֵ
ܣʾÿһѡߵϢǰƱӸߵʾÿһλĵƱ
*/
void information_condidate(struct user user[], int tot)
{
int i;
double sum = 0;
int tot_condidate = 0;
struct user user_codidate[100];
printf(" ----------------------------------------------------- \n");
printf("| ѡϢ |\n");
if (vote_end == 1)//ݹԱǷͶƱʾûзʱʾƱ
{
printf("| ѡ\tƱ\t\tٷֱ |\n");
for (i=0; i<tot; i++)
{
if (user[i].user_type == 0)
{
sum += user[i].vote_num;
}
}
tot_condidate = sort(user, tot, user_codidate);
if (sum != 0)//ûκһ˵Ʊ²ʾƱ
{
for (i=0; i<tot_condidate; i++)
{
if (user_codidate[i].user_type == 0)
{
printf("| %s\t%d\t%d\t%.2f%% |\n", user_codidate[i].name, user_codidate[i].vote_num, i + 1, user_codidate[i].vote_num / sum * 100);
}
}
printf(" ----------------------------------------------------- \n");
}
else
{
for (i=0; i<tot_condidate; i++)
{
if (user_codidate[i].user_type == 0)
{
printf("| %s\t%d\t%d |\n", user_codidate[i].name, user_codidate[i].vote_num, i + 1);
}
}
printf(" ----------------------------------------------------- \n");
}
}
else
{
printf("| ѡ\tƱ |\n");
tot_condidate = sort(user, tot, user_codidate);
for (i=0; i<tot_condidate; i++)
{
if (user_codidate[i].user_type == 0)
{
printf("| %s\t%d |\n", user_codidate[i].name, user_codidate[i].vote_num);
}
}
printf(" ----------------------------------------------------- \n");
}
}
/*
βΣ
ֵ
ܣûעᣬעϢuserṹ
*/
void regist()
{
int i;
int flag = 1;//ûǷռ
for (i=0; i<tot; i++)
{
if (strcmp(user[i].name, name) == 0)
{
flag = 0;
system("cls");
error_regist();
break;
}
}
if (flag == 1 && choice_main == 2)
{
strcpy(user[tot].name, name);
strcpy(user[tot].phone, phone);
strcpy(user[tot].passwd, passwd);
user[tot].vote_num = 0;
user[tot].user_type = 0;//עʱעѡORͨû
tot++;
}
if (flag == 1 && choice_main == 3)
{
strcpy(user[tot].name, name);
strcpy(user[tot].phone, phone);
strcpy(user[tot].passwd, passwd);
user[tot].vote_num = 0;
user[tot].user_type = 1;
tot++;
}
}
/*
βΣ
ֵ
ܣʵͨûܣʾIJѡϢ
*/
void search()
{
int i;
int flag = 0;//Ƿѡ
printf(" ѡߣ");
scanf("%s", search_name);
printf("\n");
for (i=0; i<tot; i++)
{
if ((strcmp(user[i].name, search_name) == 0) && user[i].user_type == 0)
{
flag = 1;
printf(" ----------------------------------------------------- \n");
printf("| ѡ\tƱ |\n");
printf("| |\n");
printf("| %s\t%d |\n", user[i].name, user[i].vote_num);
printf("| |\n");
printf(" ----------------------------------------------------- \n");
}
}
if (flag == 0)
{
printf(" δҵòѡߣ\n");
}
}
/*
βΣ
ֵ
ܣͨûͶƱ
*/
void vote()
{
int i, j;
int flag = 0;//DZͶƱIJѡǷ
printf(" ѡͶƱѡߣ");
scanf("%s", search_name);
printf("\n");
for (i=0; i<tot; i++)
{
if ((strcmp(user[i].name, search_name) == 0) && user[i].user_type == 0)
{
flag = 1;
}
}
if (flag == 1)
{
for (i=0; i<tot; i++)
{
if ((strcmp(user[i].name, name) == 0) && user[i].user_type == 1 && user[i].vote_num < N)//ֻûͶƱСͶƱͶƱ
{
for (j=0; j<tot; j++)
{
if ((strcmp(user[j].name, search_name) == 0) && user[j].user_type == 0)
{
user[j].vote_num++;//ѡƱ+1
user[i].vote_num++;//ͨûͶƱ+1
printf(" ͶƱɣл֧֣\n");
printf("\n");
}
}
}
if ((strcmp(user[i].name, name) == 0) && user[i].user_type == 1 && user[i].vote_num >= N)
{
printf(" ͶƱѴﵽޣ\n");
}
}
}
else
{
printf(" δҵòѡߣ\n");
}
}
/*
βΣuserΪڴд洢ûݵĽṹ
ֵ
ܣļмûݣʽ
*/
void load(struct user user[])
{
FILE *fp;
if ((fp=fopen("user.db", "ab+")) == NULL )
{
puts("Fail to open file!\n");
exit(0);
}
tot = 0;
while (!feof(fp))//ͨfeof()жǷȡļβ
{
fread(user + tot, sizeof(struct user), 1, fp);
tot++;
}
tot--;//δ֪ԭ tot ܻ 1 ڴ˴Ϊ -1
fclose(fp);
}
/*
βΣuserΪڴд洢ûݵĽṹ飬totΪ鳤Ҳû
ֵ
ܣڴеûݵļУʽ
*/
void dump(struct user user[], int tot)
{
FILE *fp;
if ((fp=fopen("user.db", "wb+")) == NULL )
{
puts("Fail to open file!\n");
exit(0);
}
fwrite(user, sizeof(struct user), tot, fp);
fclose(fp);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* free.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ahouel <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/17 15:52:37 by ahouel #+# #+# */
/* Updated: 2019/12/02 18:34:13 by ahouel ### ########.fr */
/* */
/* ************************************************************************** */
#include "malloc.h"
/*
** Free the block given and fusion it with the next / prev one
** in the linked list if they are also free
*/
static t_block *defrag(t_block *b1, t_block *b2)
{
t_block *b3;
b3 = b2->next;
b1->size += sizeof(t_block) + b2->size;
b1->next = b3;
if (b3)
b3->prev = b1;
return (b1);
}
/*
** Check if all blocks in an area are free
*/
static char is_free(t_area *area)
{
t_block *block;
block = area->blocks;
while (block)
{
if (!block->free)
return (0);
block = block->next;
}
return (1);
}
/*
** Delete an area from g_malloc_pages lists
*/
static void delete_area(t_area *area)
{
if (!area->prev && !area->next)
return ;
if (g_malloc_pages.tiny == area)
g_malloc_pages.tiny = area->next;
else if (g_malloc_pages.small == area)
g_malloc_pages.small = area->next;
else if (g_malloc_pages.large == area)
g_malloc_pages.large = area->next;
else if (area->prev)
area->prev->next = area->next;
if (area->next)
area->next->prev = area->prev;
if (munmap(area, area->size))
return ;
}
/*
** The free() function deallocates the memory allocation pointed
** to by ptr. If ptr is a NULL pointer, no operation is performed.
*/
void free(void *ptr)
{
t_area *area;
t_block *block;
if (!ptr)
return ;
pthread_mutex_lock(&g_mutex);
if (!(area = which_area(ptr)))
{
pthread_mutex_unlock(&g_mutex);
return ;
}
if (!(block = is_block_valid(&area->blocks, ptr)))
{
pthread_mutex_unlock(&g_mutex);
return ;
}
block->free = 1;
if (block->prev && block->prev->free)
block = defrag(block->prev, block);
if (block->free && block->next && block->next->free)
block = defrag(block, block->next);
if (is_free(area))
delete_area(area);
pthread_mutex_unlock(&g_mutex);
}
|
C
|
#include <ctype.h>
#include <errno.h>
#include <signal.h> // This is new!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define BUFFER_SIZE 80
// Because of space delimiters, the max number of arguments can be estimated.
#define ARG_NUM (BUFFER_SIZE + 1) / 2 + 1
// Size of the history ring buffer.
// I set a small number here so I can easily test it.
#define HIST_MAX 11
// Data struct of the history ring buffer.
typedef struct record {
char *log[HIST_MAX]; // Pointers to the buf. We put the buffer on the stack,
// so it's malloc free.
int index; // Current index in the array.
int total_count; // Total number of the commands typed.
} record_t;
// In fact, history will only add (or overwrite) items. no remove, no deletion.
int add_log(record_t *r, char *cmd) {
if (r) {
int i = r->index % HIST_MAX;
memset(r->log[i], '\0', sizeof(char) * BUFFER_SIZE);
strcpy(r->log[i], cmd);
r->index++;
r->total_count++;
return 0;
} else {
// Return on null pointer.
return -1;
}
}
// Built-in function struct. This struct is used to represent a built-in
// command.
typedef struct function {
char *name; // name of the built-in command.
int (*p_func)(char **); // function pointer of the command.
} cmd_t;
// Create a signal handler
void sigint_handler(int sig) {
// Kill all the child processes.
kill(0, SIGINT);
// Ask yourself why 35? The length of the string.
// 1 represents stdout.
write(1, "Terminating through signal handler\n", 35);
exit(0);
}
// Parse the input string so execvp can understand it.
// input is the string to be parsed.
// delimiter is used to specify delimiter for strtok.
// result is the pointers for the result.
// buf is used to provide memory space for the result.
void parse(char *input, char *delimiter, char **result,
char buf[][BUFFER_SIZE]) {
char *token = strtok(input, delimiter);
int arg_count = 0;
// Each argument is a char array.
while (token != NULL) {
result[arg_count] = buf[arg_count];
strcpy(result[arg_count++], token);
token = strtok(NULL, delimiter);
}
// Mark the end of the arguments.
result[arg_count] = NULL;
}
// argv ends with NULL.
int cmd_help(char **argv) {
printf(
"Help of mini-shell bulitin commands:\n"
"0) help:\t print the help of the builtin commands.\n"
"1) exit:\t exit mini-shell by this command. You can also exit "
"mini-shell at anytime by Ctrl+c.\n"
"2) cd: \t change the current directory to the specified directory by "
"'cd dir'.\n"
"3) hist:\t hist [num] print the history of the commands the user "
"typed. It will print at most %d commands with a number denoting "
"the order it was typed. You can also specify the number of "
"commands to be printed by an optional argument [num].\n",
HIST_MAX - 1);
return 0;
}
// Used to store history commands.
static record_t history;
int cmd_history(char **argv) {
// Check invalid argument number.
if (argv[2] != NULL) {
printf("Error: hist takes at most 1 arguments.\n");
return -1;
}
// Record HIST_MAX history in ring buffer.
int size = HIST_MAX < history.total_count ? HIST_MAX : history.total_count;
// After hist cmd, the record size is at least 1.
if (size == 1) {
printf("No previous command.\n");
return 0;
}
// Check if argument 1 is an int within the correct range.
if (argv[1] != NULL) {
// Parse the number.
int num = atoi(argv[1]);
if (num <= 0 || num >= HIST_MAX) {
printf("Error: Invalid number of history commands. It should be in "
"[%d, %d]\n",
0, HIST_MAX);
return -1;
}
num++;
size = num < size ? num : size;
}
int i;
for (i = size; i > 1; i--) {
printf("No.%4d ", history.total_count - i);
printf("%s", history.log[(history.index - i + HIST_MAX) % HIST_MAX]);
}
return 0;
}
// Used to nullify an array of pointers by setting each pointer to NULL.
void nullify_pointer_array(char **pointers, int size) {
while (size-- > 0) {
*(pointers + size) = NULL;
}
}
// This function is used to call general builtin functions. A general builtin
// function has io and will be called in a child process like an external
// command. On the other hand, a special builtin command (cd, exit) will be
// "executed" in the parent process.
// This approach makes it possible to use a pipe to redirect help or hist
// command's output to the input of grep.
int builtin(char **cmd, cmd_t **cmdset) {
if (cmd && cmdset) {
int i = -1;
while (cmdset[++i] != NULL) {
if (strcmp(cmd[0], cmdset[i]->name) == 0) {
// Call function and return its return value.
return cmdset[i]->p_func(cmd);
}
}
}
return -1;
}
// Check for empty string. It used to prevent empty string in history.
int is_not_empty(char *s) {
while (*s) {
if (!isspace(*s)) {
return 1;
}
s++;
}
return 0;
}
int main() {
// Generate a process group. All the child processes belongs to this process
// group. They will be killed by kill(0, SIGINT).
int pgid = setpgid(0, 0);
if (pgid == -1) {
perror("Failed tp setpgid.");
exit(1);
}
// Initialize history record.
// Use a buffer to avoid malloc.
char hist_record_buffer[HIST_MAX][BUFFER_SIZE];
history.total_count = 0;
history.index = 0;
int i = 0;
for (i = 0; i < HIST_MAX; i++) {
history.log[i] = hist_record_buffer[i];
}
// Initial built in command.
cmd_t *cmd[3];
cmd_t builtin_help = {"help", cmd_help};
cmd_t builtin_hist = {"hist", cmd_history};
cmd[0] = &builtin_help;
cmd[1] = &builtin_hist;
cmd[2] = NULL;
// Buffer initialization.
char buffer[BUFFER_SIZE];
// Max length of a single command name is BUFFER_SIZE
// Max number of arguments must be smaller than BUFFER_SIZE, as it needs a
// space between command name and arguments. In fact, if each argument is
// only one character length, then it could have at most: 39 arguments + 39
// spaces + 1 command = 79 characters. So, it could have at most 39
// arguments + 1 command + 1 NULL = 41 char array in parse_result.
char parse_result_buffer[ARG_NUM][BUFFER_SIZE];
char *parse_result[ARG_NUM];
nullify_pointer_array(parse_result, ARG_NUM);
// Split one command into several commands if there is any.
char split_result_buffer[ARG_NUM][BUFFER_SIZE];
char *split_result[ARG_NUM];
nullify_pointer_array(split_result, ARG_NUM);
// Two pipes will be used alternatively if there are more than one pipes in
// one command. fd_even_to_odd: pass STDOUT of cmd 2n to STDIN of cmd 2n+1.
// fd_odd_to_even: pass STDOUT of cmd 2n+1 to STDIN of cmd 2n+2.
int fd_even_to_odd[2];
int fd_odd_to_even[2];
int cmd_index;
// Install our signal handler.
signal(SIGINT, sigint_handler);
printf("You can only terminate by pressing Ctrl+C\n");
while (1) {
printf("mini-shell>");
// Clean buffer.
memset(buffer, '\0', sizeof(char) * BUFFER_SIZE);
fgets(buffer, BUFFER_SIZE, stdin);
if (ferror(stdin)) {
perror("Input Error: ");
}
// Check if command is empty.
if (is_not_empty(buffer)) {
// Record non empty command string.
add_log(&history, buffer);
} else {
// Empty command, continue to next command.
continue;
}
// Write to history.
// add_log(&history, buffer_bk);
// Remove tail '\n'.
buffer[strcspn(buffer, "\n")] = 0;
// Split by "|", and parse each command one by one.
parse(buffer, "|", split_result, split_result_buffer);
// If there is more than one single command, we need a pipe.
if (split_result[1] != NULL) {
pipe(fd_even_to_odd);
}
cmd_index = 0;
// I have implemented a strategy that uses 2 pipes to execute command
// with multiple '|'s. So we can use the following command:
// mini-shell>ls | grep c | grep s | grep h | grep e | grep l
// mini-shell>help | grep a | grep num
while (split_result[cmd_index] != NULL) {
parse(split_result[cmd_index], " ", parse_result,
parse_result_buffer);
// In case empty input.
if (parse_result[0] == NULL) {
printf("Error: Empty command found!\n");
break;
}
// Some special builtin commands.
if (strcmp(parse_result[0], "exit") == 0) {
// CMD exit
// Check if there is any arguments.
if (parse_result[1] != NULL) {
printf("Error: exit doesn't take any argument.\n");
break;
} else {
// clean and exit;
printf("Leaving mini shell.\n");
return 0;
}
} else if (strcmp(parse_result[0], "cd") == 0) {
// CMD cd
if (parse_result[2] != NULL || parse_result[1] == NULL) {
printf("Error: cd must have exactly one argument.\n");
break;
} else {
// Call chdir in the parent process.
if (chdir(parse_result[1]) < 0) {
perror("Failed to change directory: ");
}
nullify_pointer_array(parse_result, ARG_NUM);
cmd_index++;
continue;
}
}
int status = 0;
// Parse single command in child process.
int pid = fork();
if (pid == 0) {
// Even cmd and has next cmd, then redirect stdout.
if (cmd_index % 2 == 0 && split_result[cmd_index + 1] != NULL) {
// Write to pipe fd_even_to_odd.
close(fd_even_to_odd[0]);
dup2(fd_even_to_odd[1], STDOUT_FILENO);
close(fd_even_to_odd[1]);
}
// Even cmd has previous cmd, then redirect stdin.
if (cmd_index % 2 == 0 && cmd_index > 0) {
// Read from odd_to_even.
close(fd_odd_to_even[1]);
dup2(fd_odd_to_even[0], STDIN_FILENO);
close(fd_odd_to_even[0]);
}
// Odd cmd always has previous cmd.
if (cmd_index % 2 == 1) {
// Read from fd_even_to_odd pipe.
close(fd_even_to_odd[1]);
dup2(fd_even_to_odd[0], STDIN_FILENO);
close(fd_even_to_odd[0]);
if (split_result[cmd_index + 1] != NULL) {
// Write to fd_odd_to_even pipe.
close(fd_odd_to_even[0]);
dup2(fd_odd_to_even[1], STDOUT_FILENO);
close(fd_odd_to_even[1]);
}
}
// Execution
if (builtin(parse_result, cmd) != 0) {
execvp(parse_result[0], parse_result);
// Command not found will set errno to 2.
if (errno == 2) {
// Print error message to stderr.
fprintf(
stderr,
"Command( %s ) not found--Did you mean something "
"else?\n",
parse_result[0]);
} else {
// If the error is not "Command not found", just print
// the error message from system.
perror("Error:");
}
exit(-1);
} else {
// End processes.
exit(0);
}
} else {
// Wait for the child.
wait(&status);
// After first child run. close write end of the pipe.
if (cmd_index % 2 == 0 && split_result[cmd_index + 1] != NULL) {
if (split_result[cmd_index + 2] != NULL) {
// After cmd 2, 4, 6 ...
// That is before cmd 3, 5, 7 ...
// Before cmd 0, build pipe 0-1,
// Before cmd 1, build pipe 1-2,
if (cmd_index > 0) {
close(fd_odd_to_even[0]);
}
pipe(fd_odd_to_even);
}
close(fd_even_to_odd[1]);
}
if (cmd_index % 2 == 1 && split_result[cmd_index + 1] != NULL) {
if (split_result[cmd_index + 2] != NULL) {
// After cmd 1, 3, 5 ...
// That is before cmd 2, 4, 6 ...
// Before cmd 0, build pipe 0-1,
// Before cmd 2, build pipe 2-3,
close(fd_even_to_odd[0]);
pipe(fd_even_to_odd);
}
close(fd_odd_to_even[1]);
}
// Close all the pipe ends in the last loop.
if (split_result[cmd_index + 1] == NULL) {
if (cmd_index > 0) {
// Write end has been closed before.
close(fd_even_to_odd[0]);
}
if (cmd_index > 1) {
close(fd_odd_to_even[0]);
}
}
// free parser results.
nullify_pointer_array(parse_result, ARG_NUM);
}
cmd_index++;
}
// free split commands.
nullify_pointer_array(split_result, ARG_NUM);
}
}
|
C
|
#include <stdio.h>
int main(void)
{
int arr[5] = {1,2,3,4,0};
int len = sizeof(arr) / sizeof(arr[0]);
int i = 0;
int index = 0; //插入到数组的头部的情况
//从倒数第二个元素开始向右移动
for (i = len - 2; i >= index; i --)
{
//后一个元素的内容等于前一个元素的内容
//第一次循环: 1,2,3,4,4 4向右移动
//第二次循环: 1,2,3,3,4 3向右移动
//第三次循环: 1,2,2,3,4 2向右移动
//第四次循环: 1,1,2,3,4 1向右移动
arr[i + 1] = arr[i];
}
//插入一个元素到第一个元素的位置
arr[index] = 100;
for (i = 0; i < len; i ++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
/* create a barrier */
pthread_barrier_t barrier;
/* normal thread */
void* robot_worker(void *arg)
{
for(;;)
{
char* msg = (char *)arg;
puts(msg);
pthread_barrier_wait(&barrier);
/* advancing the conveyor belt happens between these two barriers */
pthread_barrier_wait(&barrier);
}
return NULL;
}
/* manager */
void* robot_worker_manager(void* arg)
{
for(;;)
{
/* wait for all threads to print message */
pthread_barrier_wait(&barrier);
/* advance conveyor belt */
puts("Advancing conveyor belt");
usleep(750000);
puts("Next work item read.\n");
/* force threads to wait for the conveyor belt to advance */
pthread_barrier_wait(&barrier);
}
return NULL;
}
int main(void)
{
char *wkrs[] = {
"cutting",
"welding",
"painting"
};
int nrobots = sizeof(wkrs) / sizeof(wkrs[0]);
pthread_t tids[nrobots];
pthread_t manager;
pthread_barrier_init(&barrier, NULL, nrobots+1);
//for(;;)
//{
/* create manager */
pthread_create(&manager, NULL, robot_worker_manager,NULL);
for(int i = 0; i < nrobots; i++)
{
pthread_create(&tids[i],NULL,robot_worker,wkrs[i]);
}
for(int i = 0; i < nrobots; i++)
{
pthread_join(tids[i], NULL);
}
/*
puts("Advancing conveyor belt...");
usleep(750000);
puts("Next work item read.");
*/
//}
return 0;
}
|
C
|
#include <stdio.h>
#include "../memory.h"
#include "../processor.h"
#include "../alu.h"
#include "jump_00_modeless.h"
#include "jump_00_default.h"
/* Jump based on aaa for an assorted group of mostly 'modeless' instructions */
static void jmpMod(unsigned char aaa, unsigned char bbb, unsigned char cc)
{
jump_00_modeless[aaa](aaa, bbb, cc);
}
/* Branch instructions */
static void branch(unsigned char aaa, unsigned char bbb, unsigned char cc)
{
// xx gives the status bit to test:
// 00=SIGN,01=OVFL,10=CARY,11=ZERO
// y gives the value to compare to
unsigned char xx = aaa >> 1;
unsigned char y = aaa & 0b1;
// all branch instructions have two's complement relative addressing.
char relative = mem_get(pc++);
char * mnemonic; // TODO implement elsewhere for debugging purposes
bool test = false;
if (xx == 0b00) { test = (sr & SIGN) != 0; mnemonic = y == 1 ? "BMI" : "BPL"; };
if (xx == 0b01) { test = (sr & OVFL) != 0; mnemonic = y == 1 ? "BVS" : "BVC"; };
if (xx == 0b10) { test = (sr & CARY) != 0; mnemonic = y == 1 ? "BCS" : "BCC"; };
if (xx == 0b11) { test = (sr & ZERO) != 0; mnemonic = y == 1 ? "BEQ" : "BNE"; };
if ((test && y == 1) || (!test && y == 0))
{
printf("sr: %d\n", sr);
printf("Branching relative: %d\n", relative);
pc += relative;
}
}
/* Set or clear status register bits */
static void setClr(unsigned char aaa, unsigned char bbb, unsigned char cc)
{
if (aaa == 0b100) { // exception: TYA
a = alu_check(y);
return;
}
// xx gives the status bit to clear or set:
// 00=CARY,01=INTR,10=SIGN,11=DECI
// y indicates set or clear
unsigned short xx = aaa >> 1;
unsigned short y = aaa & 0b1;
short which = 0;
char * mnemonic; // TODO implement elsewhere for debugging purposes
if (xx == 0b00) { which = CARY; mnemonic = y == 1 ? "SEC" : "CLC"; };
if (xx == 0b01) { which = INTR; mnemonic = y == 1 ? "SEI" : "CLI"; };
if (xx == 0b10) { which = OVFL; mnemonic = y == 1 ? "SEV" : "CLV"; };
if (xx == 0b11) { which = DECI; mnemonic = y == 1 ? "SED" : "CLD"; };
if (y == 1) sr |= which;
else sr &= (0xFF - which);
}
/* This is the default action: jump further, based on aaa */
void jmpAaa(unsigned char aaa, unsigned char bbb, unsigned char cc)
{
jump_00_default[aaa](aaa, bbb, cc);
}
void (* jump_00[])(unsigned char aaa, unsigned char bbb, unsigned char cc) =
{
jmpAaa, jmpAaa, jmpMod, jmpAaa,
branch, jmpAaa, setClr, jmpAaa
};
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct lista{
int valor;
struct lista *proximo;
};
//Funo que retorna endereo de um ponteiro que aponta para uma struct lista.
struct lista *procurarValor(struct lista *pLista, int valor){
//recebe membro da lista concatenada pLista.
while(pLista != 0){
//se o ponteiro pLista apontando para valor for igual ao valor do usuario, retornamos o endereo do ponteiro.
if(pLista-> valor == valor){
return (pLista);
}
// se no, avanamos para o proximo membro da lsita concatenada.
else{
pLista = pLista -> proximo;
}
}
// caso no encontre valor igual retornamos nulo.
return 0;
}
int main (){
struct lista *procurarValor(struct lista *pLista, int valor);
struct lista m1, m2, m3;
struct lista *resultado, *gancho = &m1;
int valor;
m1.valor= 5;
m1.proximo = &m2;
m2.valor = 10;
m2.proximo = &m3;
m3.valor = 15;
m3.proximo = 0;
printf("Digite o valor da pesquisa:\n ");
scanf("%i", &valor);
resultado = procurarValor(gancho, valor);
if(resultado == 0){
printf("Valor nao encontrado!\n");
}
else{
printf("valor %i encontrado\n", resultado->valor);
}
getchar();
return 0;}
|
C
|
#include<stdio.h>
int main()
{
int n;
scanf("%d", &n);
getchar();
char a[100][100];
for(int i=0;i<n;++i)
{
for(int j=0;j<n;++j)
{
scanf("%c", &a[i][j]);
}
getchar();
}
int ocounter=0;
for(int i=1;i<n-1;++i)
{
ocounter=0;
for(int j=1;j<n-1;++j)
{
if(a[i-1][j]=='o')
ocounter++;
if (a[i][j-1]=='o')
ocounter++;
if (a[i+1][j]=='o')
ocounter++;
if (a[i][j+1]=='o')
ocounter++;
}
if(ocounter%2!=0)
{
printf("NO");
return 0;
}
}
ocounter=0;
for(int i=1;i<n-1;i++)
{
ocounter=0;
if(a[0][i+1]=='o')
ocounter++;
if(a[1][i]=='o')
ocounter++;
if(a[0][i-1]=='o')
ocounter++;
if(ocounter%2!=0)
{
printf("NO");
return 0;
}
}
ocounter=0;
for(int i=1;i<n-1;i++)
{
ocounter=0;
if(a[i+1][0]=='o')
ocounter++;
if(a[i][1]=='o')
ocounter++;
if(a[i-1][0]=='o')
ocounter++;
if(ocounter%2!=0)
{
printf("NO");
return 0;
}
}
ocounter=0;
for(int i=1;i<n-1;i++)
{
ocounter=0;
if(a[n-1][i+1]=='o')
ocounter++;
if(a[n-2][i]=='o')
ocounter++;
if(a[n-1][i-1]=='o')
ocounter++;
if(ocounter%2!=0)
{
printf("NO");
return 0;
}
}
ocounter=0;
for(int i=1;i<n-1;i++)
{
ocounter=0;
if(a[i+1][n-1]=='o')
ocounter++;
if(a[i][n-2]=='o')
ocounter++;
if(a[i-1][n-1]=='o')
ocounter++;
if(ocounter%2!=0)
{
printf("NO");
return 0;
}
}
ocounter=0;
if(a[0][1]=='o')
ocounter++;
if(a[1][0]=='o')
ocounter++;
if(ocounter%2!=0)
{
printf("NO");
return 0;
}
ocounter=0;
if(a[0][n-2]=='o')
ocounter++;
if(a[1][n-1]=='o')
ocounter++;
if(ocounter%2!=0)
{
printf("NO");
return 0;
}
ocounter=0;
if(a[n-1][1]=='o')
ocounter++;
if(a[n-2][0]=='o')
ocounter++;
if(ocounter%2!=0)
{
printf("NO");
return 0;
}
ocounter=0;
if(a[n-1][n-2]=='o')
ocounter++;
if(a[n-2][n-1]=='o')
ocounter++;
if(ocounter%2!=0)
{
printf("NO");
return 0;
}
printf("YES");
return 0;
}
|
C
|
/*
* Pseudo Character Driver.
* Works on memory area.
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/kdev_t.h> /* MAJOR(), MINOR() macros*/
#include <linux/cdev.h> /* struct cdev */
#include <linux/export.h> /* THIS_MODULE */
#include <linux/device.h> /* class_create(), device_create() */
#include <linux/uaccess.h> /* copy_from_user() */
#undef pr_fmt
#define pr_fmt(fmt) "%s : " fmt, __func__
#define NUM_DEVICES 1
#define BUFF_SIZE 500
/* Driver Buffer */
char drv_buff[BUFF_SIZE];
/* device functions */
loff_t pcd_llseek (struct file *filp, loff_t offset, int whence) {
pr_info("llseek method called\n");
return 0;
}
ssize_t pcd_read (struct file * filp, char __user * buff, size_t count, loff_t *offset) {
pr_info("read method called, size = %zd, offset = %lld\n", count, *offset);
if(count + *offset > BUFF_SIZE) {
count = BUFF_SIZE - *offset;
}
if(copy_to_user(buff, &drv_buff[*offset], count)) {
pr_err("error in copy to user\n");
return -EFAULT;
}
/* Update the offset */
*offset += count;
pr_info("read method copied = %zd bytes, new offset = %lld\n", count, *offset);
return count;
}
ssize_t pcd_write (struct file *filp, const char __user * buff, size_t count, loff_t *offset){
pr_info("write method called, size = %zd, offset = %lld\n", count, *offset);
if(count + *offset > BUFF_SIZE) {
count = BUFF_SIZE - *offset;
}
if(!count) {
pr_err("No space left on device!\n");
return -ENOMEM;
}
if(copy_from_user(&drv_buff[*offset], buff, count)) {
return -EFAULT;
}
/* update the offset */
*offset += count;
pr_info("successfully written %zd bytes, new offset = %lld\n", count, *offset);
return count;
/*
*return 0;
* BAD IDEA! userspace progams(echo) would keep retrying
*/
}
int pcd_open (struct inode *inode, struct file *filp) {
pr_info("open method called\n");
return 0;
}
int pcd_release (struct inode *inode, struct file *filp) {
pr_info("release method called\n");
return 0;
}
dev_t device_number;
struct cdev pcd_cdev;
struct class *pcd_class;
struct device *pcd_device;
struct file_operations pcd_fops = {
.owner = THIS_MODULE,
.open = pcd_open,
.read = pcd_read,
.write = pcd_write,
.llseek = pcd_llseek,
.release = pcd_release
};
static int __init pcd_init(void) {
int ret;
/* 1. allocatate device number */
ret = alloc_chrdev_region(&device_number, 0, NUM_DEVICES, "pcd");
if(ret < 0) {
pr_err("Error allocating device number\n");
goto out;
}
/* initialize and add cdev structure */
cdev_init(&pcd_cdev, &pcd_fops);
/* add char device to the system */
ret = cdev_add(&pcd_cdev, device_number, NUM_DEVICES);
if(ret < 0) {
pr_err("Error adding char device to system\n");
goto undo_device_num_reg;
}
/* create device class */
pcd_class = class_create(THIS_MODULE, "pcd");
if(IS_ERR(pcd_class)) {
pr_err("class_create() failed\n");
goto undo_cdev_add;
}
/* create a device and register it with sysfs */
pcd_device = device_create(pcd_class, NULL, device_number, NULL, "pcd_%d", 0);
if(IS_ERR(pcd_device)) {
pr_err("device_create() failed\n");
goto undo_class_create;
}
pr_info("Hello char module loaded successfully!\n");
pr_info("allocated device number <major>: <minor> = %u: %u\n", MAJOR(device_number), MINOR(device_number));
return 0;
undo_class_create:
device_destroy(pcd_class, device_number);
undo_cdev_add:
cdev_del(&pcd_cdev);
undo_device_num_reg:
unregister_chrdev_region(device_number, NUM_DEVICES);
out:
return ret;
}
static void __exit pcd_exit(void) {
device_destroy(pcd_class, device_number);
class_destroy(pcd_class);
cdev_del(&pcd_cdev);
unregister_chrdev_region(device_number, NUM_DEVICES);
pr_info("Hello char module unloaded. Bye!\n");
}
module_init(pcd_init);
module_exit(pcd_exit);
MODULE_AUTHOR("Suyash");
MODULE_DESCRIPTION("Simple character driver with dummy functions");
MODULE_LICENSE("GPL");
|
C
|
/**
* Name: Sal Penza
* Lab: Lab 3
* Date: 2/19/2020
**/
#include "person.h"
LIST *head = NULL, *tail = NULL;
void inputPersonalData(PERSON *person)
{
// TODO implement the function
// or check out part 9 of the c tutorial ;)
scanf("%s", person->name);
scanf("%d", &person->age);
scanf("%f", &person->height);
scanf("%d/%d/%d", &person->bday.month, &person->bday.day, &person->bday.year);
}
void addPersonalDataToDatabase(PERSON *person)
{
add(&head, &tail, person);
}
void displayDatabase()
{
LIST *temp = head;
while(temp != NULL){
displayPerson((PERSON *)temp->data);
temp = temp->next;
}
}
void displayPerson(PERSON *person)
{
// TODO Implement the function
// hmmmm seems familiar....
printf("%s : age %d, height %.1f, birthday %d/%d/%d\n", person->name, person->age, person->height, person->bday.month, person->bday.day, person->bday.year);
//Zach : age 22, height 5.8, birthday 2/20/1989
}
PERSON *findPersonInDatabase(char *name)
{
LIST *currNode = head;
while(currNode != NULL) {
PERSON *person = (PERSON *) currNode->data;
if(strcmp(person->name, name) == 0){
return person;
}
currNode = currNode->next;
}
return NULL; // if not found
}
void removePersonFromDatabase(char *name)
{
delete(&head, &tail, findPersonInDatabase(name));
}
void clearDatabase()
{
clearRecursively(&head, &tail);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* run_bin.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ssnowbir <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/05 18:28:09 by iserzhan #+# #+# */
/* Updated: 2020/12/06 19:52:32 by ssnowbir ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void free_memo(char **envp, char *path)
{
int i;
i = 0;
while (envp[i])
free(envp[i++]);
if (envp)
free(envp);
if (path)
free(path);
}
char **convert_to_array(t_envp *env)
{
int i;
char **envp1;
t_envp *temp;
temp = env;
i = 0;
while (temp != NULL)
{
temp = temp->next;
i++;
}
if (!(envp1 = (char**)malloc(sizeof(char *) * i + 1)))
return (NULL);
envp1[i] = NULL;
i = 0;
while (env->next != NULL)
{
envp1[i] = ft_strdup(env->value);
env = env->next;
i++;
}
envp1[i++] = ft_strdup(env->value);
return (envp1);
}
static void child(t_info *info, char *path, char **envp)
{
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
if ((execve(path, info->tok->args, envp)) == -1)
print_error(info->tok->args[0], info);
}
static void parent(t_info *info, pid_t pid)
{
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
waitpid(pid, &info->info2->ret, WUNTRACED);
check_signal(info);
}
int run(char **args, t_envp *env, t_info *info)
{
pid_t pid;
char **envp;
char *path;
info->info2->flag_nsf = 0;
if (!(info->tok->red) && (info->flag_pipe == 0))
dup2(info->info2->temp_fd[1], 1);
envp = convert_to_array(env);
if (!(path = find_path(args, env, &info->info2->flag_nsf, envp)))
{
if (info->info2->flag_nsf == 0)
return (print_error_cmd(args[0], info, envp, path));
else
return (print_error_nsf_path(args[0], info, envp, path));
}
else
pid = fork();
if (pid == 0)
child(info, path, envp);
else if (pid > 0)
parent(info, pid);
else
ft_putendl_fd("Failed to fork", 1);
free_memo(envp, path);
return (1);
}
|
C
|
#include "threadpool.h"
#ifndef REF
#define REF(x) &(x)
#endif
void *threadpool_worker(void *tp)
{
//Get the thread pool pointer
threadpool_t *threadpool = (threadpool_t*) tp;
//The task to be executed
task_t *task;
for( ; ; ) {
//Aquire lock
pthread_mutex_lock(REF(threadpool->mutex));
//Wait for an available task
while(!threadpool->stop && !(task = tasklist_pop(threadpool->tasks)))
pthread_cond_wait(REF(threadpool->new_work), REF(threadpool->mutex));
//If the thread got a signal to stop
if(threadpool->stop) {
pthread_mutex_unlock(REF(threadpool->mutex));
break;
}
//Add task to the executing list and unlock the mutex
tasklist_insert(threadpool->executing, task);
pthread_mutex_unlock(REF(threadpool->mutex));
//Execute the task
task_exec(task);
//Aquire lock
pthread_mutex_lock(REF(threadpool->mutex));
//Remove from executing list and free task
tasklist_remove(threadpool->executing, task->ID);
task_free(task);
//Notify that a task was done
pthread_cond_broadcast(REF(threadpool->task_done));
//Unlock
pthread_mutex_unlock(REF(threadpool->mutex));
}
pthread_exit(NULL);
return NULL; //Stop bugging me eclipse
}
threadpool_t *threadpool_create(int n_thread)
{
//Allocate memory for the thread pool struct
threadpool_t *threadpool = (threadpool_t*) malloc(sizeof(threadpool_t));
if(!threadpool) {
fprintf(stderr, "Allocation failed in threadpool_create().\n");
return NULL;
}
//Initialize parameters
threadpool->threads = (pthread_t*) malloc(sizeof(pthread_t) * n_thread);
threadpool->n_threads = n_thread;
pthread_mutex_init(REF(threadpool->mutex), NULL);
threadpool->stop = 0;
threadpool->tasks = tasklist_create();
threadpool->executing = tasklist_create();
pthread_cond_init(REF(threadpool->new_work), NULL);
pthread_cond_init(REF(threadpool->task_done), NULL);
//Start threads
int i;
int error_code;
for(i = 0; i < n_thread; i++)
if((error_code = pthread_create(REF(threadpool->threads[i]), NULL, threadpool_worker, (void*) threadpool)) != 0) {
fprintf(stderr, "Error starting worker thread(error code %d).\n", error_code);
exit(-1);
}
return threadpool;
}
taskID threadpool_addTask(threadpool_t *threadpool, task_t *task)
{
//Acquire lock
pthread_mutex_lock(REF(threadpool->mutex));
//The return value
taskID ID = 0;
//Add to tasks
if(tasklist_insert(threadpool->tasks, task)) {
//If added notify a worker thread
pthread_cond_signal(REF(threadpool->new_work));
ID = task->ID;
}
//Unlock and return
pthread_mutex_unlock(REF(threadpool->mutex));
return ID;
}
taskID threadpool_add(threadpool_t *threadpool, work_function work, argument_t argument, priority_t priority)
{
//Create task
task_t *task = task_create(work, argument, priority);
//Add to threadpool
return threadpool_addTask(threadpool, task);
}
void threadpool_wait(threadpool_t *threadpool)
{
//Acquire lock
pthread_mutex_lock(REF(threadpool->mutex));
//Wait until there are no more tasks available or executing
while(threadpool->tasks->n_tasks || threadpool->executing->n_tasks)
pthread_cond_wait(REF(threadpool->task_done), REF(threadpool->mutex));
//Unlock
pthread_mutex_unlock(REF(threadpool->mutex));
}
void threadpool_waitTask(threadpool_t *threadpool, taskID ID)
{
//Acquire lock
pthread_mutex_lock(REF(threadpool->mutex));
//Wait
while(tasklist_get(threadpool->executing, ID) || tasklist_get(threadpool->tasks, ID)) {
pthread_cond_wait(REF(threadpool->task_done), REF(threadpool->mutex));
}
//Unlock
pthread_mutex_unlock(REF(threadpool->mutex));
}
int threadpool_isDone(threadpool_t *threadpool, taskID ID)
{
//Acquire lock
pthread_mutex_lock(REF(threadpool->mutex));
//Check
int isDone = 1;
if(tasklist_get(threadpool->executing, ID) || tasklist_get(threadpool->tasks, ID))
isDone = 0;
//Unlock
pthread_mutex_unlock(REF(threadpool->mutex));
return isDone;
}
void threadpool_free(threadpool_t *threadpool)
{
//Wait for tasks to be executed
threadpool_wait(threadpool);
//Signal threads to stop
pthread_mutex_lock(REF(threadpool->mutex));
threadpool->stop = 1;
pthread_cond_broadcast(REF(threadpool->new_work));
pthread_mutex_unlock(REF(threadpool->mutex));
//Join threads
int i;
for(i = 0; i < threadpool->n_threads; i++)
pthread_join(threadpool->threads[i], NULL);
//Free the memory
free(threadpool->threads);
pthread_mutex_destroy(REF(threadpool->mutex));
tasklist_free(threadpool->tasks);
tasklist_free(threadpool->executing);
pthread_cond_destroy(REF(threadpool->new_work));
pthread_cond_destroy(REF(threadpool->task_done));
free(threadpool);
}
void *threadpool_background(void *tp)
{
//Get pointer to the thread pool
threadpool_t *threadpool = (threadpool_t*) tp;
//Free memory when done
threadpool_free(threadpool);
pthread_exit(NULL);
return NULL; //Pls eclipse
}
void threadpool_freeLater(threadpool_t *threadpool)
{
//Start thread
pthread_t background;
if(pthread_create(REF(background), NULL, threadpool_background, (void*) threadpool)) {
fprintf(stderr, "Error starting background thread.\n");
exit(-1);
}
//Detach thread
pthread_detach(background);
}
|
C
|
#include <stdio.h>
#include <malloc.h>
int main()
{
int s;
int i = 0, j = 1;
int *a;
printf("enter array's size: ");
scanf_s("%i", &s);
a = (int*)malloc(s * sizeof(int));
while (i<s)
{
a[i] = j;
j += 2;
i++;
}
printf("array A { ");
for (i = 0; i < s; i++)
{
printf("%i ", a[i]);
}
printf("}\n");
printf("modified array A { ");
for (i = 0; i < s; i++)
{
printf("%i ", a[i]);
printf("%i ", a[s-1-i]);
}
printf("} ");
free(a);
return 0;
}
|
C
|
#ifndef MAP_H
#define MAP_H
#include "../color/color.h"
#include "../point/point.h"
#include "../boolean/boolean.h"
#include "../building/building.h"
#include "../unit/unit.h"
/* Ukuran minimum dan maksimum baris dan kolom */
#define MapBrsMin 1
#define MapBrsMax 15
#define MapKolMin 1
#define MapKolMax 45
typedef struct {
char Building;
Color ColorBuilding;
char Unit;
Color ColorUnit;
} Sel;
typedef int IdxMap; /* indeks baris, kolom */
typedef struct {
Sel Mem[MapBrsMax+1][MapKolMax+1];
int NBrsEff; /* banyaknya/ukuran baris yg terdefinisi */
int NKolEff; /* banyaknya/ukuran kolom yg terdefinisi */
} Map;
/**
* Definisi Map kosong :
* semua Building dan Unit adalah karakter spasi
* ColorBuilding dan ColorUnit bernilai sembarang 1-6
* Indeks matriks yang digunakan: [BrsMin..BrsMax][KolMin..KolMax]
* Memori matriks yang dipakai selalu di "ujung kiri atas"
*/
/* *** Konstruktor Membentuk Map *** */
void MakeMap(int NB, int NK, Map* M);
/**
* Membentuk MAp "kosong" yang siap diisi berukuran NB x NK di "ujung kiri" memori
* I.S. M sembarang, NB dan NK valid
* F.S. Map M sesuai definisi kosong di atas terbentuk
*/
/* *** Selektor *** */
#define NBrsEffMap(M) (M).NBrsEff
#define NKolEffMap(M) (M).NKolEff
#define Building(M,i,j) (M).Mem[(i)][(j)].Building
#define ColorBuilding(M,i,j) (M).Mem[(i)][(j)].ColorBuilding
#define Unit(M,i,j) (M).Mem[(i)][(j)].Unit
#define ColorUnit(M,i,j) (M).Mem[(i)][(j)].ColorUnit
/* *** Selektor "Dunia Map" *** */
boolean IsIdxValid(IdxMap i, IdxMap j);
/**
* Mengembalikan true jika i, j adalah indeks yang valid untuk Map apapun
*/
boolean IsMapSizeValid(int Brs, int Kol);
/**
* Mengembalikan true jika i, j adalah indeks yang valid untuk Map apapun
*/
/* *** Selektor: Untuk sebuah Map M yang terdefinisi: *** */
IdxMap GetMapFirstIdxBrs(Map M);
/* Mengembalikan indeks baris terkecil M */
IdxMap GetMapFirstIdxKol(Map M);
/* Mengembalikan indeks kolom terkecil M */
IdxMap GetMapLastIdxBrs(Map M);
/* Mengembalikan indeks baris terbesar M */
IdxMap GetMapLastIdxKol(Map M);
/* Mengembalikan indeks kolom terbesar M */
boolean IsIdxMapEff(Map M, IdxMap i, IdxMap j);
/* Mengembalikan true jika i, j adalah indeks efektif bagi M */
/* *** Kelompok Baca/Tulis *** */
void TulisMap(Map M, Point CurrentUnitLoc);
/**
* I.S. M terdefinisi
* F.S. M ditampilkan ke layar sesuai format di spesifikasi
* Unit yang sedang dipilih akan berwarna hijau
*/
/* *** Kelompok Operasi Map *** */
void MapPutUnit(Map* M, Unit U, Color Warna);
/**
* I.S. M, U, dan Warna terdefinisi
* F.S. Tertulis unit U di Map dengan warna Warna
*/
void MapPutBuilding(Map* M, Building B, Color Warna);
/**
* I.S. M, B, dan Warna terdefinisi
* F.S. Tertulis building B di Map dengan warna Warna
*/
boolean IsPlayerCastle(Map M, int x, int y, Color Warna);
/**
* Mengembalikan nilai kebenaran apakah building B merupakan milik player
*/
boolean IsLocEmpty(Map M, int X, int Y);
/**
* Mengembalikan nilai kebenaran apakah sel (X,Y) kosong
*/
void MCopy(Map M1, Map* M2);
/**
* I.S. M1 sembarang
* F.S. M2 sama seperti M1
*/
#endif
|
C
|
#include <func.h>
typedef struct{
pthread_mutex_t mutex;
long tickets;
}thData;
void* threadfunc1(void *p) {
thData *p1=(thData*)p;
while(1){
pthread_mutex_lock(&p1->mutex);
if(p1->tickets>0){
printf("I am windows1,I will sale tickets %ld\n",p1->tickets);
p1->tickets--;
printf("I am windows1,sale ok %ld\n",p1->tickets);
pthread_mutex_unlock(&p1->mutex);
}else{
pthread_mutex_unlock(&p1->mutex);
break;
}
}
}
void* threadfunc2(void *p) {
thData *p1=(thData*)p;
while(1){
pthread_mutex_lock(&p1->mutex);
if(p1->tickets>0){
printf("I am windows2,I will sale tickets %ld\n",p1->tickets);
p1->tickets--;
printf("I am windows2,sale ok %ld\n",p1->tickets);
pthread_mutex_unlock(&p1->mutex);
}else{
pthread_mutex_unlock(&p1->mutex);
break;
}
}
}
int main(int argc,char* argv[]){
thData threadinfo;
int ret;
ret=pthread_mutex_init(&threadinfo.mutex,NULL);
if(ret!=0){
printf("pthread_mutex-init failed ret=%d\n",ret);
return -1;
}
pthread_t pthid1,pthid2;
threadinfo.tickets=20;
pthread_create(&pthid1,NULL,threadfunc1,&threadinfo) ;
pthread_create(&pthid2,NULL,threadfunc2,&threadinfo) ;
pthread_join(pthid1,NULL);
pthread_join(pthid2,NULL);
return 0;
}
|
C
|
#include <iostream>
using namespace std;
int main() {
int age;
cout << "How old are you? ";
cin >> age;
cout << "Thank you. You are ";
cout << age * 365 * 24 * 60 * 60;
cout << " seconds old." << endl;
return 0;
}
|
C
|
//NMEC: ...
//NOME: ...
//
// Joaquim Madeira, AlgC, May 2020
// João Manuel Rodrigues, AlgC, May 2020
//
// Adapted from an old example (ca. 2003)
//
// Binary Search Tree storing pointers to items --- Simple Version
//
//// PROCURE ... E COMPLETE ////
#include "BSTree.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
struct _BSTreeNode {
void* item;
struct _BSTreeNode* left;
struct _BSTreeNode* right;
};
struct _BSTreeHeader {
unsigned int numNodes;
struct _BSTreeNode* root;
compFunc compare;
printFunc print;
};
BSTree* BSTreeCreate(compFunc compF, printFunc printF) {
BSTree* t = (BSTree*)malloc(sizeof(struct _BSTreeHeader));
assert(t != NULL);
t->numNodes = 0;
t->root = NULL;
t->compare = compF;
t->print = printF;
return t;
}
static void _treeDestroy(struct _BSTreeNode** pRoot) {
struct _BSTreeNode* root = *pRoot;
if (root == NULL) return;
_treeDestroy(&(root->left));
_treeDestroy(&(root->right));
free(root);
*pRoot = NULL;
}
// Q: What kind of tree traversal is this function doing?
// Breadth-first or Depth-first? A: depth
// Pre-order, In-order or Post-order? A: post-order
// Is this the best order here? Why? A: yes, cause we need pointer to both childs of the root before freeing it
void BSTreeDestroy(BSTree** pHeader) {
BSTree* header = *pHeader;
if (header == NULL) return;
_treeDestroy(&(header->root));
free(header);
*pHeader = NULL;
}
// FUNÇÕES DE CONSULTA
int BSTreeIsEmpty(const BSTree* header) {
assert(header != NULL);
return header->root == NULL;
}
unsigned int BSTreeGetNumberOfNodes(const BSTree* header) {
assert(header != NULL);
return header->numNodes;
}
// Determina a altura da (sub)árvore que nasce no nó root.
// (Função interna, que é usada por BSTreeGetHeight.)
static int _treeGetHeight(const struct _BSTreeNode* root) {
// Complete a função
if(root == NULL) return 0;
int h1 = 1 + _treeGetHeight(root->left);
int h2 = 1 + _treeGetHeight(root->right);
return h1 > h2 ? h1 : h2;
}
// Devolve a altura da árvore.
// Segundo a convenção usada, uma árvore vazia tem altura=-1
// e uma árvore de um nó tem altura=0.
int BSTreeGetHeight(const BSTree* header) {
assert(header != NULL);
if(header->root == NULL) return -1;
return _treeGetHeight(header->root) - 1;
}
// Acha e devolve o menor item da árvore.
// Requer que a árvore não esteja vazia!
void* BSTreeGetMin(const BSTree* header) {
assert(header != NULL);
assert(!BSTreeIsEmpty(header));
// Complete a função com uma solução ITERATIVA.
struct _BSTreeNode* aux = header->root;
for(aux = header->root; aux->left != NULL; aux = aux->left);
return aux->item;
}
struct _BSTreeNode* _treeGetMaxRec( struct _BSTreeNode* root){
if(root->right == NULL) return root;
return _treeGetMaxRec(root->right);
}
// Acha e devolve o maior item da (sub)árvore que nasce no nó root.
// (Função interna invocada em BSTreeGetMax.)
static void* _treeGetMax( struct _BSTreeNode* root) {
assert(root != NULL);
// Complete a função com uma solução RECURSIVA.
return _treeGetMaxRec(root)->item;
}
// Acha e devolve o maior item da árvore.
// Requer que a árvore não esteja vazia!
void* BSTreeGetMax(const BSTree* header) {
assert(header != NULL);
assert(!BSTreeIsEmpty(header));
return _treeGetMax(header->root); // chama a função interna recursiva
}
// Does the tree contain an element that compares==0 with this item?
int BSTreeContains(const BSTree* header, const void* item) {
assert(header != NULL);
struct _BSTreeNode* root = header->root;
while (root != NULL) {
if(header->compare(item, root->item) > 0)
root = root->right;
else if(header->compare(item, root->item) < 0)
root = root->left;
else
return 1;
}
return 0;
}
// Aplica a função function a cada item da árvore.
// (Função interna usada em BSTreeTraverseINOrder.)
static void
_treeTraverseINOrder(struct _BSTreeNode* root, void (*function)(void* p)) {
// Corrija a função para que os nós sejam visitados por ordem crescente.
if (root == NULL) return;
_treeTraverseINOrder(root->left, function);
function(root->item);
_treeTraverseINOrder(root->right, function);
}
// Aplica a função function a cada item da árvore.
void BSTreeTraverseINOrder(BSTree* header, void (*function)(void* p)) {
assert(header != NULL);
_treeTraverseINOrder(header->root, function);
}
// Operations with items
// Acrescenta um item à árvore, se for válido.
// Devolve 1 (sucesso) se conseguir acrescentar o item
// ou 0 (falha) se o item colide com algum que já esteja na árvore.
int BSTreeAdd(BSTree* header, void* item) {
assert(header != NULL);
struct _BSTreeNode* root = header->root;
int cmp = 0; // to store comparison results
struct _BSTreeNode* prev = NULL;
struct _BSTreeNode* current = root;
while (current != NULL) {
cmp = header->compare(item, current->item);
prev = current;
if (cmp < 0) {
current = current->left;
} else if (cmp > 0) {
current = current->right;
} else { // (cmp == 0)
return 0; // items that compare==0 are not allowed in this tree
}
}
struct _BSTreeNode* newNode = (struct _BSTreeNode*)malloc(sizeof(*newNode));
if (newNode == NULL) abort();
newNode->item = item;
newNode->left = newNode->right = NULL;
// Complete a função fazendo a ancoragem do novo nó no ramo adequado.
if(header->root == NULL) header-> root = newNode;
else if (cmp < 0)
prev->left = newNode;
else if (cmp > 0)
prev->right = newNode;
header->numNodes++;
return 1;
}
static void _deleteNextNode(struct _BSTreeNode** pRoot, void** pItem) {
if ((*pRoot)->left == NULL) {
// FOUND IT
struct _BSTreeNode* auxPointer = *pRoot;
*pItem = auxPointer->item;
*pRoot = auxPointer->right;
free(auxPointer);
} else {
_deleteNextNode(&((*pRoot)->left), pItem);
}
}
// This internal function removes the node pointed to by *pPointer.
// Note that pPointer is the address of a variable that points to the node
// to be removed. When it removes the node, it also sets that variable to NULL.
// That variable is either the root field of the _BSTreeHeader struct
// or the left or the right field of the parent _BSTreeNode struct.
// (Pointing to fields inside a struct is something you cannot do in Java.)
static void _removeNode(struct _BSTreeNode** pPointer) {
struct _BSTreeNode* nodePointer = *pPointer;
if ((nodePointer->left == NULL) && (nodePointer->right == NULL)) {
/* A LEAF node */
free(nodePointer); // FREE it and
*pPointer = NULL; // SET field in parent node (or header) to NULL
}
else if (nodePointer->left == NULL) {
/* It has only a RIGHT sub-tree */
*pPointer = nodePointer->right;
free(nodePointer);
}
else if (nodePointer->right == NULL) {
/* It has only a LEFT sub-tree */
*pPointer = nodePointer->left;
free(nodePointer);
}
else {
/* Node has TWO CHILDREN */
/* Replace its item with the item of the next node in-order */
/* And remove that node */
_deleteNextNode(&(nodePointer->right), &(nodePointer->item));
}
}
static int _treeRemoveItem(struct _BSTreeNode** pRoot, const void* item,
compFunc compare) {
struct _BSTreeNode* root = *pRoot;
if (root == NULL) {
return 0;
}
int cmp = compare(item, root->item);
if (cmp < 0) {
return _treeRemoveItem(&(root->left), item, compare);
} else if (cmp > 0) {
return _treeRemoveItem(&(root->right), item, compare);
} else { // (cmp == 0)
_removeNode(pRoot);
return 1;
}
}
int BSTreeRemove(BSTree* header, const void* item) {
assert(header != NULL);
if (_treeRemoveItem(&(header->root), item, header->compare) == 1) {
header->numNodes--;
return 1;
}
return 0;
}
// Funções internas necessárias para as funções
// BSTreeGetKthItem e BSTreeRemoveKthItem. Leia essas primeiro.
// Count and return the number of nodes of the (sub)tree at the given root.
static unsigned int _getNumNodes(const struct _BSTreeNode* root) {
if (root == NULL) {
return 0;
}
return 1 + _getNumNodes(root->left) + _getNumNodes(root->right);
}
static struct _BSTreeNode* _getPointerToKthNodeAux(struct _BSTreeNode* root, unsigned int* k) {
if(*k == 0) return root;
if(root == NULL) return NULL;
struct _BSTreeNode* n1 = _getPointerToKthNodeAux(root->left, k);
if(n1 != NULL) return n1;
(*k)--;
if(*k == 0) return root;
struct _BSTreeNode* n2 = _getPointerToKthNodeAux(root->right, k);
if(n2 != NULL) return n2;
return NULL;
}
// Procura e devolve o K-ésimo nó da árvore contado em-ordem.
static struct _BSTreeNode* _getPointerToKthNode(struct _BSTreeNode* root, unsigned int k) {
unsigned int aux = k + 1;
return _getPointerToKthNodeAux(root, &aux);
}
// Q: Admitindo que a árvore tem n nós e está equilibrada (balanced),
// qual é a complexidade computacional da função getPointerToKthNode?
// Justifique resumidamente como chegou ao resultado.
// R: O(n), cada node é visitado no maximo uma vez
//
//
// Explique como poderia evitar a chamada a _getNumNodes nesta função.
// Q: O que seria preciso mudar na estrutura de dados?
// R: ?
//
// Q: E que funções teriam de ser modificadas?
// R: ?
//
// Devolve o K-ésimo item da árvore.
// Índice K=0 corresponde ao menor item, K=1 corresponde ao segundo menor,
// K=2 ao terceiro menor, etc.
// Exige que 0 <= k < Number of Nodes.
void* BSTreeGetKthItem(const BSTree* header, unsigned int k) {
assert(header != NULL);
assert(0 <= k && k < header->numNodes);
struct _BSTreeNode* p = _getPointerToKthNode(header->root, k);
return p->item;
}
// Remove e devolve o K-ésimo item da árvore.
// Índice K=0 corresponde ao menor item, K=1 corresponde ao segundo menor,
// K=2 ao terceiro menor, etc.
// Exige que 0 <= k < Number of Nodes.
void* BSTreeRemoveKthItem(BSTree* header, int k) {
assert(header != NULL);
assert(0 <= k && k < header->numNodes);
struct _BSTreeNode* pNode = _getPointerToKthNode(header->root, k);
void* pItem = pNode->item;
BSTreeRemove(header, pItem);
return pItem;
}
// A função BSTreeRemoveKthItem percorre os nós duas vezes:
// uma quando faz _getPointerToKthNode e outra quando chama BSTreeRemove.
// Q: Será que se poderia fazer de modo mais eficiente?
// Sugira resumidamente uma solução e explique os seus aspetos essenciais.
// R: copiar a funçao getKthItem e em vez de retornar qndo k == 0 eliminar
//
// Em alternativa, pode implementar essa solução na função abaixo.
//void* BSTreeRemoveKthItem2(BSTree* header, int k) {
// // ...
//}
// Tree Visualization
static void _treeView(struct _BSTreeNode* root, int level,
const char* edge, printFunc print) {
if (root == NULL) {
printf("%*s%s\n", 4*level, edge, "#"); // # represents NULL pointer
} else {
_treeView(root->left, level+1, "/", print);
printf("%*s", 4*level, edge);
print(root->item);
printf("\n");
_treeView(root->right, level+1, "\\", print);
}
}
void BSTreeView(BSTree* header) {
_treeView(header->root, 0, ":", header->print); // : marks the root
printf("numNodes: %d\n", header->numNodes);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/*
* node structure.
*/
struct node {
struct node *next;
int data;
};
extern struct node *node_create(int data);
extern void node_free(struct node *n);
extern int list_lenght_get(struct node *list);
extern struct node *link_list_intersect(struct node *list1, struct node *list2);
extern void list_add_node_tail(struct node **list, struct node *n);
extern void list_add_data_head(struct node **list, int data);
extern void list_add_data_tail(struct node **list, int data);
extern void list_print(struct node *list);
extern bool list_data_look_up(struct node *list, int data);
extern void list_remove_node_by_data(struct node **list, int data);
extern void list_reverse(struct node **list);
|
C
|
/* Напишите программу, которая запрашивает у пользователя ввод количества
дней и затем преобразует это значение в количество недемь и дней. Например,
18 дней программа должна преобразовать в 2 недели и 4 дня. Отображайте результаты
в следующем формате:
18 дней составляют 2 недели и 4 дня.
Чтобы пользователь мог многократно вводить количество дней, используйте
цикл while. Цикл должен завершаться при вводе пользователем неположительного
значения, например, О или -20. */
#include <stdio.h>
int main (void)
{
int day, day1, day2;
printf("\r\nEnter the number of days\r\n");
while (day > -0)
{
scanf("%d", &day);
day1 = day / 7;
day2 = day % 7;
printf("\r\n%d days is %d week and %d day\r\n", day, day1, day2);
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_intlarg.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gabi42 <gabi42@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/06/03 15:44:32 by gabi42 #+# #+# */
/* Updated: 2020/06/08 16:53:25 by gabi42 ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/ft_printf.h"
#include "../libft/libft.h"
static char *largelse(t_int *list, char *lans, char *ans)
{
int n;
n = 0;
while (ans[n] != '\0')
{
lans[n] = ans[n];
n++;
}
while (n < (list->larg))
{
lans[n] = (list->zero == 1 ? '0' : ' ');
n++;
}
lans[n] = '\0';
return (lans);
}
static char *largif(t_int *list, char *lans, char *ans, int i)
{
int c;
int n;
c = 0;
while (c < (list->larg - i))
{
lans[c] = (list->zero == 1 ? '0' : ' ');
c++;
}
n = 0;
while (ans[n] != '\0')
{
lans[c + n] = ans[n];
n++;
}
lans[c + n] = '\0';
return (lans);
}
char *ft_intlarg(t_int *list, int i, char *ans)
{
char *lans;
int c;
int n;
c = 0;
c = (list->neg == 1 ? list->larg + 2 : list->larg + 1);
if (!(lans = (char*)malloc(sizeof(char) * c)))
return (0);
if (list->dash == 0)
lans = largif(list, lans, ans, i);
else if (list->dash == 1)
lans = largelse(list, lans, ans);
if (list->neg == 1 && list->zero == 1)
{
n = 1;
while (lans[n] != '-')
n++;
lans[n] = '0';
lans[0] = '-';
}
return (lans);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <string.h>
#include "ksmall.h"
static void swap(int *, int *);
static int comparator(const void *, const void *);
static size_t smallest_index(int *, size_t);
static size_t largest_index(int *, size_t);
static size_t partition(int *, size_t, size_t);
static size_t selection(int *, size_t, size_t);
static size_t pick_index(int *, size_t);
static void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
/* for qsort base cases */
static int comparator(const void *a, const void *b) {
return *(const int *)a - *(const int *)b;
}
static size_t smallest_index(int *A, size_t N) {
int smallest = INT_MAX;
size_t index;
for (size_t i = 0; i < N; i++) {
if (A[i] < smallest) {
smallest = A[i];
index = i;
}
}
return index;
}
static size_t largest_index(int *A, size_t N) {
int largest = INT_MIN;
size_t index;
for (size_t i = 0; i < N; i++) {
if (A[i] > largest) {
largest = A[i];
index = i;
}
}
return index;
}
/* partitions in place around A[k], returns the new
* index of the value originally located at A[k] */
static size_t partition(int *A, size_t N, size_t k) {
size_t s = 0;
int pivot = A[k];
swap(&A[0], &A[k]);
for (size_t i = 1; i < N; i++) {
if (A[i] <= pivot) {
swap(&A[i], &A[1 + (s++)]);
}
}
swap(&A[0], &A[s]);
return s;
}
/* selection function, implemented as discussed in lecture */
static size_t selection(int *A, size_t N, size_t k) {
size_t magic, pos;
assert(k >= 0 && k < N);
/* base cases */
if (k == 0) {
return smallest_index(A, N);
}
if (k == N - 1) {
return largest_index(A, N);
}
if (N <= 5) {
qsort(A, N, sizeof(int), comparator);
return k;
}
magic = pick_index(A, N);
pos = partition(A, N, magic);
if (pos == k) {
return pos;
} else if (pos > k) {
return selection(A, pos, k);
} else {
return selection(&A[pos + 1], N - pos - 1, k - pos - 1) + pos + 1;
}
}
/* implemented as discussed in lecture. Runs in linear time,
* since the qsort of size 5 is really constant time */
static size_t pick_index(int *A, size_t N) {
int *B, *mbuf;
size_t median_index;
B = malloc(sizeof(int) * N/5);
mbuf = malloc(sizeof(int) * 5);
assert(B);
assert(mbuf);
for (size_t i = 0; i < N/5; i++) {
for (size_t j = 0; j < 5; j++) {
mbuf[j] = A[5*i + j];
}
qsort(mbuf, 5, sizeof(int), comparator);
}
median_index = selection(B, N/5, N/10);
free(B);
free(mbuf);
return median_index;
}
int ksmall(int *A, size_t N, size_t k) {
assert(A && k >= 1 && k <= N);
return A[selection(A, N, k - 1)];
}
|
C
|
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
/*返回str2第一次出现在str1中的位置(下表索引),不存在返回-1*/
int indexOf(char *str1,char *str2)
{
char *p=str1;
int i=0;
p=strstr(str1,str2);
if(p==NULL){
return -1;
}
else{
while(str1!=p)
{
str1++;
i++;
}
}
return i;
}
int post(char *ip,int port,char *page,char *msg,char *recvline){
int sockfd,n;
struct sockaddr_in servaddr;
char content[4096];
char content_page[50];
sprintf(content_page,"POST /%s HTTP/1.1\r\n",page);
char content_host[50];
sprintf(content_host,"HOST: %s:%d\r\n",ip,port);
char content_type[] = "Content-Type: application/x-www-form-urlencoded\r\n";
char content_len[50];
sprintf(content_len,"Content-Length: %d\r\n\r\n",strlen(msg));
sprintf(content,"%s%s%s%s%s",content_page,content_host,content_type,content_len,msg);
printf("content---%s\n",content);
if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0){
printf("sockfd2---%d\n",sockfd);
printf("socket error\n");
return -1;
}
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
if(inet_pton(AF_INET,ip,&servaddr.sin_addr) <= 0){
printf("transfer ip err");
printf("ip---%s\n",ip);
return -1;
}
if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)) < 0){
printf("connect error\n");
return -1;
}
write(sockfd,content,strlen(content));
n = read(sockfd,recvline,1024);
printf("n---%d\n",n);
int ind = indexOf(recvline,"config");
printf("ind---%d\n",ind);
if(n < 0){
printf("read error\n");
return -1;
}
return 0;
}
int main()
{
char msg[] = "Ceshilianwang=ceshi";
char ip[] = "192.168.0.102";
int port = 8989;
char page[] = "sn/ceshilianwang";
char recvline[1024];
int cg = post(ip,port,page,msg,recvline);
if (cg==0){
printf("recvline---%s\n",recvline);
}
exit(0);
}
|
C
|
/* compile with gcc -o msHOT msGCHOT.c streecGCHOT.c rand1.c -lm */
/*same as ms.c but with mutliple crossover and geneconv hotspots addition */
/***** ms.c ************************************************
*
* Generates samples of gametes ( theta given or fixed number
* of segregating sites.)
* Usage is shown by typing ms without arguments.
usage: ms nsam howmany -t theta [options]
or
ms nsam howmany -s segsites [options]
nsam is the number of gametes per sample.
howmany is the number of samples to produce.
With -t the numbers of segregating sites will randomly vary
from one sample to the next.
with -s segsites, the number of segregating sites will be
segsites in each sample.
Other options: See msdoc.pdf or after downloading and compiling, type ms<CR>.
* Arguments of the options are explained here:
npop: Number of subpopulations which make up the total population
ni: the sample size from the i th subpopulation (all must be
specified.) The output will have the gametes in order such that
the first n1 gametes are from the first island, the next n2 are
from the second island, etc.
nsites: number of sites between which recombination can occur.
theta: 4No times the neutral mutation rate
rho: recombination rate between ends of segment times 4No
f: ratio of conversion rate to recombination rate. (Wiuf and Hein model.)
track_len: mean length of conversion track in units of sites. The
total number of sites is nsites, specified with the -r option.
mig_rate: migration rate: the fraction of each subpop made up of
migrants times 4No.
howmany: howmany samples to generate.
Note: In the above definition, No is the total diploid population if
npop is one, otherwise, No is the diploid population size of each
subpopulation.
A seed file called "seedms" will be created if it doesn't exist. The
seed(s) in this file will be modified by the program.
So subsequent runs
will produce new output. The initial contents of seedms will be
printed on the second line of the output.
Output consists of one line with the command line arguments and one
line with the seed(s).
The samples appear sequentially following that line.
Each sample begins with "//", then the number of segregating sites, the positions
of the segregating sites (on a scale of 0.0 - 1.0). On the following
lines are the sampled gametes, with mutants alleles represented as
ones and ancestral alleles as zeros.
To compile: cc -o ms ms.c streec.c rand1.c -lm
or: cc -o ms ms.c streec.c rand2.c -lm
(Of course, gcc would be used instead of cc on some machines. And -O3 or
some other optimization switches might be usefully employed with some
compilers.) ( rand1.c uses drand48(), whereas rand2.c uses rand() ).
*
* Modifications made to combine ms and mss on 25 Feb 2001
* Modifications to command line options to use switches 25 Feb 2001
* Modifications to add // before each sample 25 Feb 2001
Modifications to add gene conversion 5 Mar 2001
Added demographic options -d 13 Mar 2001
Changed ran1() to use rand(). Changed seed i/o to accomodate this change. 20 April.
Changed cleftr() to check for zero rand() .13 June 2001
Move seed stuff to subroutine seedit() 11 July 2001
Modified streec.c to handle zero length demographic intervals 9 Aug 2001
Corrected problem with negative growth rates (Thanks to D. Posada and C. Wiuf) 13 May 2002
Changed sample_stats.c to output thetah - pi rather than pi - thetah. March 8 2003.
Changed many command line options, allowing arbitrary migration matrix, and subpopulation
sizes. Also allows parameters to come from a file. Option to output trees. Option to
split and join subpopulations. March 8, 2003. (Old versions saved in msold.tar ).
!!! Fixed bug in -en option. Earlier versions may have produced garbage when -en ... used. 9 Dec 2003
Fixed bug which resulted in incorrect results for the case where
rho = 0.0 and gene conversion rate > 0.0. This case was not handled
correctly in early versions of the program. 5 Apr 2004. (Thanks to
Vincent Plagnol for pointing out this problem.)
Fixed bug in prtree(). Earlier versions may have produced garbage when the -T option was used.
1 Jul 2004.
Fixed bug in -e. options that caused problems with -f option 13 Aug 2004.
Fixed bug in -es option, which was a problem when used with -eG. (Thanks again to V. Plagnol.) 6 Nov. 2004
Added -F option: -F minfreq produces output with sites with minor allele freq < minfreq filtered out. 11 Nov. 2004.
Fixed bug in streec.c (isseg() ). Bug caused segmentation fault, crash on some machines. (Thanks
to Melissa Jane Todd-Hubisz for finding and reporting this bug.)
Added -seeds option 4 Nov 2006
Added "tbs" arguments feature 4 Nov 2006
***************************************************************************/
#define UN_EXTERN
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include "ms.h"
#include "eca_funcsHOTmulti.h"
#define SITESINC 10
unsigned maxsites = SITESINC ;
struct node{
int abv;
int ndes;
float time;
};
struct segl {
int beg;
struct node *ptree;
int next;
};
double *posit ;
double segfac ;
int count, ntbs ;
struct params pars ;
/*I have added some functions and an structure*/
struct rejection_statistics rs;
double nucdiv(int, int, int **);
double tajd(int, int, double) ;
double hfay(int, int, char **);
double thetah(int, int, char **);
double a1f(int);
double a2f(int);
double b1f(int);
double b2f(int);
double c1f(double, double);
double c2f(int, double, double, double);
double e1f(double, double);
double e2f(double, double, double);
main(argc,argv)
int argc;
char *argv[];
{
int i, k, howmany, segsites ;
char **list, **cmatrix(), **tbsparamstrs ;
FILE *pf, *fopen(),*sims ;
double probss ;
void seedit( const char * ) ;
void getpars( int argc, char *argv[], int *howmany ) ;
int gensam( char **list, double *probss ) ;
void argcheck( int arg, int argc, char ** ), commandlineseed( char ** ) ;
/*I will add this function*/
double ran1();
float heterozygosis(int **, int, int);
float variancemean (int **, int, int);
int numberofconfigurations(int **, int, int);
float Fst (int**, int, int, int, int *);
void mismatch (int **, int, int);
float sizehomoplasyloc (int **, int, int, char***);
float SH (int **, int , int , char ***);
float MASH (int **, int, int);
float SASH (int **, int , int , char ***);
float SHchanges(int **, int , int , char ***);
float SHdistance (int **, int , int , char ***);
int sitesSMM (int **, int , int );
int singleton (int **, int , int );
float msitesvar(int **, int , int);
float hetero(int **, int , int) ;
float configmicmean (int **, int , int);
float HomoBC(int **, int , int , char ***);
float varIS(char ***, int, int);
float heterozygosisIS(char ***, int, int);
int numberofconfigurationsIS(char ***, int, int);
int sitesIS (char ***, int , int );
int singletonIS (char ***, int , int );
float msitesvarIS(char ***, int , int);
float heteroIS(char ***, int , int) ;
float configmicvarIS (char ***, int , int);
float nucdivIS (char ***, int, int);
/*i will add this variable*/
int j,l,m,n,counter, arg, npop, simnum = 0;
int s, co1, co2, tbsnumber, cr;
char *ch;
tbsnumber = 0;
double pi, theta0, theta1, time, migr;
char *microdata,*ISdata;
rs.simulationnumber = 0;
rs.varianceflag= 0;
rs.heteroflag= 0;
rs.conflag= 0;
rs.piflag= 0;
rs.goodnessflag= 0;
rs.sitesflag = 0;
rs.singletonflag = 0;
rs.heterohapflag = 0;
rs.heteroISflag = 0; rs.conISflag = 0;rs.piISflag = 0;rs.goodnessISflag = 0,rs.varISflag = 0;
rs.sitesISflag = 0; rs.sitesvarIS = 0;rs.singletonISflag = 0; rs.heterohapISflag = 0; rs.configmicvarISflag = 0;
rs.readmicroflag = 0; rs.readISflag = 0; rs.acceptancesflag = 0;
//printf("Variance mean\tHeterozygosis mean\tNumber of configurations\tLinkage disequilibrium (delta)\tKurtosis mean\tVariance of variances\tTajimas D\n");
//printf("Skewness\tKurtosis\tMode\tMean\tMedian\tDifmeanmedian\tdifmeanmode\tdifmodemedian\tSegregating sites\n");
/*End of my additions*/
pars.cp.nsam = atoi( argv[1] );
//printf("numero de secuencias = %i\n",pars.cp.nsam);
rs.acceptances = 0;
arg= 3;
//printf ("numero de argumentos %i\n", argc);
while( arg < argc ){
//printf("Tu cadenita es %c", argv[arg][0]);
if( argv[arg][1]) {
switch ( argv[arg][1] ){
case 'z' :
arg++;
argcheck( arg, argc, argv);
pars.cp.r = 0;
pars.cp.nsites = atoi( argv[arg++]);
rs.micronumber = pars.cp.nsites;
pars.cp.nsites = pars.cp.nsites*2 + (pars.cp.nsites - 1)*2;
if( pars.cp.nsites <1 ){
fprintf(stderr,"with -z option must specify both rec_rate and nsites>1\n");
usage();
}
//printf("numero de microsatelites1 = %i\n",rs.micronumber);
/*End of my part of the code*/
break;
case 'I' :
arg++;
if( count == 0 ) {
argcheck( arg, argc, argv);
pars.cp.npop = atoi( argv[arg]);
pars.cp.config = (int *) realloc( pars.cp.config, (unsigned)( pars.cp.npop*sizeof( int)));
npop = pars.cp.npop ;
}
arg++;
//printf("Tu numero de poblaciones = %i\n",pars.cp.npop);
for( i=0; i< pars.cp.npop; i++) {
argcheck( arg, argc, argv);
pars.cp.config[i] = atoi( argv[arg++]);
// printf("El tamano de tu poblacion %i es %i\n", i, pars.cp.config[i]);
}
if( count == 0 ){
pars.cp.mig_mat = (double **)realloc(pars.cp.mig_mat, (unsigned)(pars.cp.npop*sizeof(double *) )) ;
for(i=0; i<pars.cp.npop; i++) pars.cp.mig_mat[i] = (double *)realloc(pars.cp.mig_mat[i],
(unsigned)( pars.cp.npop*sizeof(double)));
pars.cp.size = (double *) realloc( pars.cp.size, (unsigned)( pars.cp.npop*sizeof( double )));
pars.cp.alphag = (double *) realloc( pars.cp.alphag, (unsigned)( pars.cp.npop*sizeof( double )));
}
for( i=1; i< pars.cp.npop ; i++) {
(pars.cp.size)[i] = (pars.cp.size)[0] ;
(pars.cp.alphag)[i] = (pars.cp.alphag)[0] ;
}
if( (arg <argc) && ( argv[arg][0] != '-' ) ) {
argcheck( arg, argc, argv);
migr = atof( argv[arg++] );
}
else migr = 0.0 ;
for( i=0; i<pars.cp.npop; i++)
for( j=0; j<pars.cp.npop; j++) pars.cp.mig_mat[i][j] = migr/(pars.cp.npop-1) ;
for( i=0; i< pars.cp.npop; i++) pars.cp.mig_mat[i][i] = migr ;
break;
case 'a' :
arg++;
argcheck( arg, argc, argv);
rs.alpha = atof( argv[arg++]);
break;
case 'R' :
arg++;
rs.varianceflag= 1;
break;
case 'H' :
arg++;
rs.heteroflag= 1;
break;
case 'C' :
arg++;
rs.conflag= 1;
break;
case 'P' :
arg++;
rs.piflag= 1;
break;
case 'O' :
arg++;
rs.goodnessflag= 1;
break;
case 'Z' :
arg++;
rs.sitesflag= 1;
break;
case 'l' :
arg++;
rs.singletonflag= 1;
break;
case 'U' :
arg++;
rs.msitesflag= 1;
break;
case 'h' :
arg++;
rs.heterohapflag= 1;
break;
case 'u' :
arg++;
rs.configmicmeanflag= 1;
break;
case '0' :
arg++;
rs.heteroISflag= 1;
break;
case '1' :
arg++;
rs.conISflag= 1;
break;
case '2' :
arg++;
rs.piISflag= 1;
break;
case '4' :
arg++;
rs.sitesISflag= 1;
break;
case '5' :
arg++;
rs.sitesvarIS= 1;
break;
case '6' :
arg++;
rs.singletonISflag= 1;
break;
case '7' :
arg++;
rs.heterohapISflag= 1;
break;
case '8' :
arg++;
rs.configmicvarISflag= 1;
break;
case '9' :
arg++;
rs.varISflag= 1;
break;
case 'K' :
arg++;
microdata = malloc(100*sizeof(char));
strcpy(microdata,argv[arg]);
if( strlen(microdata) == 0 ) {fprintf(stderr," missing argument after -K\n" ); exit(0);}
//fprintf(stderr,"%s",microdata);
arg++;
rs.readmicroflag = 1;
break;
case 'k' :
arg++;
ISdata = malloc(100*sizeof(char));
strcpy(ISdata,argv[arg]);
if( strlen(ISdata) == 0 ) {fprintf(stderr," missing argument after -K\n" ); exit(0);}
//fprintf(stderr,"%s",ISdata);
arg++;
rs.readISflag = 1;
break;
case 'A' :
arg++;
argcheck( arg, argc, argv);
rs.readacceptances = atoi( argv[arg++]);
rs.acceptancesflag = 1;
break;
case 's' :
arg++;
argcheck( arg, argc, argv);
if( argv[arg-1][2] == 'e' ){ /* command line seeds */
pars.commandlineseedflag = 1 ;
if( count == 0 ) commandlineseed(argv+arg );
arg += 3 ;
}
else {
pars.mp.segsitesin = atoi( argv[arg++] );
}
break;
default:
// while( argv[arg][0] != '-' ) { arg++;}
arg++;
break;
}
}
}
/*printf("\nAlpha = %f\n",rs.alpha);*/
if (rs.readmicroflag ==0){
if((rs.varianceflag== 1) ||(rs.heteroflag== 1)|| (rs.conflag== 1) || (rs.piflag== 1) || (rs.goodnessflag== 1) || (rs.sitesflag== 1)
|| (rs.singletonflag== 1) || (rs.msitesflag== 1)|| (rs.heterohapflag== 1)|| (rs.configmicmeanflag== 1)){
fprintf(stderr,"Must enter input file of microsatelites with the command -K");exit(0);
}
}
if (rs.acceptancesflag == 0){
rs.readacceptances= atoi( argv[2] );
}
if(rs.readmicroflag == 1){
rs.datamicrosize = malloc(pars.cp.nsam*sizeof(int*));
for(i=0;i<pars.cp.nsam;i++){
*(rs.datamicrosize +i) = malloc(rs.micronumber*sizeof(int));
}
pf=fopen(microdata,"r");
if(pf==NULL){fprintf(stderr,"No file: %s",microdata);exit(0);}
i=0;
j=0;
while(fscanf(pf,"%d",&cr)!=EOF)
{
if(i >= rs.micronumber){
i=0;
j++;
}
//printf("\n%d %i %i",cr,i,j);
*(*(rs.datamicrosize + j)+i) =cr;
//printf(" %d",*(*(rs.datamicrosize + j)+i));
i++;
}
fclose(pf);
//printf("\n");
free(microdata);}
printf("Acceptancenum Simnum Time T0 T1 TMRCA");
if(rs.varianceflag == 1){
//printf ("La heterocigosis = %f\n", rs.dataheterozygosis);
rs.datavariancemean = variancemean(rs.datamicrosize, rs.micronumber, pars.cp.nsam);
printf(" Variance epsilonV");}
if(rs.heteroflag == 1){
rs.dataheterozygosis = heterozygosis(rs.datamicrosize, rs.micronumber, pars.cp.nsam);
printf(" Heterozygosis epsilonH");}
//printf ("Media de la varianza = %f\n", rs.datavariancemean);
if(rs.conflag == 1){
rs.datanumberofconfig = numberofconfigurations(rs.datamicrosize, rs.micronumber, pars.cp.nsam);
printf(" Numberofconfig epsilonC");}
if(rs.piflag == 1){
rs.datapi = nucdiv(pars.cp.nsam, rs.micronumber, rs.datamicrosize) ;
printf(" Pi epsilonP");}
if(rs.goodnessflag == 1){
mismatch (rs.datamicrosize, rs.micronumber, pars.cp.nsam);
rs.datamismatch = malloc ((rs.pairmaximum + 1)*sizeof(float));
rs.datamismatchmaximum = rs.pairmaximum;
for (i=0;i<=rs.datamismatchmaximum;i++){
*(rs.datamismatch + i) = *(rs.simmismatch + i);
//printf(" %f",*(rs.datamismatch + i));
}
printf(" Goodnessoffit");
free(rs.simmismatch);
}
if(rs.sitesflag == 1){
rs.datasites = sitesSMM(rs.datamicrosize,rs.micronumber,pars.cp.nsam) ;
printf(" Sites epsilonS");}
if(rs.singletonflag == 1){
rs.datasingleton = singleton(rs.datamicrosize,rs.micronumber,pars.cp.nsam) ;
//fprintf(stderr,"data = %i\n",rs.datasingleton);
printf(" Singleton epsilonSingleton");}
if(rs.msitesflag == 1){
rs.datamicsegsites = msitesvar(rs.datamicrosize,rs.micronumber,pars.cp.nsam) ;
//fprintf(stderr,"var = %f\n",rs.datamicsegsites);
printf(" Micsitesvar epsilonM");}
if(rs.heterohapflag == 1){
rs.dataheterohap = hetero(rs.datamicrosize,rs.micronumber,pars.cp.nsam) ;
//fprintf(stderr,"var = %f\n",rs.datamicsegsites);
printf(" Heteromean epsilonM");}
if(rs.configmicmeanflag == 1){
rs.dataconfigmicvar = configmicmean(rs.datamicrosize,rs.micronumber,pars.cp.nsam) ;
printf(" configmicvar epsilonCM");}
if (rs.readISflag ==0){
if((rs.varISflag== 1) ||(rs.heteroISflag== 1)|| (rs.conISflag== 1) || (rs.piISflag== 1) || (rs.sitesISflag== 1)
|| (rs.singletonISflag== 1) || (rs.sitesvarIS== 1)|| (rs.heterohapISflag== 1)|| (rs.configmicvarISflag== 1)){
fprintf(stderr,"Must enter input file of IS with the command -k");exit(0);
}
}
if (rs.readISflag ==1){
rs.datainfinitesitepart = malloc(pars.cp.nsam*sizeof(char**));
for(i=0;i<pars.cp.nsam;i++){
*(rs.datainfinitesitepart + i) = malloc(rs.micronumber*sizeof(char*));
for(j=0;j<rs.micronumber;j++){
//*(*(rs.datainfinitesitepart + i)+j) = malloc(10000*sizeof(char));
//strcpy( *(*(rs.datainfinitesitepart + i)+j), "");
}}
i=0;
j=0;
ch = malloc(100000*sizeof(char));
//fprintf(stderr,"segsites =%i\n",segsites);
int length;
rs.segsites=0;
pf=fopen(ISdata,"r");
if(pf==NULL){fprintf(stderr,"No file: %s",ISdata);exit(0);}
while(fscanf(pf,"%s",ch)!=EOF)
{
if(i >= rs.micronumber){
i=0;
j++;
//fprintf(stderr,"\n");
}
if(i==0){
rs.segsites = rs.segsites + strlen(ch);
}
//printf("\n%d %i %i",cr,i,j);
length = strlen(ch);
*(*(rs.datainfinitesitepart + j)+i) = malloc(length*sizeof(char));
if((strcmp(ch,"N"))==0){
strcpy(*(*(rs.datainfinitesitepart + j)+i),"");
}else{
strcpy(*(*(rs.datainfinitesitepart + j)+i),ch);}
//*(*(rs.datamicrosize + j)+i) =cr;
//fprintf(stderr," %s",*(*(rs.datainfinitesitepart + j)+i));
//sprintf(*(*(rs.datainfinitesitepart + j)+i),"%s",ch);
//fprintf(stderr,"%s ",ch);
i++;
}
fclose(pf);
free(ch);
free(ISdata);}
if(rs.varISflag == 1){
//printf ("La heterocigosis = %f\n", rs.dataheterozygosis);
rs.dataISvariancemean = varIS(rs.datainfinitesitepart, rs.micronumber, pars.cp.nsam);
//fprintf(stderr,"datavariance = %f",rs.dataISvariancemean);
printf(" Variance_IS epsilonV_IS");
}
if(rs.heteroISflag == 1){
rs.dataISheterozygosis = heterozygosisIS(rs.datainfinitesitepart, rs.micronumber, pars.cp.nsam);
printf(" Heterozygosis_IS epsilonH_IS");
//fprintf(stderr,"Heterozygosis = %f",rs.dataISheterozygosis);
}
//printf ("Media de la varianza = %f\n", rs.datavariancemean);
if(rs.conISflag == 1){
rs.dataISnumberofconfig = numberofconfigurationsIS(rs.datainfinitesitepart, rs.micronumber, pars.cp.nsam);
printf(" Numberofconfig_IS epsilonC_IS");
//fprintf(stderr,"numberofconfig = %i",rs.dataISnumberofconfig);
}
if(rs.piISflag == 1){
rs.dataISpi = nucdivIS(rs.datainfinitesitepart,rs.micronumber,pars.cp.nsam) ;
//fprintf(stderr,"pi = %f",rs.dataISpi);
printf(" Pi_IS epsilonP_IS");}
if(rs.sitesISflag == 1){
rs.dataISsites = sitesIS(rs.datainfinitesitepart,rs.micronumber,pars.cp.nsam) ;
//fprintf(stderr,"sitesI = %i",rs.dataISsites);
printf(" Sites_IS epsilonS_IS");}
if(rs.singletonISflag == 1){
rs.dataISsingleton = singletonIS(rs.datainfinitesitepart,rs.micronumber,pars.cp.nsam) ;
//fprintf(stderr,"singleton = %i\n",rs.dataISsingleton);
printf(" Singleton_IS epsilonSingleton_IS");}
if(rs.sitesvarIS == 1){
rs.dataISsitesvar = msitesvarIS(rs.datainfinitesitepart,rs.micronumber,pars.cp.nsam) ;
//fprintf(stderr,"varI = %f\n",rs.dataISsitesvar);
printf(" Micsitesvar_IS epsilonM_IS");}
if(rs.heterohapISflag == 1){
rs.dataISheterohap = heteroIS(rs.datainfinitesitepart,rs.micronumber,pars.cp.nsam) ;
//fprintf(stderr,"hetero = %f\n",rs.dataISheterohap);
printf(" Heteromean_IS epsilonM_IS");}
if(rs.configmicvarISflag == 1){
rs.dataISconfigmicvar = configmicvarIS(rs.datainfinitesitepart,rs.micronumber,pars.cp.nsam) ;
//fprintf(stderr,"configmicvar = %f\n",rs.dataISconfigmicvar);
printf(" configmicvar_IS epsilonCM_IS");}
printf(" SASHloc SH MASH SASH SHchanges SHdist HBC Simnum Alpha\n");
//rs.datamismatch =
/*mismatch (rs.datamicrosize, rs.micronumber, pars.cp.nsam);
rs.datamismatch = malloc ((rs.pairmaximum + 1)*sizeof(float));
rs.datamismatchmaximum = rs.pairmaximum;
for (i=0;i<=rs.datamismatchmaximum;i++){
*(rs.datamismatch + i) = *(rs.simmismatch + i);
printf(" %f",*(rs.datamismatch + i));
}
printf("\n");
free(rs.simmismatch);
//printf ("Mismatch de datos:\n");
for (i=0;i<=rs.datamismatchmaximum;i++){
//printf ("%f ",*(rs.datamismatch + i));
}
//printf("\n");
//printf ("numero de configuraciones = %i\n", rs.datanumberofconfig);
/*rs.dataFst = Fst(rs.datamicrosize, rs.micronumber, pars.cp.nsam, pars.cp.npop, pars.cp.config);
//printf("Fst = %f\n", rs.dataFst);
/*I add this piece of code*/
ntbs = 0 ; /* these next few lines are for reading in parameters from a file (for each sample) */
tbsparamstrs = (char **)malloc( argc*sizeof(char *) ) ;
/*for( i=0; i<argc; i++) printf("%s ",argv[i]);*/
for( i =0; i<argc; i++) tbsparamstrs[i] = (char *)malloc(30*sizeof(char) ) ;
for( i = 1; i<argc ; i++)
if( strcmp( argv[i],"tbs") == 0 ) argv[i] = tbsparamstrs[ ntbs++] ;
count=0;
if( ntbs > 0 ) for( k=0; k<ntbs; k++) scanf(" %s", tbsparamstrs[k] );
getpars( argc, argv, &howmany) ; /* results are stored in global variable, pars */
if( !pars.commandlineseedflag ) seedit( "s");
pf = stdout ;
if( pars.mp.segsitesin == 0 ) {
list = cmatrix(pars.cp.nsam,maxsites+1);
posit = (double *)malloc( (unsigned)( maxsites*sizeof( double)) ) ;
}
else {
list = cmatrix(pars.cp.nsam, pars.mp.segsitesin+1 ) ;
posit = (double *)malloc( (unsigned)( pars.mp.segsitesin*sizeof( double)) ) ;
if( pars.mp.theta > 0.0 ){
segfac = 1.0 ;
for( i= pars.mp.segsitesin; i > 1; i--) segfac *= i ;
}
}
while( howmany-count++ ) {
if( (ntbs > 0) && (count >1 ) ){
for( k=0; k<ntbs; k++){
if( scanf(" %s", tbsparamstrs[k]) == EOF ){
if( !pars.commandlineseedflag ) seedit( "end" );
exit(0);
}
}
getpars( argc, argv, &howmany) ;
}
//fprintf(pf,"\n//");
if( ntbs >0 ){
for(k=0; k< 3; k++){//printf("%s\t", tbsparamstrs[k] ) ;
}
}
//printf("\n");
segsites = gensam( list, &probss ) ;
rs.segsites = segsites;
if( (segsites > 0 ) || ( pars.mp.theta > 0.0 ) ) {
//fprintf(pf,"segsites: %d\n",segsites);
if( (pars.mp.segsitesin > 0 ) && ( pars.mp.theta > 0.0 ))
// fprintf(pf,"\nprob: %g", probss ) ;
if( segsites > 0 ){} //fprintf(pf,"\npositions: ");
for( i=0; i<segsites; i++){
//printf("%6.4lf ",posit[i] );
}
rs.segsites = segsites;
//fprintf(pf,"\n");
/*for(i=0;i<pars.cp.nsam;i++){
for(j=0;j<rs.micronumber;j++){
fprintf(stderr,"%s ",*(*(rs.datainfinitesitepart + i)+j));
}
fprintf(stderr,"\n");
}*/
//fprintf(pf,"Mis sitios\n");
if( segsites > 0 )
for(i=0;i<pars.cp.nsam; i++) { //fprintf(pf,"%s\n", list[i] );
/*Aqui voy a ver s puedo ver cada casilla de los caracteres de la matriz que me indican los sitios segregantes*/
for(k=0;k<segsites;k++){
// printf("%c",list[i][k]);
}
//
// printf("\n");
}
}
if(rs.rejectionflag==1){
rs.flagsimulation = 1;
simnum++;
rs.hcounter=1;
rs.simulationnumber++;
rs.microsegsite = NULL;
rs.microsize = NULL;
rs.microsegsite = malloc(segsites*sizeof(int));
rs.microsize = malloc(pars.cp.nsam*sizeof(int*));
for(i=0;i<pars.cp.nsam;i++){
*(rs.microsize +i) = NULL;
*(rs.microsize +i) = malloc(rs.micronumber*sizeof(int));
}
rs.infinitesitepart = malloc(pars.cp.nsam*sizeof(char**));
for(i=0;i<pars.cp.nsam;i++){
*(rs.infinitesitepart + i) = malloc(rs.micronumber*sizeof(char*));
}
for(i=0;i<pars.cp.nsam;i++){
for(j=0;j<rs.micronumber;j++){
*(*(rs.infinitesitepart + i)+j) = malloc(segsites*sizeof(char));
strcpy( *(*(rs.infinitesitepart + i)+j), "");
}}
// printf("%s\t",tbsparamstrs[0]);
//printf("Numero de micros = %i\n", rs.micronumber);
rs.fractionsites = 1.0/pars.cp.nsites;
rs.sitebeginning = 0.0;
rs.sitethreshold = 2.0/ pars.cp.nsites;
//printf("Site threshold = %6.4lf, pars.cp.nsites = %i", rs.sitethreshold ,pars.cp.nsites);
for (i=0; i<segsites; i++){
rs.randomnumber = ran1();
if(rs.randomnumber <= 0.5){
*(rs.microsegsite+i) = -1;
}else{
*(rs.microsegsite+i) = 1;
}
}
/*printf("Mi matriz de sitios segregantes\n");
for(i=0;i<pars.cp.nsam; i++) {
for(k=0;k<segsites;k++){}
printf("%c",list[i][k]);
printf("\n");
}
*/
//printf("Micro seg sites\n");
/*for (i=0;i<segsites;i++){
printf("%i ",*(rs.microsegsite+i));
}*/
for(i=0;i<rs.micronumber;i++){
for(k=0;k<pars.cp.nsam;k++){
*(*(rs.microsize +k)+i) = 0;
}
}
//printf("sitebeginning = %f, sitethreshold = %f va\n", rs.sitebeginning, rs.sitethreshold);
int initialflag = 0;
int finalflag = 0;
int micronumber = 0;
int *number;
int *number2;
char *segvalue;
char *segvalue2;
number = NULL;
number2 = NULL;
segvalue = NULL;
segvalue2 = NULL;
number = malloc (1*sizeof(int));
number2 = malloc (1*sizeof(int));
segvalue = malloc (1*sizeof(char));
segvalue2 = malloc (1*sizeof(char));
for(k=0;k<segsites;k++){
//printf("1sitebeginning = %f, sitethreshold = %f posit[k] = %f\n", rs.sitebeginning, rs.sitethreshold, posit[k]);
//printf("sitio aumenta o decrementa %i\n",*(rs.microsegsite+k));
for(j=0;j<pars.cp.nsam;j++){
//printf("list: %c\n",list[j][k]);
if(rs.sitebeginning ==0){initialflag =1;}
if((initialflag ==0) && (finalflag ==0)){
if(posit[k]>rs.sitebeginning && posit[k]< rs.sitethreshold){
//printf("micro!: %f micronumber = %i\n",posit[k], micronumber);
sprintf(segvalue,"%c" ,list[j][k]);
*number = atoi(segvalue);
if(*number ==1){
if(*(rs.microsegsite + k) ==1){*(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) + 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
else if (*(rs.microsegsite + k) == -1){ *(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) - 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
}else {strcat(*(*(rs.infinitesitepart+j)+micronumber),"0");}
}else if (posit[k]<=(rs.sitebeginning + (4*rs.fractionsites))){
//printf("entre sitio: %f\n",posit[k]);
}
else{
while(posit[k]> (rs.sitebeginning + (4*rs.fractionsites)) ){
rs.sitebeginning = rs.sitebeginning + (4*rs.fractionsites);
rs.sitethreshold = rs.sitethreshold + (4*rs.fractionsites);
initialflag =0;
micronumber ++;
if(rs.sitethreshold ==1.0){finalflag =1;
//printf("microweird!: %f micronumber = %i\n",posit[k], micronumber);
sprintf(segvalue,"%c" ,list[j][k]);
*number = atoi(segvalue);
if(*number ==1){
if(*(rs.microsegsite + k) ==1){*(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) + 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
else if (*(rs.microsegsite + k) == -1){ *(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) - 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
}else {strcat(*(*(rs.infinitesitepart+j)+micronumber),"0");}
break;
}
else if(posit[k]>rs.sitebeginning && posit[k]< rs.sitethreshold){
//printf("micro!: %f micronumber = %i\n",posit[k],micronumber);
sprintf(segvalue,"%c" ,list[j][k]);
*number = atoi(segvalue);
if(*number ==1){
if(*(rs.microsegsite + k) ==1){*(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) + 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
else if (*(rs.microsegsite + k) == -1){ *(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) - 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
}else {strcat(*(*(rs.infinitesitepart+j)+micronumber),"0");}
break;
}
}
if (posit[k]>= rs.sitethreshold){
//printf("entre sitio: %f\n",posit[k]);
}
}
}else if (initialflag == 1){
if(posit[k]>=rs.sitebeginning && posit[k]< rs.sitethreshold){
//printf("micro!: %f micronumber = %i\n",posit[k], micronumber);
sprintf(segvalue,"%c" ,list[j][k]);
*number = atoi(segvalue);
if(*number ==1){
if(*(rs.microsegsite + k) ==1){*(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) + 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
else if (*(rs.microsegsite + k) == -1){ *(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) - 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
}else {strcat(*(*(rs.infinitesitepart+j)+micronumber),"0");}
}else if (posit[k]<=(rs.sitebeginning + (4*rs.fractionsites))){
//printf("entre sitio: %f\n",posit[k]);
}
else{
while(posit[k]> (rs.sitebeginning + (4*rs.fractionsites)) ){
rs.sitebeginning = rs.sitebeginning + (4*rs.fractionsites);
rs.sitethreshold = rs.sitethreshold + (4*rs.fractionsites);
micronumber++;
initialflag =0;
if(rs.sitethreshold ==1.0){finalflag =1;
//printf("microweird!: %f micronumber = %i\n",posit[k], micronumber);
sprintf(segvalue,"%c" ,list[j][k]);
*number = atoi(segvalue);
if(*number ==1){
if(*(rs.microsegsite + k) ==1){*(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) + 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
else if (*(rs.microsegsite + k) == -1){ *(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) - 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
}else {strcat(*(*(rs.infinitesitepart+j)+micronumber),"0");}
}
else if(posit[k]>rs.sitebeginning && posit[k]< rs.sitethreshold){
//printf("micro!: %f micronumber = %i\n",posit[k], micronumber);
sprintf(segvalue,"%c" ,list[j][k]);
*number = atoi(segvalue);
if(*number ==1){
if(*(rs.microsegsite + k) ==1){*(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) + 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
else if (*(rs.microsegsite + k) == -1){ *(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) - 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
}else {strcat(*(*(rs.infinitesitepart+j)+micronumber),"0");}
break;
}
}
if (posit[k]>= rs.sitethreshold){
//printf("entre sitio: %f\n",posit[k]);
}
}
}else if (finalflag ==1){
if(posit[k]>rs.sitebeginning && posit[k]<= rs.sitethreshold){
//printf("micro!: %f micronumber = %i\n",posit[k], micronumber);
sprintf(segvalue,"%c" ,list[j][k]);
*number = atoi(segvalue);
if(*number ==1){
if(*(rs.microsegsite + k) ==1){*(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) + 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
else if (*(rs.microsegsite + k) == -1){ *(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) - 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
}else {strcat(*(*(rs.infinitesitepart+j)+micronumber),"0");}
}else if (posit[k]<=(rs.sitebeginning + (4*rs.fractionsites))){
//printf("entre sitio: %f\n",posit[k]);
}
else{
while(posit[k]> (rs.sitebeginning + (4*rs.fractionsites)) ){
rs.sitebeginning = rs.sitebeginning + (4*rs.fractionsites);
rs.sitethreshold = rs.sitethreshold + (4*rs.fractionsites);
micronumber ++;
initialflag =0;
if(rs.sitethreshold ==1.0){finalflag =1;
//printf("microweird!: %f micronumber = %i\n",posit[k], micronumber);
sprintf(segvalue,"%c" ,list[j][k]);
*number = atoi(segvalue);
if(*number ==1){
if(*(rs.microsegsite + k) ==1){*(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) + 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
else if (*(rs.microsegsite + k) == -1){ *(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) - 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
}else {strcat(*(*(rs.infinitesitepart+j)+micronumber),"0");}
}
else if(posit[k]>rs.sitebeginning && posit[k]< rs.sitethreshold){
//printf("micro!: %f micronumber = %i\n",posit[k], micronumber);
sprintf(segvalue,"%c" ,list[j][k]);
*number = atoi(segvalue);
if(*number ==1){
if(*(rs.microsegsite + k) ==1){*(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) + 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
else if (*(rs.microsegsite + k) == -1){ *(*(rs.microsize + j) +micronumber) = *(*(rs.microsize + j) +micronumber) - 1;
strcat(*(*(rs.infinitesitepart+j)+micronumber),"1");}
}else {strcat(*(*(rs.infinitesitepart+j)+micronumber),"0");}
break;
}
}
if (posit[k]>= rs.sitethreshold){
//printf("entre sitio: %f\n",posit[k]);
}
}
}
}
//printf(" initial flag %i final flag %i\n",initialflag , finalflag);
}
//printf("2sitebeginning = %f, sitethreshold = %f posit[k] = %f\n", rs.sitebeginning, rs.sitethreshold, posit[k]);
rs.flagbegin=0;
//printf ("Tamano de microsatelites\n");
for(k=0;k<rs.micronumber;k++){
//printf("\t%i",k);
}
//printf("Micros\n");
for(k=0;k<pars.cp.nsam;k++){
// printf ("%i",k);
for(i=0;i<rs.micronumber;i++){
// printf (" %i",*(*(rs.microsize +k)+i));
}
// printf ("\n");
}
//printf("\n");
/*El primer estadstico de resumen a probar ser la media de la varianza en el nmero de repeats entre varios loci */
//(rs.datavariancemean)/rs.datavariancemean
if(rs.varianceflag == 1){
rs.rejectionvariance = variancemean(rs.microsize, rs.micronumber, pars.cp.nsam);
if (rs.datavariancemean == 0){
if (rs.rejectionvariance == 0){
rs.dif1 = 0;
}else{
rs.flagsimulation = 0 ;
rs.dif1 = 10000;
}
}else{
rs.dif1 = (rs.datavariancemean -rs.rejectionvariance) / rs.datavariancemean;
//fprintf (stderr,"\nLa media de la varianza1 = %f, sim = %i, dif = %f", rs.rejectionvariance, simnum,rs.dif1);
if (rs.dif1>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif1<-rs.alpha){
rs.flagsimulation =0;}}
}
/*rs.datavariancemean = variancemean(rs.datamicrosize, rs.micronumber, pars.cp.nsam);
printf ("Media de la varianza = %f\n", rs.datavariancemean);
/*Heterocigosis*/
if(rs.heteroflag == 1){
rs.heterozygosismean = heterozygosis(rs.microsize, rs.micronumber, pars.cp.nsam);
//printf ("\nHeterocigosis1 = %f\n", rs.heterozygosismean);
if (rs.dataheterozygosis == 0){
if (rs.heterozygosismean == 0){
rs.dif2 = 0;
}else{
rs.flagsimulation = 0 ;
rs.dif2 = 10000;
}
}else{
rs.dif2 = (rs.dataheterozygosis -rs.heterozygosismean) / rs.dataheterozygosis;
if (rs.dif2>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif2<-rs.alpha){
rs.flagsimulation =0;}}
}
/*Vamos a contar el nmero de configuraciones de microsatlites*/
if(rs.conflag == 1){
rs.numberconfigurations = numberofconfigurations(rs.microsize, rs.micronumber, pars.cp.nsam);
//printf ("\nNumber of configurations1 = %i\n", rs.numberconfigurations);
if (rs.datanumberofconfig == 0){
if (rs.numberconfigurations == 0){
rs.dif3 = 0;
}else{
rs.flagsimulation = 0 ;
rs.dif3 = 10000;
}
}else{
rs.dif3 = (float)(rs.datanumberofconfig -rs.numberconfigurations) /rs.datanumberofconfig;
if (rs.dif3>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif3<-rs.alpha){
rs.flagsimulation =0;}}
}
if(rs.piflag){
rs.pi = nucdiv(pars.cp.nsam, rs.micronumber, rs.microsize) ;
if (rs.datapi == 0){
if (rs.pi == 0){
rs.dif4 = 0;
}else{
rs.flagsimulation = 0 ;
rs.dif4 = 10000;
}
}else{
rs.dif4 = (float)(rs.datapi -rs.pi) /rs.datapi;
if (rs.dif4>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif4<-rs.alpha){
rs.flagsimulation =0;}}
}
if(rs.goodnessflag == 1){
mismatch (rs.microsize, rs.micronumber, pars.cp.nsam);
rs.dif5 = 0;
if (rs.datamismatchmaximum<rs.pairmaximum){
rs.realminimum = rs.datamismatchmaximum;
rs.realmaximum = rs.pairmaximum;
rs.flag = 1;
} else{
rs.realminimum = rs.pairmaximum;
rs.realmaximum = rs.datamismatchmaximum;
rs.flag = 0;
}
for (i=0;i<=rs.realminimum;i++){
if (*(rs.simmismatch + i)> *(rs.datamismatch + i)){
rs.dif5 = rs.dif5 + *(rs.simmismatch + i)-*(rs.datamismatch + i);
} else{
rs.dif5 = rs.dif5 + *(rs.datamismatch + i) - *(rs.simmismatch + i);}
}
if (rs.flag == 1){
for (i=rs.realminimum +1;i<=rs.realmaximum;i++){
rs.dif5 = rs.dif5 + *(rs.simmismatch + i);
}
}
if (rs.flag == 0){
for (i=rs.realminimum +1;i<=rs.realmaximum;i++){
rs.dif5 = rs.dif5 + *(rs.datamismatch + i);
}
}
if (rs.dif5>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif5<-rs.alpha){
rs.flagsimulation =0;}
}
if(rs.sitesflag == 1){
rs.simsites = sitesSMM(rs.microsize,rs.micronumber,pars.cp.nsam) ;
if (rs.datasites == 0){
if (rs.simsites == 0){
rs.dif6 = 0;
}else{
rs.flagsimulation = 0 ;
rs.dif6 = 10000;
}
}else{
rs.dif6 = (float)(rs.datasites -rs.simsites) /rs.datasites;
if (rs.dif6>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif6<-rs.alpha){
rs.flagsimulation =0;}}
}
if(rs.singletonflag == 1){
rs.simsingleton = singleton(rs.microsize,rs.micronumber,pars.cp.nsam) ;
if (rs.datasingleton == 0){
if (rs.simsingleton == 0){
rs.dif7 = 0;
}else{
rs.flagsimulation = 0 ;
rs.dif7 = 10000;
}
}else{
rs.dif7 = (float)(rs.datasingleton -rs.simsingleton) /rs.datasingleton;
//fprintf(stderr," simsingleton =%i datasingleton = %i dif = %f\n",rs.simsingleton,rs.datasingleton,rs.dif7);
if (rs.dif7>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif7<-rs.alpha){
rs.flagsimulation =0;}}
}
if(rs.msitesflag== 1){
rs.simmicsegsites = msitesvar(rs.microsize,rs.micronumber,pars.cp.nsam) ;
//fprintf(stderr,"%i\n",rs.simsingleton);
//fprintf(stderr,"varsim = %f\n",rs.simmicsegsites);
if (rs.datamicsegsites == 0){
if (rs.simmicsegsites == 0){
rs.dif8 = 0;
}else{
rs.flagsimulation = 0 ;
rs.dif8 = 10000;
}
}else{
rs.dif8 = (float)(rs.datamicsegsites-rs.simmicsegsites) /rs.datamicsegsites;
if (rs.dif8>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif8<-rs.alpha){
rs.flagsimulation =0;}}
}
if(rs.heterohapflag== 1){
rs.simheterohap = hetero(rs.microsize,rs.micronumber,pars.cp.nsam) ;
//fprintf(stderr,"%i\n",rs.simsingleton);
//fprintf(stderr,"varsim = %f\n",rs.simmicsegsites);
if (rs.dataheterohap == 0){
if (rs.simheterohap == 0){
rs.dif9 = 0;
}else{
rs.flagsimulation = 0 ;
rs.dif9 = 10000;
}
}else{
rs.dif9 = (float)(rs.dataheterohap-rs.simheterohap) /rs.dataheterohap;
if (rs.dif9>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif9<-rs.alpha){
rs.flagsimulation =0;}}
}
if(rs.configmicmeanflag== 1){
rs.simconfigmicvar = configmicmean(rs.microsize,rs.micronumber,pars.cp.nsam) ;
//fprintf(stderr,"%i\n",rs.simsingleton);
//fprintf(stderr,"varsim = %f data = %f\n",rs.simconfigmicvar, rs.dataconfigmicvar);
rs.dif10 = (float)(rs.dataconfigmicvar-rs.simconfigmicvar) /rs.dataconfigmicvar;
if (rs.dif10>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif10<-rs.alpha){
rs.flagsimulation =0;}
}
if(rs.varISflag == 1){
//printf ("La heterocigosis = %f\n", rs.dataheterozygosis);
rs.simISvariancemean = varIS(rs.infinitesitepart, rs.micronumber, pars.cp.nsam);
//fprintf(stderr,"simvariance = %f",rs.simISvariancemean);
rs.dif11 = (float)(rs.dataISvariancemean-rs.simISvariancemean) /rs.dataISvariancemean;
if (rs.dif11>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif11<-rs.alpha){
rs.flagsimulation =0;}
}
if(rs.heteroISflag == 1){
rs.simISheterozygosis = heterozygosisIS(rs.infinitesitepart, rs.micronumber, pars.cp.nsam);
rs.dif12 = (float)(rs.dataISheterozygosis-rs.simISheterozygosis) /rs.dataISheterozygosis;
//fprintf(stderr,"Heterozygosis = %f",rs.simISheterozygosis);
if (rs.dif12>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif12<-rs.alpha){
rs.flagsimulation =0;}
}
if(rs.conISflag == 1){
rs.simISnumberofconfig = numberofconfigurationsIS(rs.infinitesitepart, rs.micronumber, pars.cp.nsam);
rs.dif13 = (float)(rs.dataISnumberofconfig-rs.simISnumberofconfig) /rs.dataISnumberofconfig;
//fprintf(stderr,"numberofconfigsim = %i",rs.simISnumberofconfig);
if (rs.dif13>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif13<-rs.alpha){
rs.flagsimulation =0;}
}
if(rs.piISflag == 1){
rs.simISpi = nucdivIS(rs.infinitesitepart, rs.micronumber, pars.cp.nsam);
rs.dif14 = (float)(rs.dataISpi-rs.simISpi) /rs.dataISpi;
//fprintf(stderr,"simpi = %f",rs.simISpi);
if (rs.dif14>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif14<-rs.alpha){
rs.flagsimulation =0;}
}
if(rs.sitesISflag == 1){
rs.simISsites = sitesIS(rs.infinitesitepart, rs.micronumber, pars.cp.nsam);
rs.dif15 = (float)(rs.dataISsites-rs.simISsites) /rs.dataISsites;
//fprintf(stderr,"simsites = %i",rs.simISsites);
if (rs.dif15>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif15<-rs.alpha){
rs.flagsimulation =0;}
}
if(rs.singletonISflag == 1){
rs.simISsingleton = sitesIS(rs.infinitesitepart, rs.micronumber, pars.cp.nsam);
rs.dif16 = (float)(rs.dataISsingleton-rs.simISsingleton) /rs.dataISsingleton;
//fprintf(stderr,"simsing = %i",rs.simISsingleton);
if (rs.dif16>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif16<-rs.alpha){
rs.flagsimulation =0;}
}
if(rs.sitesvarIS == 1){
rs.simISsitesvar = msitesvarIS(rs.infinitesitepart, rs.micronumber, pars.cp.nsam);
rs.dif17 = (float)(rs.dataISsitesvar-rs.simISsitesvar) /rs.dataISsitesvar;
//fprintf(stderr,"simsitesvar = %f",rs.simISsitesvar);
if (rs.dif17>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif17<-rs.alpha){
rs.flagsimulation =0;}
}
if(rs.heterohapISflag == 1){
rs.simISheterohap = heteroIS(rs.infinitesitepart, rs.micronumber, pars.cp.nsam);
rs.dif18 = (float)(rs.dataISheterohap-rs.simISheterohap) /rs.dataISheterohap;
//fprintf(stderr,"simhap = %f",rs.simISheterohap);
if (rs.dif18>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif18<-rs.alpha){
rs.flagsimulation =0;}
}
if(rs.configmicvarISflag == 1){
rs.simISconfigmicvar = configmicvarIS(rs.infinitesitepart, rs.micronumber, pars.cp.nsam);
rs.dif19 = (float)(rs.dataISconfigmicvar-rs.simISconfigmicvar) /rs.dataISconfigmicvar;
//fprintf(stderr,"simconfigvar = %f\n",rs.simISconfigmicvar);
if (rs.dif19>rs.alpha){
rs.flagsimulation =0;}
if (rs.dif19<-rs.alpha){
rs.flagsimulation =0;}
}
if(rs.flagsimulation == 1){
rs.sizehomoplasy1 = sizehomoplasyloc (rs.microsize, rs.micronumber, pars.cp.nsam,rs.infinitesitepart);
rs.SH = SH(rs.microsize, rs.micronumber, pars.cp.nsam,rs.infinitesitepart);
rs.MASH = MASH(rs.microsize, rs.micronumber, pars.cp.nsam);
rs.SASH = SASH(rs.microsize, rs.micronumber, pars.cp.nsam,rs.infinitesitepart);
rs.SHchanges = SHchanges(rs.microsize, rs.micronumber, pars.cp.nsam,rs.infinitesitepart);
rs.SHdist = SHdistance(rs.microsize, rs.micronumber, pars.cp.nsam,rs.infinitesitepart);
rs.HBC = HomoBC(rs.microsize, rs.micronumber, pars.cp.nsam,rs.infinitesitepart);
rs.acceptances++;
//fprintf (stderr,"\nLa media de la varianza1 = %f, sim = %i, dif = %f", rs.rejectionvariance, simnum,rs.dif1);
printf("%i ",rs.acceptances);
printf("%i ",simnum);
for(k=0; k< 3; k++){
printf("%s\t", tbsparamstrs[k] ) ;
}
printf("%f\t",rs.TMRCA);
if(rs.varianceflag == 1){
//printf ("La heterocigosis = %f\n", rs.dataheterozygosis);
//fprintf (stderr,"\nLa media de la varianza1 = %f, sim = %i, dif = %f", rs.rejectionvariance, simnum,rs.dif1);
printf("%f %f ",rs.rejectionvariance,rs.dif1);}
if(rs.heteroflag == 1){
printf("%f %f ",rs.heterozygosismean,rs.dif2);}
//printf ("Media de la varianza = %f\n", rs.datavariancemean);
if(rs.conflag == 1){
printf("%i %f ",rs.numberconfigurations,rs.dif3);}
if(rs.piflag == 1){
printf("%f %f ",rs.pi,rs.dif4);}
if(rs.goodnessflag == 1){
printf("%f ",rs.dif5);
free(rs.simmismatch);
}
if(rs.sitesflag == 1){
printf("%i %f ",rs.simsites,rs.dif6);}
if(rs.singletonflag == 1){
printf("%i %f ",rs.simsingleton,rs.dif7);
}if(rs.msitesflag == 1){
printf("%f %f ",rs.simmicsegsites,rs.dif8);
}
if(rs.heterohapflag == 1){
printf("%f %f ",rs.simheterohap,rs.dif9);
}
if(rs.configmicmeanflag== 1){
printf("%f %f ",rs.simconfigmicvar,rs.dif10);
}
if(rs.varISflag == 1){
printf("%f %f ",rs.simISvariancemean,rs.dif11);
}
if(rs.heteroISflag == 1){
printf("%f %f ",rs.simISheterozygosis,rs.dif12);
}
if(rs.conISflag == 1){
printf("%i %f ",rs.simISnumberofconfig,rs.dif13);
}
if(rs.piISflag == 1){
printf("%f %f ",rs.simISpi,rs.dif14);
}
if(rs.sitesISflag == 1){
printf("%i %f ",rs.simISsites,rs.dif15);
}
if(rs.singletonISflag == 1){
printf("%i %f ",rs.simISsingleton,rs.dif16);
}
if(rs.sitesvarIS == 1){
printf("%f %f ",rs.simISsitesvar,rs.dif17);
}
if(rs.heterohapISflag == 1){
printf("%f %f ",rs.simISheterohap,rs.dif18);
}
if(rs.configmicvarISflag == 1){
printf("%f %f ",rs.simISconfigmicvar,rs.dif19);
}
printf("%f %f %f %f %f %f %f %i %f",rs.sizehomoplasy1, rs.SH, rs.MASH, rs.SASH, rs.SHchanges, rs.SHdist,rs.HBC,simnum, rs.alpha);
printf ("\n");
if((rs.tauflag == 1) && (atof(tbsparamstrs[0])>= rs.tauthreshold)){
rs.uppersims= malloc(30*sizeof(char));
sprintf(rs.uppersims, "%i_sim.txt", simnum);
sims=fopen(rs.uppersims,"w");
for(k=0;k<pars.cp.nsam;k++){
for(i=0;i<rs.micronumber;i++){
if (i<rs.micronumber-1){
fprintf (sims,"%i ",*(*(rs.microsize +k)+i));}else{
fprintf (sims,"%i",*(*(rs.microsize +k)+i));
}
}
fprintf (sims,"\n");}
fclose(sims);
rs.uppersims= malloc(30*sizeof(char));
sprintf(rs.uppersims, "%i_siminf.txt", simnum);
sims=fopen(rs.uppersims,"w");
for(k=0;k<pars.cp.nsam;k++){
for(i=0;i<rs.micronumber;i++){
if (i<rs.micronumber-1){
fprintf (sims,"%s ",*(*(rs.infinitesitepart+k)+i));}else{
fprintf (sims,"%s",*(*(rs.infinitesitepart +k)+i));
}
}
fprintf (sims,"\n");
}
fclose(sims);
}
if((rs.tauflagmin == 1) && (atof(tbsparamstrs[0])<= rs.tauthresholdmax) && (atof(tbsparamstrs[0])>= rs.tauthresholdmin)){
rs.uppersims= malloc(30*sizeof(char));
sprintf(rs.uppersims, "%i_simmin.txt", simnum);
sims=fopen(rs.uppersims,"w");
for(k=0;k<pars.cp.nsam;k++){
for(i=0;i<rs.micronumber;i++){
if (i<rs.micronumber-1){
fprintf (sims,"%i ",*(*(rs.microsize +k)+i));}else{
fprintf (sims,"%i",*(*(rs.microsize +k)+i));
}
}
fprintf (sims,"\n");}
fclose(sims);
rs.uppersims= malloc(30*sizeof(char));
sprintf(rs.uppersims, "%i_siminfmin.txt", simnum);
sims=fopen(rs.uppersims,"w");
for(k=0;k<pars.cp.nsam;k++){
for(i=0;i<rs.micronumber;i++){
if (i<rs.micronumber-1){
fprintf (sims,"%s ",*(*(rs.infinitesitepart+k)+i));}else{
fprintf (sims,"%s",*(*(rs.infinitesitepart +k)+i));
}
}
fprintf (sims,"\n");
}
fclose(sims);
}
}
if (rs.acceptances >= rs.readacceptances){
exit(1);}
if( ( simnum % 1000 ) == 0) {
fprintf(stderr,"simnum = %i acceptances = %i\n",simnum,rs.acceptances);
if(simnum == 50000){
if(rs.acceptances == 0){
fprintf (stderr,"There hasnt been an acceptance after 50,000 simulations");
exit (1);
}
}
}
for(i=0;i<pars.cp.nsam;i++){
for(j=0;j<rs.micronumber;j++){
free(*(*(rs.infinitesitepart + i)+j));
}}
for(i=0;i<pars.cp.nsam;i++){
free(*(rs.infinitesitepart + i));
}
free(rs.infinitesitepart);
free(number);
free(number2);
free(segvalue);
free(segvalue2);
free (rs.microsegsite);
for(i=0;i<pars.cp.nsam;i++){
free(*(rs.microsize +i));
}
free (rs.microsize);
}
//free(rs.simmismatch);
}
//printf("\nTajimas D: %f",tajd(pars.cp.nsam,segsites,pi));
if( !pars.commandlineseedflag ) seedit( "end" );
}
int
gensam( char **list, double *pprobss )
{
int nsegs, h, i, k, j, seg, ns, start, end, len, segsit ;
struct segl *seglst, *segtre_mig(struct c_params *p, int *nsegs ) ; /* used to be: [MAXSEG]; */
double nsinv, tseg, tt, ttime(struct node *, int nsam), ttimemf(struct node *, int nsam, int mfreq), division ;
double *pk;
int *ss;
int segsitesin,nsites;
double theta, es ;
int nsam, mfreq ;
void prtree( struct node *ptree, int nsam);
int make_gametes(int nsam, int mfreq, struct node *ptree, double tt, int newsites, int ns, char **list );
void ndes_setup( struct node *, int nsam );
nsites = pars.cp.nsites ;
nsinv = 1./nsites;
/*Ver cmo funciona esto*/
//printf("sitios %f\n",nsinv);
seglst = segtre_mig(&(pars.cp), &nsegs ) ;
nsam = pars.cp.nsam;
segsitesin = pars.mp.segsitesin ;
/*One line to adjust for theta in the microsatellites*/
division =(float)pars.mp.theta*(((float)rs.micronumber-1)/((float)rs.micronumber));
//printf ("Tus micros = %i y division %f",rs.micronumber, division);
theta = pars.mp.theta + division;
/*End of my line to adjust for theta*/
mfreq = pars.mp.mfreq ;
if( pars.mp.treeflag ) {
ns = 0 ;
for( seg=0, k=0; k<nsegs; seg=seglst[seg].next, k++) {
if( (pars.cp.r > 0.0 ) || (pars.cp.f > 0.0) ){
end = ( k<nsegs-1 ? seglst[seglst[seg].next].beg -1 : nsites-1 );
start = seglst[seg].beg ;
len = end - start + 1 ;
// fprintf(stdout,"[%d]", len);
}
prtree( seglst[seg].ptree, nsam ) ;
if( (segsitesin == 0) && ( theta == 0.0 ) )
free(seglst[seg].ptree) ;
}
}
if( (segsitesin == 0) && ( theta > 0.0) ) {
ns = 0 ;
for( seg=0, k=0; k<nsegs; seg=seglst[seg].next, k++) {
if( mfreq > 1 ) ndes_setup( seglst[seg].ptree, nsam );
end = ( k<nsegs-1 ? seglst[seglst[seg].next].beg -1 : nsites-1 );
start = seglst[seg].beg ;
//printf("start %i y end %i\n",start,end);
len = end - start + 1 ;
tseg = len*(theta/nsites) ;
if( mfreq == 1) tt = ttime(seglst[seg].ptree, nsam);
else tt = ttimemf(seglst[seg].ptree, nsam, mfreq );
segsit = poisso( tseg*tt );
if( (segsit + ns) >= maxsites ) {
maxsites = segsit + ns + SITESINC ;
posit = (double *)realloc(posit, maxsites*sizeof(double) ) ;
biggerlist(nsam, list) ;
}
make_gametes(nsam,mfreq,seglst[seg].ptree,tt, segsit, ns, list );
free(seglst[seg].ptree) ;
locate(segsit,start*nsinv, len*nsinv,posit+ns);
ns += segsit;
}
} /*Mi desmadre*/
else if ((segsitesin == 0) && ( rs.variablethetaflag == 1)){
float startmicro = 0;
float endmicro = 1;
int thetacounter = 0;
ns = 0 ;
// printf ("follow me down\n");
for( seg=0, k=0; k<nsegs; seg=seglst[seg].next, k++) {
if( mfreq > 1 ) ndes_setup( seglst[seg].ptree, nsam );
end = ( k<nsegs-1 ? seglst[seglst[seg].next].beg -1 : nsites-1 );
start = seglst[seg].beg ;
//printf("start %i y end %i\n",start,end);
//printf("To the valley below\n");
while ((startmicro >=start) && (endmicro <=end)){
if (endmicro == (pars.cp.nsites-1)){
//printf("enter");
tseg = *(rs.thetavalues + thetacounter) ;
if( mfreq == 1) tt = ttime(seglst[seg].ptree, nsam);
else tt = ttimemf(seglst[seg].ptree, nsam, mfreq );
segsit = poisso( tseg*tt );
//printf ("Segsit = %i",segsit);
if( (segsit + ns) >= maxsites ) {
maxsites = segsit + ns + SITESINC ;
posit = (double *)realloc(posit, maxsites*sizeof(double) ) ;
biggerlist(nsam, list) ;
}
make_gametes(nsam,mfreq,seglst[seg].ptree,tt, segsit, ns, list );
locate(segsit,startmicro*nsinv, 2*nsinv,posit+ns);
ns += segsit;
//printf ("theta counter1 = %i, startm = %f, endm = %f, start = %i, end = %i, tseg = %f\n",thetacounter,startmicro,endmicro,start,end,*(rs.thetavalues + thetacounter));
thetacounter++;
startmicro = startmicro + 4;
endmicro = endmicro + 4;
} else{
// printf("enter");
tseg = 2* *(rs.thetavalues + thetacounter) ;
if( mfreq == 1) tt = ttime(seglst[seg].ptree, nsam);
else tt = ttimemf(seglst[seg].ptree, nsam, mfreq );
segsit = poisso( tseg*tt );
//printf ("Segsit = %i",segsit);
if( (segsit + ns) >= maxsites ) {
maxsites = segsit + ns + SITESINC ;
posit = (double *)realloc(posit, maxsites*sizeof(double) ) ;
biggerlist(nsam, list) ;
}
make_gametes(nsam,mfreq,seglst[seg].ptree,tt, segsit, ns, list );
locate(segsit,startmicro*nsinv, 4*nsinv,posit+ns);
ns += segsit;
//printf ("theta counter2 = %i, startm = %f, endm = %f, start = %i, end = %i, tseg = %f\n",thetacounter,startmicro,endmicro,start,end,*(rs.thetavalues + thetacounter));
thetacounter++;
startmicro = startmicro + 4;
endmicro = endmicro + 4;
}
}
free(seglst[seg].ptree);
}
}
/*Fin de mi desmadre*/
else if( segsitesin > 0 ) {
pk = (double *)malloc((unsigned)(nsegs*sizeof(double)));
ss = (int *)malloc((unsigned)(nsegs*sizeof(int)));
if( (pk==NULL) || (ss==NULL) ) perror("malloc error. gensam.2");
tt = 0.0 ;
for( seg=0, k=0; k<nsegs; seg=seglst[seg].next, k++) {
if( mfreq > 1 ) ndes_setup( seglst[seg].ptree, nsam );
end = ( k<nsegs-1 ? seglst[seglst[seg].next].beg -1 : nsites-1 );
start = seglst[seg].beg ;
len = end - start + 1 ;
tseg = len/(double)nsites ;
if( mfreq == 1 ) pk[k] = ttime(seglst[seg].ptree,nsam)*tseg ;
else pk[k] = ttimemf(seglst[seg].ptree,nsam, mfreq)*tseg ;
tt += pk[k] ;
}
if( theta > 0.0 ) {
es = theta * tt ;
*pprobss = exp( -es )*pow( es, (double) segsitesin) / segfac ;
}
if( tt > 0.0 ) {
for (k=0;k<nsegs;k++) pk[k] /= tt ;
mnmial(segsitesin,nsegs,pk,ss);
}
else
for( k=0; k<nsegs; k++) ss[k] = 0 ;
ns = 0 ;
for( seg=0, k=0; k<nsegs; seg=seglst[seg].next, k++) {
end = ( k<nsegs-1 ? seglst[seglst[seg].next].beg -1 : nsites-1 );
start = seglst[seg].beg ;
len = end - start + 1 ;
tseg = len/(double)nsites;
make_gametes(nsam,mfreq,seglst[seg].ptree,tt*pk[k]/tseg, ss[k], ns, list);
free(seglst[seg].ptree) ;
locate(ss[k],start*nsinv, len*nsinv,posit+ns);
ns += ss[k] ;
}
free(pk);
free(ss);
}
for(i=0;i<nsam;i++) list[i][ns] = '\0' ;
return( ns ) ;
}
void
ndes_setup(struct node *ptree, int nsam )
{
int i ;
for( i=0; i<nsam; i++) (ptree+i)->ndes = 1 ;
for( i = nsam; i< 2*nsam -1; i++) (ptree+i)->ndes = 0 ;
for( i= 0; i< 2*nsam -2 ; i++) (ptree+((ptree+i)->abv))->ndes += (ptree+i)->ndes ;
}
int
biggerlist(nsam, list )
int nsam ;
char ** list ;
{
int i;
/* fprintf(stderr,"maxsites: %d\n",maxsites); */
for( i=0; i<nsam; i++){
list[i] = (char *)realloc( list[i],maxsites*sizeof(char) ) ;
if( list[i] == NULL ) perror( "realloc error. bigger");
}
}
/* allocates space for gametes (character strings) */
char **
cmatrix(nsam,len)
int nsam, len;
{
int i;
char **m;
if( ! ( m = (char **) malloc( (unsigned) nsam*sizeof( char* ) ) ) )
perror("alloc error in cmatrix") ;
for( i=0; i<nsam; i++) {
if( ! ( m[i] = (char *) malloc( (unsigned) len*sizeof( char ) )))
perror("alloc error in cmatric. 2");
}
return( m );
}
int
locate(n,beg,len,ptr)
int n;
double beg, len, *ptr;
{
int i;
ordran(n,ptr);
for(i=0; i<n; i++)
ptr[i] = beg + ptr[i]*len ;
/*Agregue estoprintf("%f ",ptr[i]);*/
/*Y esto*/ //printf("va\n");
}
void
getpars(int argc, char *argv[], int *phowmany )
{
int arg, i, j, sum , pop , argstart, npop , npop2, pop2 ;
double migr, mij, psize, palpha ;
//struct params p;
void addtoelist( struct devent *pt, struct devent *elist );
void argcheck( int arg, int argc, char ** ), commandlineseed( char ** ) ;
void free_eventlist( struct devent *pt, int npop );
struct devent *ptemp , *pt ;
FILE *pf ;
char ch3 ;
if( count == 0 ) {
if( argc < 4 ){ fprintf(stderr,"Too few command line arguments\n"); usage();}
pars.cp.nsam = atoi( argv[1] );
if( pars.cp.nsam <= 0 ) { fprintf(stderr,"First argument error. nsam <= 0. \n"); usage();}
*phowmany = atoi( argv[2] );
if( *phowmany <= 0 ) { fprintf(stderr,"Second argument error. howmany <= 0. \n"); usage();}
pars.commandlineseedflag = 0 ;
pars.cp.r = pars.mp.theta = pars.cp.f = 0.0 ;
pars.cp.track_len = 0. ;
pars.cp.npop = npop = 1 ;
pars.cp.mig_mat = (double **)malloc( (unsigned) sizeof( double *) );
pars.cp.mig_mat[0] = (double *)malloc( (unsigned)sizeof(double *));
pars.cp.mig_mat[0][0] = 0.0 ;
pars.mp.segsitesin = 0 ;
pars.mp.treeflag = 0 ;
pars.mp.mfreq = 1 ;
pars.cp.config = (int *) malloc( (unsigned)(( pars.cp.npop +1 ) *sizeof( int)) );
(pars.cp.config)[0] = pars.cp.nsam ;
pars.cp.size= (double *) malloc( (unsigned)( pars.cp.npop *sizeof( double )) );
(pars.cp.size)[0] = 1.0 ;
pars.cp.alphag = (double *) malloc( (unsigned)(( pars.cp.npop ) *sizeof( double )) );
(pars.cp.alphag)[0] = 0.0 ;
pars.cp.nsites = 2 ;
}
else{
npop = pars.cp.npop ;
free_eventlist( pars.cp.deventlist, npop );
}
pars.cp.deventlist = NULL ;
/* Eric's stuff for hotspots and ascertainment -- initializations */
gNumHotSpots = 0;
//gHotSpots = NULL;
//gHSRates = NULL;
gHSRates = NULL;
gHotSpotStart = NULL;
gHotSpotEnd = NULL;
gNumHotSpotsGC = 0;
gHSRatesGC = NULL;
gHotSpotStartGC = NULL;
gHotSpotEndGC = NULL;
rs.variablethetaflag=0;
arg = 3 ;
while( arg < argc ){
//printf(" Tu cadenita %c", argv[arg][0]);
if( argv[arg][0] != '-' ) { fprintf(stderr," argument should be -%s ?\n", argv[arg]); usage();}
switch ( argv[arg][1] ){
case 'f' :
if( ntbs > 0 ) { fprintf(stderr," can't use tbs args and -f option.\n"); exit(1); }
arg++;
argcheck( arg, argc, argv);
pf = fopen( argv[arg], "r" ) ;
if( pf == NULL ) {fprintf(stderr," no parameter file %s\n", argv[arg] ); exit(0);}
arg++;
argc++ ;
argv = (char **)malloc( (unsigned)(argc+1)*sizeof( char *) ) ;
argv[arg] = (char *)malloc( (unsigned)(20*sizeof( char )) ) ;
argstart = arg ;
while( fscanf(pf," %s", argv[arg]) != EOF ) {
arg++;
argc++;
argv = (char **)realloc( argv, (unsigned)argc*sizeof( char*) ) ;
argv[arg] = (char *)malloc( (unsigned)(20*sizeof( char )) ) ;
}
fclose(pf);
argc--;
arg = argstart ;
break;
/*My piece of code*/
case 'Q' :
rs.rejectionflag = 1 ;
arg++;
break;
case 'W' :
arg++;
argcheck( arg, argc, argv);
rs.thetavaluesnum = atoi( argv[arg++] );
rs.thetavalues = (float *)malloc (rs.thetavaluesnum*sizeof(float));
for (i=0;i<rs.thetavaluesnum;i++){
argcheck( arg, argc, argv);
*(rs.thetavalues+i) = atof (argv[arg++] );
}
rs.variablethetaflag =1;
break;
case 'z' :
arg++;
argcheck( arg, argc, argv);
pars.cp.r = 0;
pars.cp.nsites = atoi( argv[arg++]);
rs.micronumber = pars.cp.nsites;
pars.cp.nsites = pars.cp.nsites*2 + (pars.cp.nsites - 1)*2;
if( pars.cp.nsites <1 ){
fprintf(stderr,"with -z option must specify both rec_rate and nsites>1\n");
usage();
}
//printf("numero de microsatelites = %i\n",rs.micronumber);
/*End of my part of the code*/
break;
case 'a' :
arg++;
argcheck( arg, argc, argv);
rs.alpha = atof( argv[arg++]);
break;
case 'y' :
arg++;
argcheck( arg, argc, argv);
rs.tauthreshold = atof( argv[arg++]);
rs.tauflag = 1;
break;
case 'Y' :
arg++;
argcheck( arg, argc, argv);
rs.tauthresholdmin = atof( argv[arg++]);
rs.tauthresholdmax = atof( argv[arg++]);
rs.tauflagmin = 1;
break;
case 'A' :
arg++;
argcheck( arg, argc, argv);
rs.readacceptances = atoi( argv[arg++]);
rs.acceptancesflag = 1;
break;
case 'R' :
arg++;
rs.varianceflag= 1;
break;
case 'H' :
arg++;
rs.heteroflag= 1;
break;
case 'C' :
arg++;
rs.configflag= 1;
break;
case 'P' :
arg++;
rs.piflag= 1;
break;
case 'O' :
arg++;
rs.goodnessflag= 1;
break;
case 'Z' :
arg++;
rs.sitesflag= 1;
break;
case 'l' :
arg++;
rs.singletonflag= 1;
break;
case 'U' :
arg++;
rs.msitesflag= 1;
break;
case 'h' :
arg++;
rs.heterohapflag= 1;
break;
case 'u' :
arg++;
rs.configmicmeanflag= 1;
break;
case '0' :
arg++;
rs.heteroISflag= 1;
break;
case '1' :
arg++;
rs.conISflag= 1;
break;
case '2' :
arg++;
rs.piISflag= 1;
break;
case '4' :
arg++;
rs.sitesISflag= 1;
break;
case '5' :
arg++;
rs.sitesvarIS= 1;
break;
case '6' :
arg++;
rs.singletonISflag= 1;
break;
case '7' :
arg++;
rs.heterohapISflag= 1;
break;
case '8' :
arg++;
rs.configmicvarISflag= 1;
break;
case '9' :
arg++;
rs.varISflag= 1;
break;
case 'K' :
arg++;
/*char *microdata;
microdata = malloc(100*sizeof(char));
strcpy(microdata,argv[arg]);
if( strlen(microdata) == 0 ) {fprintf(stderr," missing argument after -K\n" ); exit(0);}
fprintf(stderr,"%s",microdata);*/
arg++;
break;
case 'k' :
arg++;
/*ISdata = malloc(100*sizeof(char));
strcpy(ISdata,argv[arg]);
if( strlen(ISdata) == 0 ) {fprintf(stderr," missing argument after -K\n" ); exit(0);}
fprintf(stderr,"%s",ISdata);*/
arg++;
break;
/*End of my piece of code*/
case 'r' :
arg++;
argcheck( arg, argc, argv);
pars.cp.r = atof( argv[arg++] );
argcheck( arg, argc, argv);
pars.cp.nsites = atoi( argv[arg++]);
if( pars.cp.nsites <2 ){
fprintf(stderr,"with -r option must specify both rec_rate and nsites>1\n");
usage();
}
break;
case 'c' :
arg++;
argcheck( arg, argc, argv);
pars.cp.f = atof( argv[arg++] );
argcheck( arg, argc, argv);
pars.cp.track_len = atof( argv[arg++]);
if( pars.cp.track_len <1. ){
fprintf(stderr,"with -c option must specify both f and track_len>0\n");
usage();
}
break;
case 't' :
arg++;
argcheck( arg, argc, argv);
pars.mp.theta = atof( argv[arg++] );
break;
case 'F' :
arg++;
argcheck( arg, argc, argv);
pars.mp.mfreq = atoi( argv[arg++] );
if( (pars.mp.mfreq < 2 ) || (pars.mp.mfreq > pars.cp.nsam/2 ) ){
fprintf(stderr," mfreq must be >= 2 and <= nsam/2.\n");
usage();
}
break;
case 'T' :
pars.mp.treeflag = 1 ;
arg++;
break;
case 'I' :
arg++;
if( count == 0 ) {
argcheck( arg, argc, argv);
pars.cp.npop = atoi( argv[arg]);
pars.cp.config = (int *) realloc( pars.cp.config, (unsigned)( pars.cp.npop*sizeof( int)));
npop = pars.cp.npop ;
}
arg++;
for( i=0; i< pars.cp.npop; i++) {
argcheck( arg, argc, argv);
pars.cp.config[i] = atoi( argv[arg++]);
}
if( count == 0 ){
pars.cp.mig_mat = (double **)realloc(pars.cp.mig_mat, (unsigned)(pars.cp.npop*sizeof(double *) )) ;
for(i=0; i<pars.cp.npop; i++) pars.cp.mig_mat[i] = (double *)realloc(pars.cp.mig_mat[i],
(unsigned)( pars.cp.npop*sizeof(double)));
pars.cp.size = (double *) realloc( pars.cp.size, (unsigned)( pars.cp.npop*sizeof( double )));
pars.cp.alphag = (double *) realloc( pars.cp.alphag, (unsigned)( pars.cp.npop*sizeof( double )));
}
for( i=1; i< pars.cp.npop ; i++) {
(pars.cp.size)[i] = (pars.cp.size)[0] ;
(pars.cp.alphag)[i] = (pars.cp.alphag)[0] ;
}
if( (arg <argc) && ( argv[arg][0] != '-' ) ) {
argcheck( arg, argc, argv);
migr = atof( argv[arg++] );
}
else migr = 0.0 ;
for( i=0; i<pars.cp.npop; i++)
for( j=0; j<pars.cp.npop; j++) pars.cp.mig_mat[i][j] = migr/(pars.cp.npop-1) ;
for( i=0; i< pars.cp.npop; i++) pars.cp.mig_mat[i][i] = migr ;
break;
case 'm' :
if( npop < 2 ) { fprintf(stderr,"Must use -I option first.\n"); usage();}
if( argv[arg][2] == 'a' ) {
arg++;
for( pop = 0; pop <npop; pop++)
for( pop2 = 0; pop2 <npop; pop2++){
argcheck( arg, argc, argv);
pars.cp.mig_mat[pop][pop2]= atof( argv[arg++] ) ;
}
for( pop = 0; pop < npop; pop++) {
pars.cp.mig_mat[pop][pop] = 0.0 ;
for( pop2 = 0; pop2 < npop; pop2++){
if( pop2 != pop ) pars.cp.mig_mat[pop][pop] += pars.cp.mig_mat[pop][pop2] ;
}
}
}
else {
arg++;
argcheck( arg, argc, argv);
i = atoi( argv[arg++] ) -1;
argcheck( arg, argc, argv);
j = atoi( argv[arg++] ) -1;
argcheck( arg, argc, argv);
mij = atof( argv[arg++] );
pars.cp.mig_mat[i][i] += mij - pars.cp.mig_mat[i][j] ;
pars.cp.mig_mat[i][j] = mij;
}
break;
case 'v' : /* case added by Eric Anderson to allow specification of recombinational
hotspots of different intensities */
arg++;
argcheck( arg, argc, argv);
gNumHotSpots = atoi(argv[arg++]);
gHotSpotStart = (int *)calloc((size_t)gNumHotSpots, sizeof(int));
gHotSpotEnd = (int *)calloc((size_t)gNumHotSpots, sizeof(int));
gHSRates = (double *)calloc((size_t)gNumHotSpots, sizeof(double));
for (i = 0; i<gNumHotSpots; i++)
{
argcheck( arg, argc, argv);
gHotSpotStart[i] = atoi(argv[arg++]);
gHotSpotStart[i] = gHotSpotStart[i]-1;
argcheck( arg, argc, argv);
gHotSpotEnd[i] = atoi(argv[arg++]);
gHotSpotEnd[i] = gHotSpotEnd[i]-1;
argcheck( arg, argc, argv);
gHSRates[i] = atof(argv[arg++]);
//printf("\n\n%d\n\n",p.cp.nsites);
if ((gHotSpotStart[i] < 0) || (gHotSpotEnd[i] >= pars.cp.nsites))
{
fprintf(stderr,"\n\n At least one crossover hotspot is not contained within the sequence. Exiting....\n\n");
usage();
}
if(i>0 && gHotSpotStart[i]<=gHotSpotEnd[i-1])
{
fprintf(stderr,"\n\nHot spots overlapping or not listed in order. Abort!...\n\n");
usage();
}
if(gHotSpotStart[i] >= gHotSpotEnd[i])
{
fprintf(stderr,"\n\nHotspot locations entered incorrectly.\n\n");
usage();
}
}
break;
case 'V' : /* case added by GRH to allow specification of a single gene conversion hotspot of specified intensity in specified area*/
arg++;
argcheck( arg, argc, argv);
gNumHotSpotsGC = atoi(argv[arg++]);
gHotSpotStartGC = (int *)calloc((size_t)gNumHotSpotsGC, sizeof(int));
gHotSpotEndGC = (int *)calloc((size_t)gNumHotSpotsGC, sizeof(int));
gHSRatesGC = (double *)calloc((size_t)gNumHotSpotsGC, sizeof(double));
for (i = 0; i<gNumHotSpotsGC; i++)
{
argcheck( arg, argc, argv);
gHotSpotStartGC[i] = atoi(argv[arg++]);
gHotSpotStartGC[i] = gHotSpotStartGC[i]-1;
argcheck( arg, argc, argv);
gHotSpotEndGC[i] = atoi(argv[arg++]);
gHotSpotEndGC[i] = gHotSpotEndGC[i]-1;
argcheck( arg, argc, argv);
gHSRatesGC[i] = atof(argv[arg++]);
if ((gHotSpotStartGC[i] < 0) || (gHotSpotEndGC[i] >= pars.cp.nsites))
{
fprintf(stderr,"\n\n At least one gene conversion hotspot is not contained within the sequence. Exiting....\n\n");
usage();
}
if(i>0 && gHotSpotStartGC[i]<=gHotSpotEndGC[i-1])
{
fprintf(stderr,"\n\nGene Conv Hot spots overlapping or not listed in order. Abort!...\n\n");
usage();
}
if(gHotSpotStartGC[i] >= gHotSpotEndGC[i])
{
fprintf(stderr,"\n\nHotspot locations entered incorrectly.\n\n");
usage();
}
}
break;
case 'n' :
if( npop < 2 ) { fprintf(stderr,"Must use -I option first.\n"); usage();}
arg++;
argcheck( arg, argc, argv);
pop = atoi( argv[arg++] ) -1;
argcheck( arg, argc, argv);
psize = atof( argv[arg++] );
pars.cp.size[pop] = psize ;
break;
case 'g' :
if( npop < 2 ) { fprintf(stderr,"Must use -I option first.\n"); usage();}
arg++;
argcheck( arg, argc, argv);
pop = atoi( argv[arg++] ) -1;
if( arg >= argc ) { fprintf(stderr,"Not enough arg's after -G.\n"); usage(); }
palpha = atof( argv[arg++] );
pars.cp.alphag[pop] = palpha ;
break;
case 'G' :
arg++;
if( arg >= argc ) { fprintf(stderr,"Not enough arg's after -G.\n"); usage(); }
palpha = atof( argv[arg++] );
for( i=0; i<pars.cp.npop; i++)
pars.cp.alphag[i] = palpha ;
break;
case 's' :
arg++;
argcheck( arg, argc, argv);
if( argv[arg-1][2] == 'e' ){ /* command line seeds */
pars.commandlineseedflag = 1 ;
if( count == 0 ) commandlineseed(argv+arg );
arg += 3 ;
}
else {
pars.mp.segsitesin = atoi( argv[arg++] );
}
break;
case 'e' :
pt = (struct devent *)malloc( sizeof( struct devent) ) ;
pt->detype = argv[arg][2] ;
ch3 = argv[arg][3] ;
arg++;
argcheck( arg, argc, argv);
pt->time = atof( argv[arg++] ) ;
pt->nextde = NULL ;
if( pars.cp.deventlist == NULL )
pars.cp.deventlist = pt ;
else if ( pt->time < pars.cp.deventlist->time ) {
ptemp = pars.cp.deventlist ;
pars.cp.deventlist = pt ;
pt->nextde = ptemp ;
}
else
addtoelist( pt, pars.cp.deventlist ) ;
switch( pt->detype ) {
case 'N' :
argcheck( arg, argc, argv);
pt->paramv = atof( argv[arg++] ) ;
break;
case 'G' :
if( arg >= argc ) { fprintf(stderr,"Not enough arg's after -eG.\n"); usage(); }
pt->paramv = atof( argv[arg++] ) ;
break;
case 'M' :
argcheck( arg, argc, argv);
pt->paramv = atof( argv[arg++] ) ;
break;
case 'n' :
argcheck( arg, argc, argv);
pt->popi = atoi( argv[arg++] ) -1 ;
argcheck( arg, argc, argv);
pt->paramv = atof( argv[arg++] ) ;
break;
case 'g' :
argcheck( arg, argc, argv);
pt->popi = atoi( argv[arg++] ) -1 ;
if( arg >= argc ) { fprintf(stderr,"Not enough arg's after -eg.\n"); usage(); }
pt->paramv = atof( argv[arg++] ) ;
break;
case 's' :
argcheck( arg, argc, argv);
pt->popi = atoi( argv[arg++] ) -1 ;
argcheck( arg, argc, argv);
pt->paramv = atof( argv[arg++] ) ;
break;
case 'm' :
if( ch3 == 'a' ) {
pt->detype = 'a' ;
argcheck( arg, argc, argv);
npop2 = atoi( argv[arg++] ) ;
pt->mat = (double **)malloc( (unsigned)npop2*sizeof( double *) ) ;
for( pop =0; pop <npop2; pop++){
(pt->mat)[pop] = (double *)malloc( (unsigned)npop2*sizeof( double) );
for( i=0; i<npop2; i++){
if( i == pop ) arg++;
else {
argcheck( arg, argc, argv);
(pt->mat)[pop][i] = atof( argv[arg++] ) ;
}
}
}
for( pop = 0; pop < npop2; pop++) {
(pt->mat)[pop][pop] = 0.0 ;
for( pop2 = 0; pop2 < npop2; pop2++){
if( pop2 != pop ) (pt->mat)[pop][pop] += (pt->mat)[pop][pop2] ;
}
}
}
else {
argcheck( arg, argc, argv);
pt->popi = atoi( argv[arg++] ) -1 ;
argcheck( arg, argc, argv);
pt->popj = atoi( argv[arg++] ) -1 ;
argcheck( arg, argc, argv);
pt->paramv = atof( argv[arg++] ) ;
}
break;
case 'j' :
argcheck( arg, argc, argv);
pt->popi = atoi( argv[arg++] ) -1 ;
argcheck( arg, argc, argv);
pt->popj = atoi( argv[arg++] ) -1 ;
break;
default: fprintf(stderr,"e event\n"); usage();
}
break;
default: fprintf(stderr," option default\n"); usage() ;
}
}
/*I add something at the end*/
if( (pars.mp.theta == 0.0) && ( pars.mp.segsitesin == 0 ) && ( pars.mp.treeflag == 0 ) && (rs.variablethetaflag == 0) ) {
fprintf(stderr," either -s or -t or -T option must be used. \n");
usage();
exit(1);
}
sum = 0 ;
for( i=0; i< pars.cp.npop; i++) sum += (pars.cp.config)[i] ;
if( sum != pars.cp.nsam ) {
fprintf(stderr," sum sample sizes != nsam\n");
usage();
exit(1);
}
}
void
argcheck( int arg, int argc, char *argv[] )
{
if( (arg >= argc ) || ( argv[arg][0] == '-') ) {
fprintf(stderr,"not enough arguments after %s\n", argv[arg-1] ) ;
fprintf(stderr,"For usage type: ms<return>\n");
exit(0);
}
}
int
usage()
{
fprintf(stderr,"usage: ms nsam howmany \n");
fprintf(stderr," Options: \n");
fprintf(stderr,"\t -t theta (this option and/or the next must be used. Theta = 4*N0*u )\n");
fprintf(stderr,"\t -s segsites ( fixed number of segregating sites)\n");
fprintf(stderr,"\t -T (Output gene tree.)\n");
fprintf(stderr,"\t -F minfreq Output only sites with freq of minor allele >= minfreq.\n");
fprintf(stderr,"\t -r rho nsites (rho here is 4Nc)\n");
fprintf(stderr,"\t\t -c f track_len (f = ratio of conversion rate to rec rate. tracklen is mean length.) \n");
fprintf(stderr,"\t\t\t if rho = 0., f = 4*N0*g, with g the gene conversion rate.\n");
fprintf(stderr,"\t -G alpha ( N(t) = N0*exp(-alpha*t) . alpha = -log(Np/Nr)/t\n");
fprintf(stderr,"\t -I npop n1 n2 ... [mig_rate] (all elements of mig matrix set to mig_rate/(npop-1) \n");
fprintf(stderr,"\t\t -m i j m_ij (i,j-th element of mig matrix set to m_ij.)\n");
fprintf(stderr,"\t\t -ma m_11 m_12 m_13 m_21 m_22 m_23 ...(Assign values to elements of migration matrix.)\n");
fprintf(stderr,"\t\t -n i size_i (popi has size set to size_i*N0 \n");
fprintf(stderr,"\t\t -g i alpha_i (If used must appear after -M option.)\n");
fprintf(stderr,"\t The following options modify parameters at the time 't' specified as the first argument:\n");
fprintf(stderr,"\t -eG t alpha (Modify growth rate of all pop's.)\n");
fprintf(stderr,"\t -eg t i alpha_i (Modify growth rate of pop i.) \n");
fprintf(stderr,"\t -eM t mig_rate (Modify the mig matrix so all elements are mig_rate/(npop-1)\n");
fprintf(stderr,"\t -em t i j m_ij (i,j-th element of mig matrix set to m_ij at time t )\n");
fprintf(stderr,"\t -ema t npop m_11 m_12 m_13 m_21 m_22 m_23 ...(Assign values to elements of migration matrix.)\n");
fprintf(stderr,"\t -eN t size (Modify pop sizes. New sizes = size*N0 ) \n");
fprintf(stderr,"\t -en t i size_i (Modify pop size of pop i. New size of popi = size_i*N0 .)\n");
fprintf(stderr,"\t -es t i proportion (Split: pop i -> pop-i + pop-npop, npop increases by 1.\n");
fprintf(stderr,"\t\t proportion is probability that each lineage stays in pop-i. (p, 1-p are admixt. proport.\n");
fprintf(stderr,"\t\t Size of pop npop is set to N0 and alpha = 0.0 , size and alpha of pop i are unchanged.\n");
fprintf(stderr,"\t -ej t i j ( Join lineages in pop i and pop j into pop j\n");
fprintf(stderr,"\t\t size, alpha and M are unchanged.\n");
fprintf(stderr,"\t -v J a_1 b_1 I_1 ... a_J b_J I_J ( Incorporate J crossover hotspots, each of intensity I_j on [a_j,b_j] )\n");
fprintf(stderr,"\t -V K a_1 b_1 I_1 ... a_K b_K I_K ( Incorporate K gene conversion hotspots, each of intensity I_k on [a_k,b_k] )\n");
fprintf(stderr,"\t -f filename ( Read command line arguments from file filename.)\n");
fprintf(stderr," See msdoc.pdf for explanation of these parameters.\n");
exit(1);
}
void
addtoelist( struct devent *pt, struct devent *elist )
{
struct devent *plast, *pevent, *ptemp ;
pevent = elist ;
while( (pevent != NULL ) && ( pevent->time <= pt->time ) ) {
plast = pevent ;
pevent = pevent->nextde ;
}
ptemp = plast->nextde ;
plast->nextde = pt ;
pt->nextde = ptemp ;
}
void
free_eventlist( struct devent *pt, int npop )
{
struct devent *next ;
int pop ;
while( pt != NULL){
next = pt->nextde ;
if( pt->detype == 'a' ) {
for( pop = 0; pop < npop; pop++) free( (pt->mat)[pop] );
free( pt->mat );
}
free(pt);
pt = next ;
}
}
/************ make_gametes.c *******************************************
*
*
*****************************************************************************/
#define STATE1 '1'
#define STATE2 '0'
int
make_gametes(int nsam, int mfreq, struct node *ptree, double tt, int newsites, int ns, char **list )
{
int tip, j, node ;
int pickb(int nsam, struct node *ptree, double tt),
pickbmf(int nsam, int mfreq, struct node *ptree, double tt) ;
for( j=ns; j< ns+newsites ; j++ ) {
if( mfreq == 1 ) node = pickb( nsam, ptree, tt);
else node = pickbmf( nsam, mfreq, ptree, tt);
for( tip=0; tip < nsam ; tip++) {
if( tdesn(ptree, tip, node) ) list[tip][j] = STATE1 ;
else list[tip][j] = STATE2 ;
}
}
}
/*** ttime.c : Returns the total time in the tree, *ptree, with nsam tips. **/
double
ttime( ptree, nsam)
struct node *ptree;
int nsam;
{
double t;
int i;
t = (ptree + 2*nsam-2) -> time ;
for( i=nsam; i< 2*nsam-1 ; i++)
t += (ptree + i)-> time ;
return(t);
}
double
ttimemf( ptree, nsam, mfreq)
struct node *ptree;
int nsam, mfreq;
{
double t;
int i;
t = 0. ;
for( i=0; i< 2*nsam-2 ; i++)
if( ( (ptree+i)->ndes >= mfreq ) && ( (ptree+i)->ndes <= nsam-mfreq) )
t += (ptree + (ptree+i)->abv )->time - (ptree+i)->time ;
return(t);
}
void
prtree( ptree, nsam)
struct node *ptree;
int nsam;
{
double t;
int i, *descl, *descr ;
void parens( struct node *ptree, int *descl, int *descr, int noden );
descl = (int *)malloc( (unsigned)(2*nsam-1)*sizeof( int) );
descr = (int *)malloc( (unsigned)(2*nsam-1)*sizeof( int) );
for( i=0; i<2*nsam-1; i++) descl[i] = descr[i] = -1 ;
for( i = 0; i< 2*nsam-2; i++){
if( descl[ (ptree+i)->abv ] == -1 ) descl[(ptree+i)->abv] = i ;
else descr[ (ptree+i)->abv] = i ;
}
parens( ptree, descl, descr, 2*nsam-2);
free( descl ) ;
free( descr ) ;
}
void
parens( struct node *ptree, int *descl, int *descr, int noden)
{
double time ;
if( descl[noden] == -1 ) {
printf("%d:%5.3lf", noden+1, (ptree+ ((ptree+noden)->abv))->time );
}
else{
printf("(");
parens( ptree, descl,descr, descl[noden] ) ;
printf(",");
parens(ptree, descl, descr, descr[noden] ) ;
if( (ptree+noden)->abv == 0 ){printf(");\n"); }
else {
time = (ptree + (ptree+noden)->abv )->time - (ptree+noden)->time ;
printf("):%5.3lf", time );
}
}
}
/*** pickb : returns a random branch from the tree. The probability of picking
a particular branch is proportional to its duration. tt is total
time in tree. ****/
int
pickb(nsam, ptree, tt)
int nsam;
struct node *ptree;
double tt;
{
double x, y, ran1();
int i;
x = ran1()*tt;
for( i=0, y=0; i < 2*nsam-2 ; i++) {
y += (ptree + (ptree+i)->abv )->time - (ptree+i)->time ;
if( y >= x ) return( i ) ;
}
return( i );
}
int
pickbmf(nsam, mfreq, ptree, tt )
int nsam, mfreq;
struct node *ptree;
double tt;
{
double x, y, ran1();
int i;
x = ran1()*tt;
for( i=0, y=0; i < 2*nsam-2 ; i++) {
if( ( (ptree+i)->ndes >= mfreq ) && ( (ptree+i)->ndes <= nsam-mfreq) )
y += (ptree + (ptree+i)->abv )->time - (ptree+i)->time ;
if( y >= x ) return( i ) ;
}
return( i );
}
/**** tdesn : returns 1 if tip is a descendant of node in *ptree, otherwise 0. **/
int
tdesn(ptree, tip, node )
struct node *ptree;
int tip, node;
{
int k;
for( k= tip ; k < node ; k = (ptree+k)->abv ) ;
if( k==node ) return(1);
else return(0);
}
/* pick2() */
int
pick2(n,i,j)
int n, *i, *j;
{
double ran1();
*i = n * ran1() ;
while( ( *j = n * ran1() ) == *i )
;
return(0) ;
}
/**** ordran.c ***/
int
ordran(n,pbuf)
int n;
double pbuf[];
{
ranvec(n,pbuf);
order(n,pbuf);
return;
}
int
mnmial(n,nclass,p,rv)
int n, nclass, rv[];
double p[];
{
double ran1();
double x, s;
int i, j;
for(i=0; i<nclass; i++) rv[i]=0;
for(i=0; i<n ; i++) {
x = ran1();
j=0;
s = p[0];
while( (x > s) && ( j<(nclass-1) ) ) s += p[++j];
rv[j]++;
}
return(j);
}
int
order(n,pbuf)
int n;
double pbuf[];
{
int gap, i, j;
double temp;
for( gap= n/2; gap>0; gap /= 2)
for( i=gap; i<n; i++)
for( j=i-gap; j>=0 && pbuf[j]>pbuf[j+gap]; j -=gap) {
temp = pbuf[j];
pbuf[j] = pbuf[j+gap];
pbuf[j+gap] = temp;
}
}
int
ranvec(n,pbuf)
int n;
double pbuf[];
{
int i;
double ran1();
for(i=0; i<n; i++)
pbuf[i] = ran1();
return;
}
int
poisso(u)
double u;
{
double cump, ru, ran1(), p, gasdev() ;
int i=1;
if( u > 30. ) return( (int)(0.5 + gasdev(u,u)) );
ru = ran1();
p = exp(-u);
if( ru < p) return(0);
cump = p;
while( ru > ( cump += (p *= u/i ) ) )
i++;
return(i);
}
/* a slight modification of crecipes version */
double gasdev(m,v)
double m, v;
{
static int iset=0;
static float gset;
float fac,r,v1,v2;
double ran1();
if (iset == 0) {
do {
v1=2.0*ran1()-1.0;
v2=2.0*ran1()-1.0;
r=v1*v1+v2*v2;
} while (r >= 1.0);
fac=sqrt(-2.0*log(r)/r);
gset= v1*fac;
iset=1;
return( m + sqrt(v)*v2*fac);
} else {
iset=0;
return( m + sqrt(v)*gset ) ;
}
}
/*I have added this functions*/
double
tajd(int nsam, int segsites, double sumk)
{
double a1, a2, b1, b2, c1, c2, e1, e2;
if( segsites == 0 ) return( 0.0) ;
a1 = a1f(nsam);
a2 = a2f(nsam);
b1 = b1f(nsam);
b2 = b2f(nsam);
c1 = c1f(a1, b1);
c2 = c2f(nsam, a1, a2, b2);
e1 = e1f(a1, c1);
e2 = e2f(a1, a2, c2);
return( (sumk - (segsites/a1))/sqrt((e1*segsites) + ((e2*segsites)*(segsites
-1))) ) ;
}
double a1f(int nsam)
{
double a1;
int i;
a1 = 0.0;
for (i=1; i<=nsam-1; i++) a1 += 1.0/i;
return (a1);
}
double a2f(int nsam)
{
double a2;
int i;
a2 = 0.0;
for (i=1; i<=nsam-1; i++) a2 += 1.0/(i*i);
return (a2);
}
double b1f(int nsam)
{
double b1;
b1 = (nsam + 1.0)/(3.0*(nsam-1.0));
return (b1);
}
double b2f(int nsam)
{
double b2;
b2 = (2*(nsam*nsam + nsam + 3.0))/(9*nsam*(nsam - 1));
return (b2);
}
double e1f(double a1, double c1)
{
double e1;
e1 = c1/a1;
return (e1);
}
double e2f(double a1, double a2, double c2)
{
double e2;
e2 = c2/((a1*a1)+a2);
return (e2);
}
double c1f(double a1, double b1)
{
double c1;
c1 = b1 - (1/a1);
return (c1);
}
double c2f(int nsam, double a1, double a2, double b2)
{
double c2;
c2 = b2 - ((nsam+2)/(a1*nsam)) + (a2/(a1 * a1));
return (c2);
}
double
nucdiv( int nsam, int mnumber, int** list)
{
//printf("nsam = %i mnumber = %i\n",nsam,mnumber);
double pi, p1, nd, nnm1 ;
int co1,co2,s , counter;
pi = 0.0;
rs.maxsize= malloc(mnumber*sizeof(int));
rs.minsize= malloc(mnumber*sizeof(int));
rs.segtajd =0;
for(s = 0; s <mnumber; s++){
*(rs.maxsize +s) = *(*( list+0)+s);
*(rs.minsize +s) = *(*( list+0)+s);
for (co1 =0; co1<nsam;co1++){
if( *(*( list+co1)+s)> *(rs.maxsize +s)){
*(rs.maxsize +s) = *(*( list+co1)+s);
}
if( *(*( list+co1)+s)< *(rs.minsize +s)){
*(rs.minsize +s) = *(*( list+co1)+s);
}
for(co2 = co1;co2 <nsam ; co2++){
if(*(*( list+co1)+s) > *(*( list+co2)+s)){
pi = pi + (*(*( list+co1)+s) - *(*( list+co2)+s));
} else if (*(*( list+co1)+s) < *(*( list+co2)+s)){
pi = pi + (*(*( list+co2)+s) - *(*( list+co1)+s));
}
}
}
rs.segtajd = rs.segtajd + (*(rs.maxsize +s) - *(rs.minsize +s));
//printf("part rs.segtajd = %i",rs.segtajd);
//printf ("pi = %f micro = %i\n",pi,s);
}
//printf("int = %i\n",s);
//printf ("pi = %f\n",pi);
pi = pi/((nsam*(nsam-1))/2);
//printf ("pi = %f seg = %i\n",pi,rs.segtajd);
return( pi ) ;
}
/* thetah - pi */
double
hfay( int nsam, int segsites, char **list)
{
int s, frequency( char, int, int, char**);
double pi, p1, nd, nnm1 ;
pi = 0.0 ;
nd = nsam;
nnm1 = nd/(nd-1.0) ;
for( s = 0; s <segsites; s++){
p1 = frequency('1', s,nsam,list)/nd ;
pi += 2.0*p1*(2.*p1 - 1.0 )*nnm1 ;
}
return( -pi ) ;
}
/* Fay's theta_H */
double
thetah( int nsam, int segsites, char **list)
{
int s, frequency( char, int, int, char**);
double pi, p1, nd, nnm1 ;
pi = 0.0 ;
nd = nsam;
nnm1 = nd/(nd-1.0) ;
for( s = 0; s <segsites; s++){
p1 = frequency('1', s,nsam,list) ;
pi += p1*p1 ;
}
return( pi*2.0/( nd*(nd-1.0) ) ) ;
}
int
frequency( char allele,int site,int nsam, char **list)
{
int i, count=0;
for( i=0; i<nsam; i++) count += ( list[i][site] == allele ? 1: 0 ) ;
return( count);
}
int
segsub( int nsub, int segsites, char **list )
{
int i, count = 0 , c1 ;
int frequency( char, int, int, char**) ;
for(i=0; i < segsites ; i++){
c1 = frequency('1',i,nsub, list);
if( ( c1 > 0 ) && ( c1 <nsub ) ) count++;
}
return( count ) ;
}
float heterozygosis(int **size,int mnumber, int secnumber){
int i, j, k;
rs.microflag = NULL;
rs.heterozygosis = NULL;
rs.microflag = malloc(secnumber * sizeof(int));
rs.heterozygosis = malloc(mnumber * sizeof(float));
for (i=0;i<mnumber;i++){
*(rs.heterozygosis + i) = 0;
}
rs.heterozygosismean =0;
for (i=0;i<mnumber;i++){
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
for (k=0;k<secnumber;k++){
rs.homopart = 1./secnumber;
if(*(rs.microflag + k) ==0){
for (j=k+1;j<secnumber;j++){
if(*(*(size + k)+i) == *(*(size + j)+i)){
rs.homopart = rs.homopart + (1./secnumber);
*(rs.microflag + j) = 1;
}
}
*(rs.heterozygosis + i) = *(rs.heterozygosis + i) + rs.homopart * rs.homopart;
}
}
*(rs.heterozygosis + i) = 1- *(rs.heterozygosis + i);
*(rs.heterozygosis + i) = ((*(rs.heterozygosis + i))/(secnumber -1))*secnumber;
rs.heterozygosismean = rs.heterozygosismean + *(rs.heterozygosis + i);
}
rs.heterozygosismean = rs.heterozygosismean/mnumber;
free(rs.microflag);
free(rs.heterozygosis);
return (rs.heterozygosismean);
}
float variancemean (int **size,int mnumber, int secnumber){
int i, k;
rs.mean = NULL;
rs.mean = malloc (mnumber *sizeof(float));
for(i=0;i<mnumber;i++){
*(rs.mean + i) = 0;
for(k=0;k<secnumber;k++){
*(rs.mean + i) = *(rs.mean + i) + *(*(size +k)+i);
}
*(rs.mean + i) = (*(rs.mean + i))/secnumber;
}
//printf("\nLas medias\n");
for(i=0;i<mnumber;i++){
//printf("%f ",*(rs.mean + i));
}
rs.variance = NULL;
rs.variance = malloc(mnumber *sizeof(float));
for(i=0;i<mnumber;i++){
rs.sum = 0;
rs.squaresum = 0;
for(k=0;k<secnumber;k++){
rs.sum = rs.sum + *(*(size +k)+i);
rs.squaresum = rs.squaresum + (*(*(size +k)+i) * *(*(size +k)+i));
}
*(rs.variance + i) = (rs.squaresum -((rs.sum*rs.sum)/secnumber))/(secnumber - 1);
}
//printf("\nLas varianzas\n");
rs.rejectionvariance = 0;
for(i=0;i<mnumber;i++){
//printf("%f ", *(rs.variance + i));
rs.rejectionvariance = *(rs.variance + i) + rs.rejectionvariance;
}
rs.rejectionvariance = rs.rejectionvariance/mnumber;
//printf("La media de tu rejection variance %f",rs.rejectionvariance);
free(rs.mean);
free(rs.variance);
return (rs.rejectionvariance);
}
int numberofconfigurations(int **size, int mnumber, int secnumber){
int i, j, k;
rs.microflag = NULL;
rs.microflag = malloc(secnumber * sizeof(int));
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
rs.numberconfigurations = secnumber;
for(i=0;i<secnumber;i++){
if(*(rs.microflag + i) == 0){
for(j=i+1;j<secnumber;j++){
rs.configflag =0;
for(k=0;k<mnumber;k++){
if(*(*(size + i)+k) != *(*(size + j)+k)){
rs.configflag = 1;
}
}
if(rs.configflag ==0){
*(rs.microflag + j) = 1;
rs.numberconfigurations = rs.numberconfigurations -1;
}
}
}
}
//fprintf(stderr,"\nTu nmero de configuraciones SMM es %i",rs.numberconfigurations);
//printf("%i\n",rs.numberconfigurations);
free(rs.microflag);
return (rs.numberconfigurations);
}
float Fst(int **size, int mnumber, int secnumber, int pop, int *conpop){
float totalheterozygosis, *subpopheterozygosis, subpopheterozygosisprom, Fst;
int i, j, k, l, **subpopmatrix, counterstart, counterend;
totalheterozygosis = heterozygosis(rs.datamicrosize, rs.micronumber, pars.cp.nsam);
subpopheterozygosis = NULL;
subpopheterozygosis = malloc (pop*sizeof (float));
counterstart = 0;
for (i=0; i<pop; i++){
subpopmatrix = malloc(*(conpop + i)*sizeof(int*));
subpopmatrix = NULL;
for(j=0;j<*(conpop + i);j++){
*(subpopmatrix +j) = NULL;
*(subpopmatrix +j) = malloc(mnumber*sizeof(int));
}
counterend = counterstart + *(conpop + i);
for (j= counterstart; j< counterend; j++){
for (k=0;k<mnumber;k++){
*(*(subpopmatrix+(j-counterstart))+k) =*(*(size+j)+k);
}
}
*(subpopheterozygosis + i ) = heterozygosis(subpopmatrix, rs.micronumber, *(conpop + i));
counterstart = counterstart + *(conpop + i);
}
subpopheterozygosisprom= 0;
for (i=0; i<pop; i++){
subpopheterozygosisprom = subpopheterozygosisprom + *(subpopheterozygosis + i );
}
subpopheterozygosisprom = subpopheterozygosisprom / pop;
Fst = (totalheterozygosis - subpopheterozygosisprom)/ totalheterozygosis;
return (Fst);
}
void mismatch(int **size, int mnumber, int secnumber){
int maximum = 0;
int *differencepairs = NULL;
//differencepairs = NULL;
differencepairs = malloc(((pars.cp.nsam*(pars.cp.nsam-1))/2)* sizeof(int));
int counter = 0, i, j, k;
rs.pairmaximum = 0;
for(j=0;j<pars.cp.nsam;j++){
for(k=j+1;k<pars.cp.nsam;k++){
*(differencepairs + counter)= 0;
for(i=0;i<rs.micronumber;i++){
if (*(*(size + j)+i) > *(*(size + k)+i)){
*(differencepairs + counter) = *(differencepairs + counter) + *(*(size + j)+i) - *(*(size + k)+i);
} else if (*(*(size + k)+i) > *(*(size + j)+i)){
*(differencepairs + counter) = *(differencepairs + counter) + *(*(size + k)+i) - *(*(size + j)+i);
}
}
if (*(differencepairs + counter)>rs.pairmaximum){
rs.pairmaximum = *(differencepairs + counter);
}
counter++;
}
}
//printf("Diferencias\n");
for (i=0;i<((pars.cp.nsam*(pars.cp.nsam-1))/2);i++){
//printf("%i\t",*(differencepairs+i));
}
//printf("\n");
//printf ("El counter = %i\n",counter);
/*for(i=0;i<((pars.cp.nsam*(pars.cp.nsam-1))/2);i++){
//printf("\ndif=%i",*(rs.differencepairs + i));
}*/
//free(differencepairs);
//float *rs.simmismatch = NULL;
rs.simmismatch = malloc((rs.pairmaximum + 1)* sizeof(float));
//printf("maximum = % i ",rs.pairmaximum);
//printf("pair maximum = %i\n",rs.pairmaximum);
//printf ("La mismatch de los datos:\n");
for(i=0;i<=rs.pairmaximum;i++){
*(rs.simmismatch + i ) = 0;
for(j=0;j<((pars.cp.nsam*(pars.cp.nsam-1))/2);j++){
if( *(differencepairs + j)==i){
*(rs.simmismatch + i ) = *(rs.simmismatch + i ) + 1;
//printf("%f",*(rs.frequencypairs + counter ));
}
}
*(rs.simmismatch + i ) = *(rs.simmismatch + i )/((pars.cp.nsam*(pars.cp.nsam-1))/2);
//printf ("%f ",*(rs.simmismatch + i ));
}
//printf("counter = %i", counter);
//printf("\n");
free(differencepairs);
//free (simmismatch);
}
float sizehomoplasyloc (int **size, int mnumber, int secnumber, char ***infinite){
int i, j, k;
rs.microflag = NULL;
rs.heterozygosis = NULL;
rs.microflag = malloc(secnumber * sizeof(int));
rs.heterozygosis = malloc(mnumber * sizeof(float));
rs.infinite_heterozygosis = malloc(mnumber * sizeof(float));
rs.homoplasyloc = malloc (mnumber * sizeof (float));
for (i=0;i<mnumber;i++){
*(rs.heterozygosis + i) = 0;
}
float heterozygosismean =0;
rs.denominatorsquare = NULL;
rs.denominatorsquare = malloc(mnumber * sizeof(float*));
for (i=0;i<mnumber;i++){
*(rs.denominatorsquare + i) = NULL;
*(rs.denominatorsquare + i) = malloc(secnumber*sizeof(float));
for (j=0;j<secnumber;j++){
*(*(rs.denominatorsquare + i)+j) = 0;
}
}
for (i=0;i<mnumber;i++){
rs.counterfreq=0;
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
for (k=0;k<secnumber;k++){
rs.homopart = 1./secnumber;
if(*(rs.microflag + k) ==0){
for (j=k+1;j<secnumber;j++){
if(*(*(size + k)+i) == *(*(size + j)+i)){
rs.homopart = rs.homopart + (1./secnumber);
*(rs.microflag + j) = 1;
}
}
*(*(rs.denominatorsquare + i) + rs.counterfreq) = rs.homopart;
rs.counterfreq++;
*(rs.heterozygosis + i) = *(rs.heterozygosis + i) + rs.homopart * rs.homopart;
}
}
*(rs.heterozygosis + i) = 1- *(rs.heterozygosis + i);
*(rs.heterozygosis + i) = ((*(rs.heterozygosis + i))/(secnumber -1))*secnumber;
heterozygosismean = heterozygosismean + *(rs.heterozygosis + i);
}
heterozygosismean = heterozygosismean/mnumber;
for (i=0;i<mnumber;i++){
*(rs.infinite_heterozygosis + i) = 0;
}
for (i=0;i<mnumber;i++){
for (j=0;j<secnumber;j++){
*(*(rs.denominatorsquare + i)+j) = 0;
}
}
for (i=0;i<mnumber;i++){
rs.counterfreq=0;
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
for (k=0;k<secnumber;k++){
rs.homopart = 1./secnumber;
if(*(rs.microflag + k) ==0){
for (j=k+1;j<secnumber;j++){
if((strcmp(*(*(rs.infinitesitepart + k)+i),*(*(rs.infinitesitepart + j)+i)))==0){
rs.homopart = rs.homopart + (1./secnumber);
*(rs.microflag + j) = 1;
}
}
*(*(rs.denominatorsquare + i) + rs.counterfreq) = rs.homopart;
rs.counterfreq++;
*(rs.infinite_heterozygosis + i) = *(rs.infinite_heterozygosis + i) + rs.homopart * rs.homopart;
}
}
*(rs.infinite_heterozygosis + i) = 1- *(rs.infinite_heterozygosis + i);
*(rs.infinite_heterozygosis + i) = ((*(rs.infinite_heterozygosis + i))/(secnumber -1))*secnumber;
//rs.heterozygosismean = rs.heterozygosismean + *(rs.heterozygosis + i);
}
rs.homoplasymeanloc = 0;
for (i=0;i<mnumber;i++){
*(rs.homoplasyloc + i) = 1-((1 - *(rs.infinite_heterozygosis + i))/(1-*(rs.heterozygosis + i)));
//printf("heterozygosis = %f con micro %i\n",*(rs.infinite_heterozygosis + i), i);
rs.homoplasymeanloc = rs.homoplasymeanloc + *(rs.homoplasyloc + i);
}
rs.homoplasymeanloc =rs.homoplasymeanloc/mnumber;
free(rs.microflag);
for (i=0;i<mnumber;i++){
free(*(rs.denominatorsquare + i));
}
free(rs.denominatorsquare);
free(rs.heterozygosis);
free(rs.infinite_heterozygosis);
free(rs.homoplasyloc);
return (rs.homoplasymeanloc);
}
float SASH (int **size, int mnumber, int secnumber, char ***infinite){
int i, j, k;
rs.microflag = NULL;
float ISheterozygosis = 0;
rs.microflag = malloc(secnumber * sizeof(int));
char *chain;
rs.microchain = malloc (secnumber*sizeof(char*));
for (i=0;i<secnumber;i++){
*(rs.microchain + i) = malloc((6*mnumber)*sizeof(char));
strcpy(*(rs.microchain + i),"");
}
for (i=0;i<secnumber;i++){
for (j=0;j<mnumber;j++){
chain = malloc (6*sizeof(char));
sprintf(chain,"%i",*(*(size+i)+j));
strcat(*(rs.microchain + i),chain);
free(chain);
}
}
float heterozygosismean = 0;
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
for (k=0;k<secnumber;k++){
rs.homopart = 1./secnumber;
if(*(rs.microflag + k) ==0){
for (j=k+1;j<secnumber;j++){
if((strcmp(*(rs.microchain + k),*(rs.microchain + j)))==0){
rs.homopart = rs.homopart + (1./secnumber);
*(rs.microflag + j) = 1;
}
}
heterozygosismean = heterozygosismean + rs.homopart * rs.homopart;
}
}
heterozygosismean = 1- heterozygosismean;
heterozygosismean = ((heterozygosismean)/(secnumber -1))*secnumber;
rs.ISchain = malloc(secnumber*sizeof(char*));
for (i=0;i<secnumber;i++){
*(rs.ISchain + i) = malloc((rs.segsites*mnumber)*sizeof(char));
strcpy(*(rs.ISchain + i),"");
}
for (i=0;i<secnumber;i++){
for (j=0;j<mnumber;j++){
chain = malloc (rs.segsites*sizeof(char));
sprintf(chain,"%s",*(*(infinite+i)+j));
strcat(*(rs.ISchain + i),*(*(infinite+i)+j));
free(chain);
}
}
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
for (k=0;k<secnumber;k++){
rs.homopart = 1./secnumber;
if(*(rs.microflag + k) ==0){
for (j=k+1;j<secnumber;j++){
if((strcmp(*(rs.ISchain + k),*(rs.ISchain + j)))==0){
rs.homopart = rs.homopart + (1./secnumber);
*(rs.microflag + j) = 1;
}
}
ISheterozygosis = ISheterozygosis + rs.homopart * rs.homopart;
}
}
ISheterozygosis = 1- ISheterozygosis;
ISheterozygosis = ((ISheterozygosis)/(secnumber -1))*secnumber;
//rs.heterozygosismean = rs.heterozygosismean + *(rs.heterozygosis + i);
rs.SASH = 0;
rs.SASH = 1-((1 - ISheterozygosis)/(1-heterozygosismean));
//printf("SH = %f, ISheterozygosis = %f, heterozygosismicro = %f\n",rs.SH,ISheterozygosis,heterozygosismean);
for (i=0;i<secnumber;i++){
free(*(rs.microchain + i));
}
for (i=0;i<secnumber;i++){
free(*(rs.ISchain + i));
}
free(rs.microflag);
free(rs.ISchain);
free(rs.microchain);
return (rs.SASH);
}
float MASH (int **size, int mnumber, int secnumber){
int i, j, k;
char *chain;
rs.microflag = NULL;
rs.microflag = malloc(secnumber * sizeof(int));
rs.microchain = malloc (secnumber*sizeof(char*));
int *compositesize;
for (i=0;i<secnumber;i++){
*(rs.microchain + i) = malloc((6*mnumber)*sizeof(char));
strcpy(*(rs.microchain + i),"");
}
for (i=0;i<secnumber;i++){
for (j=0;j<mnumber;j++){
chain = malloc (6*sizeof(char));
sprintf(chain,"%i",*(*(size+i)+j));
strcat(*(rs.microchain + i),chain);
free(chain);
}
}
float heterozygosismean = 0;
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
for (k=0;k<secnumber;k++){
rs.homopart = 1./secnumber;
if(*(rs.microflag + k) ==0){
for (j=k+1;j<secnumber;j++){
if((strcmp(*(rs.microchain + k),*(rs.microchain + j)))==0){
rs.homopart = rs.homopart + (1./secnumber);
*(rs.microflag + j) = 1;
}
}
heterozygosismean = heterozygosismean + rs.homopart * rs.homopart;
}
}
heterozygosismean = 1- heterozygosismean;
heterozygosismean = ((heterozygosismean)/(secnumber -1))*secnumber;
compositesize = malloc (secnumber*sizeof(int));
for (i=0;i<secnumber;i++){
*(compositesize + i) = 0;
for (j=0;j<mnumber;j++){
*(compositesize + i) = *(compositesize + i) + *(*(size+i)+j);
}}
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
float MASHheterozygosis = 0;
for (k=0;k<secnumber;k++){
rs.homopart = 1./secnumber;
if(*(rs.microflag + k) ==0){
for (j=k+1;j<secnumber;j++){
if(*(compositesize + j) == *(compositesize + k)){
rs.homopart = rs.homopart + (1./secnumber);
*(rs.microflag + j) = 1;
}
}
MASHheterozygosis = MASHheterozygosis + rs.homopart * rs.homopart;
}
}
MASHheterozygosis = 1- MASHheterozygosis;
MASHheterozygosis = ((MASHheterozygosis)/(secnumber -1))*secnumber;
// printf("MASHheterozygosis = %f heterocigosis = %f\n",MASHheterozygosis, heterozygosismean);
rs.MASH = 1- ((1- heterozygosismean)/(1- MASHheterozygosis));
for (i=0;i<secnumber;i++){
free(*(rs.microchain + i));
}
free(rs.microflag);
free(rs.microchain);
free(compositesize);
return (rs.MASH);
}
float SH (int **size, int mnumber, int secnumber, char ***infinite){
int i, j, k;
char *chain;
rs.microflag = NULL;
rs.microflag = malloc(secnumber * sizeof(int));
rs.microchain = malloc (secnumber*sizeof(char*));
int *compositesize;
compositesize = malloc (secnumber*sizeof(int));
for (i=0;i<secnumber;i++){
*(compositesize + i) = 0;
for (j=0;j<mnumber;j++){
*(compositesize + i) = *(compositesize + i) + *(*(size+i)+j);
}}
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
float MASHheterozygosis = 0;
for (k=0;k<secnumber;k++){
rs.homopart = 1./secnumber;
if(*(rs.microflag + k) ==0){
for (j=k+1;j<secnumber;j++){
if(*(compositesize + j) == *(compositesize + k)){
rs.homopart = rs.homopart + (1./secnumber);
*(rs.microflag + j) = 1;
}
}
MASHheterozygosis = MASHheterozygosis + rs.homopart * rs.homopart;
}
}
MASHheterozygosis = 1- MASHheterozygosis;
MASHheterozygosis = ((MASHheterozygosis)/(secnumber -1))*secnumber;
rs.ISchain = malloc(secnumber*sizeof(char*));
for (i=0;i<secnumber;i++){
*(rs.ISchain + i) = malloc((rs.segsites*mnumber)*sizeof(char));
strcpy(*(rs.ISchain + i),"");
}
for (i=0;i<secnumber;i++){
for (j=0;j<mnumber;j++){
chain = malloc (rs.segsites*sizeof(char));
sprintf(chain,"%s",*(*(infinite+i)+j));
strcat(*(rs.ISchain + i),*(*(infinite+i)+j));
free(chain);
}
}
float ISheterozygosis = 0;
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
for (k=0;k<secnumber;k++){
rs.homopart = 1./secnumber;
if(*(rs.microflag + k) ==0){
for (j=k+1;j<secnumber;j++){
if((strcmp(*(rs.ISchain + k),*(rs.ISchain + j)))==0){
rs.homopart = rs.homopart + (1./secnumber);
*(rs.microflag + j) = 1;
}
}
ISheterozygosis = ISheterozygosis + rs.homopart * rs.homopart;
}
}
ISheterozygosis = 1- ISheterozygosis;
ISheterozygosis = ((ISheterozygosis)/(secnumber -1))*secnumber;
rs.SH = 1- ((1- ISheterozygosis)/(1-MASHheterozygosis));
free(rs.microflag);
free(compositesize);
for (i=0;i<secnumber;i++){
free(*(rs.ISchain + i));
}
free(rs.ISchain);
return (rs.SH);
}
float SHchanges (int **size, int mnumber, int secnumber, char ***infinite){
char *chain;
int ISchanges, j, i;
chain = malloc (rs.segsites*sizeof(char));
ISchanges = 0;
for (j=0;j<mnumber;j++){
ISchanges = ISchanges + strlen(*(*(infinite+0)+j));
//printf("%s",*(*(infinite+0)+j));
}
//printf("Tu cadena = %s\n",chain);
//printf("cambios = %i %s\n",ISchanges,chain);
int microchanges = 0.0;
int min, max;
for (j=0;j<mnumber;j++){
min = *(*(size+0)+j);
max = *(*(size+0)+j);
for (i=0;i<secnumber;i++){
if(*(*(size+i)+j)<min){min=*(*(size+i)+j);}
if(*(*(size+i)+j)>max){max=*(*(size+i)+j);}
}
microchanges = microchanges + (max - min);
}
rs.SHchanges = (1 -(((float)microchanges)/((float)ISchanges)));
// printf("chanIS = %i, chanmic = %i\n", ISchanges,microchanges);
return(rs.SHchanges);
}
float SHdistance (int **size, int mnumber, int secnumber, char ***infinite){
int maximum = 0;
int differencepairs = 0;
//differencepairs = NULL;
//printf("grgue");
int i, j, k, l;
rs.pairmaximum = 0;
rs.microminsize = malloc (mnumber * sizeof (int) );
rs.micromaxsize = malloc (mnumber * sizeof (int) );
int sites = 0;
int counter = 0;
for (k=0;k<mnumber;k++){
*(rs.microminsize + k ) = *(*(size + 0)+k);
*(rs.micromaxsize + k ) = *(*(size + 0)+k);
for(j=0;j<secnumber;j++){
if(*(*(size + j)+k) < *(rs.microminsize + k )){
*(rs.microminsize + k ) = *(*(size + j)+k);
}
if(*(*(size + j)+k) > *(rs.micromaxsize + k )){
*(rs.micromaxsize + k ) = *(*(size + j)+k);
}
}
}
float pimicro = 0;
float fraction;
for(i=0;i<rs.micronumber;i++){
for(k=*(rs.microminsize + i );k<*(rs.micromaxsize + i);k++){
fraction = 0;
for(j=0;j<pars.cp.nsam;j++){
if (*(*(size + j)+i) > k){
fraction++;
}}
fraction=fraction/pars.cp.nsam;
pimicro = pimicro + 2*(fraction)*(1-fraction);
//fprintf(stderr,"fraction = %f\n",fraction);
//fprintf(stderr,"pimicro = %f\n",pimicro);
}}
//fprintf(stderr,"pimicro2 = %f\n",pimicro);
char *chain,*chain2;
int number, dist;
float piIS = 0;
for(i=0;i<rs.micronumber;i++){
dist = strlen(*(*(infinite+0)+i));
//printf("dist = %i ",dist);
for(l=0;l<dist;l++){
fraction = 0;
for(j=0;j<pars.cp.nsam;j++){
chain = malloc (1*sizeof(char));
sprintf(chain,"%c",*(*(*(infinite+j)+i)+l));
//printf("%s %s ",chain,chain2);
number = atoi(chain);
//printf("%i %i\n",*number,*number2);
if(number == 0){
fraction++;
}
free(chain);
}
fraction=fraction/pars.cp.nsam;
piIS = piIS +2*(fraction)*(1-fraction);
//fprintf(stderr,"fractionIS = %f\n",fraction);
//fprintf(stderr,"piIS = %f\n",piIS);
}}
//printf("SMMdist= %i ISdistance = %i",differencepairs,ISdistance);
rs.SHdist = ((float)piIS - (float)pimicro )/(float)piIS;
//printf("SHdist = %f\n",rs.SHdist);
free(rs.microminsize);
free(rs.micromaxsize);
return(rs.SHdist);
}
int sitesSMM (int **size, int mnumber, int secnumber){
int microchanges = 0;
int min, max, i , j;
for (j=0;j<mnumber;j++){
min = *(*(size+0)+j);
max = *(*(size+0)+j);
for (i=0;i<secnumber;i++){
if(*(*(size+i)+j)<min){min=*(*(size+i)+j);}
if(*(*(size+i)+j)>max){max=*(*(size+i)+j);}
}
microchanges = microchanges + (max - min);
}
return (microchanges);
}
int singleton (int **size, int mnumber, int secnumber){
rs.microminsize = malloc (mnumber * sizeof (int) );
rs.micromaxsize = malloc (mnumber * sizeof (int) );
int sites = 0;
int i, j, k, l;
int counter = 0;
for (k=0;k<mnumber;k++){
*(rs.microminsize + k ) = *(*(size + 0)+k);
*(rs.micromaxsize + k ) = *(*(size + 0)+k);
for(j=0;j<secnumber;j++){
if(*(*(size + j)+k) < *(rs.microminsize + k )){
*(rs.microminsize + k ) = *(*(size + j)+k);
}
if(*(*(size + j)+k) > *(rs.micromaxsize + k )){
*(rs.micromaxsize + k ) = *(*(size + j)+k);
}
}
//fprintf(stderr,"%i ",*(rs.microminsize + k ));
//fprintf(stderr,"%i\n",*(rs.micromaxsize + k ));
sites = sites + (*(rs.micromaxsize + k ) - *(rs.microminsize + k ));
}
//Aqu me qued
int **microbinary;
microbinary = malloc (sites*sizeof(int*));
for(i=0;i<sites;i++){
*(microbinary + i) = malloc (secnumber*sizeof(int));
}
for (i=0;i<secnumber;i++){
counter =0;
for (j=0;j<mnumber;j++){
for (l=0;l<*(*(size + i)+j) - *(rs.microminsize + j );l++){
*(*(microbinary + counter)+i) = 1;
//fprintf(stderr," %i", *(*(microbinary + counter)+i));
counter++;
}
for (l=*(*(size + i)+j) - *(rs.microminsize + j );l<(*(rs.micromaxsize + j ) - *(rs.microminsize + j ));l++){
*(*(microbinary + counter)+i) = 0;
//fprintf(stderr," %i", *(*(microbinary + counter)+i));
counter++;
}
}
//fprintf(stderr,"\n");
//fprintf(stderr,"%i\n",counter);
}
int singleton = 0;
for(i=0;i<sites;i++){
counter = 0;
for (j=0;j<secnumber;j++){
if (*(*(microbinary +i)+j) == 1){counter++;}
}
if (counter ==1){singleton++;}else if(counter == (secnumber-1)){singleton++;}
}
//fprintf(stderr,"Tus singletones = %i",singleton);
for(i=0;i<sites;i++){
free(*(microbinary + i));
}
free(microbinary);
free(rs.microminsize);
free(rs.micromaxsize);
return(singleton);
}
float msitesvar(int **size, int mnumber, int secnumber){
int i, j, k;
rs.microminsize = malloc (mnumber * sizeof (int) );
rs.micromaxsize = malloc (mnumber * sizeof (int) );
for (k=0;k<mnumber;k++){
*(rs.microminsize + k ) = *(*(size + 0)+k);
*(rs.micromaxsize + k ) = *(*(size + 0)+k);
for(j=0;j<secnumber;j++){
if(*(*(size + j)+k) < *(rs.microminsize + k )){
*(rs.microminsize + k ) = *(*(size + j)+k);
}
if(*(*(size + j)+k) > *(rs.micromaxsize + k )){
*(rs.micromaxsize + k ) = *(*(size + j)+k);
}
}
}
float mean = 0;
int *sites;
sites = malloc (mnumber * sizeof (int) );
for(i=0;i<mnumber;i++){
mean = mean + *(rs.micromaxsize + i ) -*(rs.microminsize + i );
*(sites + i) = *(rs.micromaxsize + i ) -*(rs.microminsize + i );
// fprintf(stderr, "mean = %f\n",mean);
}
mean = mean/mnumber;
//fprintf(stderr, "mean = %i\n",mean);
rs.sum = 0;
rs.squaresum = 0;
for (k=0;k<mnumber;k++){
rs.sum = rs.sum + *(sites + k);
rs.squaresum = rs.squaresum + (*(sites + k) * *(sites + k));
}
float variance;
variance = (rs.squaresum -((rs.sum*rs.sum)/mnumber))/(mnumber - 1);
//fprintf(stderr, "variance = %f\n",variance);
free(sites);
free(rs.microminsize);
free(rs.micromaxsize);
return(variance);
}
float hetero(int **size, int mnumber, int secnumber){
int i, j, k;
rs.microflag = NULL;
rs.microflag = malloc(secnumber * sizeof(int));
char *chain;
rs.microchain = malloc (secnumber*sizeof(char*));
for (i=0;i<secnumber;i++){
*(rs.microchain + i) = malloc((6*mnumber)*sizeof(char));
strcpy(*(rs.microchain + i),"");
}
for (i=0;i<secnumber;i++){
for (j=0;j<mnumber;j++){
chain = malloc (6*sizeof(char));
sprintf(chain,"%i",*(*(size+i)+j));
strcat(*(rs.microchain + i),chain);
free(chain);
}
}
float heterozygosismean = 0;
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
for (k=0;k<secnumber;k++){
rs.homopart = 1./secnumber;
if(*(rs.microflag + k) ==0){
for (j=k+1;j<secnumber;j++){
if((strcmp(*(rs.microchain + k),*(rs.microchain + j)))==0){
rs.homopart = rs.homopart + (1./secnumber);
*(rs.microflag + j) = 1;
}
}
heterozygosismean = heterozygosismean + rs.homopart * rs.homopart;
}
}
heterozygosismean = 1- heterozygosismean;
heterozygosismean = ((heterozygosismean)/(secnumber -1))*secnumber;
for (i=0;i<secnumber;i++){
free(*(rs.microchain + i));
}
free(rs.microflag);
free(rs.microchain);
return(heterozygosismean);
}
float configmicmean (int **size, int mnumber, int secnumber){
int i, j, k;
int *micros;
micros = malloc(secnumber * sizeof(int));
float meannumberconfig = 0.0;
int numberconfigurations;
int *config;
config = malloc(mnumber * sizeof(int));
float mean = 0.0;
for(k=0;k<mnumber;k++){
for (i=0;i<secnumber;i++){
*(micros + i) =0;
}
numberconfigurations = secnumber;
for(i=0;i<secnumber;i++){
if(*(micros + i) == 0){
for(j=i+1;j<secnumber;j++){
if(*(*(size + i)+k) == *(*(size + j)+k)){
*(micros + j) = 1;
numberconfigurations = numberconfigurations -1;
}
}
}
}
*(config + k) =numberconfigurations;
mean = mean + numberconfigurations;
//fprintf(stderr,"k = %i, number = %i\n",mnumber,*(config + k));
}
mean = mean / mnumber;
//fprintf(stderr,"va\n");
//printf("\nnumber of config =%f\n",meannumberconfig);
rs.sum = 0;
rs.squaresum = 0;
for(i=0;i<mnumber;i++){
rs.sum = rs.sum + *(config + i);
rs.squaresum = rs.squaresum + (*(config + i) * *(config + i));
}
meannumberconfig = (rs.squaresum -((rs.sum*rs.sum)/mnumber))/(mnumber - 1);
//printf("\nTu nmero de configuraciones es %i",rs.numberconfigurations);
//printf("%i\n",rs.numberconfigurations);
free(micros);
return (meannumberconfig);
}
float HomoBC(int **size, int mnumber, int secnumber, char ***infinite){
int i, j, k;
rs.microflag = NULL;
rs.microflag = malloc(secnumber * sizeof(int));
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
rs.numberconfigurations = secnumber;
for(i=0;i<secnumber;i++){
if(*(rs.microflag + i) == 0){
for(j=i+1;j<secnumber;j++){
rs.configflag =0;
for(k=0;k<mnumber;k++){
if(*(*(size + i)+k) != *(*(size + j)+k)){
rs.configflag = 1;
}
}
if(rs.configflag ==0){
*(rs.microflag + j) = 1;
rs.numberconfigurations = rs.numberconfigurations -1;
}
}
}
}
//printf("\nTu nmero de configuraciones es %i",rs.numberconfigurations);
//printf("%i\n",rs.numberconfigurations);
rs.ISchain = malloc(secnumber*sizeof(char*));
for (i=0;i<secnumber;i++){
*(rs.ISchain + i) = malloc((rs.segsites*mnumber)*sizeof(char));
strcpy(*(rs.ISchain + i),"");
}
for (i=0;i<secnumber;i++){
for (j=0;j<mnumber;j++){
strcat(*(rs.ISchain + i),*(*(infinite+i)+j));
}
}
rs.ISconfigurations = secnumber;
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
for(i=0;i<secnumber;i++){
if(*(rs.microflag + i) == 0){
for(j=i+1;j<secnumber;j++){
rs.configflag =0;
if((strcmp(*(rs.ISchain + i),*(rs.ISchain + j)))==0){
rs.configflag = 1;
rs.ISconfigurations = rs.ISconfigurations -1;
*(rs.microflag + j) = 1;
}
}
}
}
rs.HBC= 1.0 - ((float)rs.numberconfigurations/(float)rs.ISconfigurations);
//fprintf(stderr,"%i %i %f\n",rs.ISconfigurations, rs.numberconfigurations, rs.HBC);
free(rs.ISchain);
free(rs.microflag);
return (rs.HBC);
}
float varIS(char ***IS, int mnumber, int secnumber){
int i, k, j;
int **size;
char *num;
char *chain;
float variance;
num = malloc(1*sizeof(char));
chain = malloc(1*sizeof(char));
size = malloc(secnumber*sizeof(int*));
for(k=0;k<secnumber;k++){
*(size + k) = malloc(mnumber*sizeof(int));
for(i=0;i<mnumber;i++){
*(*(size+k)+i) =0;
}
}
strcpy(num,"1");
//fprintf(stderr,"va =%s\n",num);
for(i=0;i<mnumber;i++){
for(j=0;j<secnumber;j++){
for(k=0;k<strlen(*(*(IS+j)+i));k++){
sprintf(chain,"%c",*(*(*(IS+j)+i)+k));
if((strcmp(chain,num))==0){*(*(size+j)+i)= *(*(size+j)+i) + 1;}
}
}
}
rs.mean = NULL;
rs.mean = malloc (mnumber *sizeof(float));
for(i=0;i<mnumber;i++){
*(rs.mean + i) = 0;
for(k=0;k<secnumber;k++){
*(rs.mean + i) = *(rs.mean + i) + *(*(size +k)+i);
}
*(rs.mean + i) = (*(rs.mean + i))/secnumber;
}
//printf("\nLas medias\n");
for(i=0;i<mnumber;i++){
//printf("%f ",*(rs.mean + i));
}
rs.variance = NULL;
rs.variance = malloc(mnumber *sizeof(float));
for(i=0;i<mnumber;i++){
rs.sum = 0;
rs.squaresum = 0;
for(k=0;k<secnumber;k++){
rs.sum = rs.sum + *(*(size +k)+i);
rs.squaresum = rs.squaresum + (*(*(size +k)+i) * *(*(size +k)+i));
}
*(rs.variance + i) = (rs.squaresum -((rs.sum*rs.sum)/secnumber))/(secnumber - 1);
}
//printf("\nLas varianzas\n");
variance = 0;
for(i=0;i<mnumber;i++){
//printf("%f ", *(rs.variance + i));
variance = *(rs.variance + i) + variance;
}
variance = variance/mnumber;
//printf("La media de tu rejection variance %f",rs.rejectionvariance);
free(rs.mean);
free(rs.variance);
return (variance);
}
float heterozygosisIS(char ***IS, int mnumber, int secnumber){
int i, j, k;
rs.microflag = NULL;
rs.heterozygosis = NULL;
rs.microflag = malloc(secnumber * sizeof(int));
rs.heterozygosis = malloc(mnumber * sizeof(float));
float heterozygosis = 0.0;
for (i=0;i<mnumber;i++){
*(rs.heterozygosis + i) = 0;
}
for (i=0;i<mnumber;i++){
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
for (k=0;k<secnumber;k++){
rs.homopart = 1./secnumber;
if(*(rs.microflag + k) ==0){
for (j=k+1;j<secnumber;j++){
if((strcmp(*(*(IS + k)+i), *(*(IS + j)+i)))==0){
rs.homopart = rs.homopart + (1./secnumber);
*(rs.microflag + j) = 1;
}
}
//fprintf(stderr,"\nhomopart=%f",rs.homopart);
*(rs.heterozygosis + i) = *(rs.heterozygosis + i) + rs.homopart * rs.homopart;
}
}
//fprintf(stderr,"heteropart=%f ",*(rs.heterozygosis + i));
*(rs.heterozygosis + i) = 1- *(rs.heterozygosis + i);
*(rs.heterozygosis + i) = ((*(rs.heterozygosis + i))/(secnumber -1))*secnumber;
heterozygosis = heterozygosis + *(rs.heterozygosis + i);
}
heterozygosis = heterozygosis/mnumber;
free(rs.microflag);
free(rs.heterozygosis);
return (heterozygosis);
}
int numberofconfigurationsIS(char ***IS,int mnumber, int secnumber){
int i, j, k;
rs.microflag = NULL;
rs.microflag = malloc(secnumber * sizeof(int));
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
int numberconfigurations = secnumber;
//fprintf(stderr,"\nTu nmero de configuraciones es %i",numberconfigurations);
for(i=0;i<secnumber;i++){
if(*(rs.microflag + i) == 0){
for(j=i+1;j<secnumber;j++){
rs.configflag =0;
for(k=0;k<mnumber;k++){
if((strcmp(*(*(IS + i)+k), *(*(IS + j)+k)))==0){}else{
rs.configflag = 1;
}
}
if(rs.configflag ==0){
*(rs.microflag + j) = 1;
numberconfigurations = numberconfigurations -1;
}
}
}
}
//fprintf(stderr,"\nTu nmero de configuraciones es %i",numberconfigurations);
//printf("%i\n",rs.numberconfigurations);
free(rs.microflag);
return (numberconfigurations);
}
float nucdivIS (char ***IS, int mnumber, int secnumber){
//printf("nsam = %i mnumber = %i\n",nsam,mnumber);
float pi;
char *chain,*chain2;
int *number, *number2,dist, i, j, k, l;
int ISdistance = 0;
for(i=0;i<mnumber;i++){
dist = strlen(*(*(IS+0)+i));
//printf("dist = %i ",dist);
for(l=0;l<dist;l++){
for(j=0;j<secnumber;j++){
for(k=j+1;k<secnumber;k++){
chain = malloc (1*sizeof(char));
chain2 = malloc (1*sizeof(char));
number = malloc (1*sizeof(int));
number2 = malloc (1*sizeof(int));
sprintf(chain,"%c",*(*(*(IS+j)+i)+l));
sprintf(chain2,"%c",*(*(*(IS+k)+i)+l));
//printf("%s %s ",chain,chain2);
*number = atoi(chain);
*number2 = atoi(chain2);
//printf("%i %i\n",*number,*number2);
free(chain);
free(chain2);
if(*number != *number2){
ISdistance++;
}
free(number);
free(number2);
}
}
}}
//printf("int = %i\n",s);
//fprintf (stderr,"ISdistance = %i\n",ISdistance);
pi = (float)ISdistance/((secnumber*(secnumber-1))/2);
//printf ("pi = %f seg = %i\n",pi,rs.segtajd);
return( pi ) ;
}
int sitesIS (char ***IS, int mnumber, int secnumber){
int ISchanges, j;
ISchanges = 0;
for (j=0;j<mnumber;j++){
ISchanges = ISchanges + strlen(*(*(IS+0)+j));
//printf("%s",*(*(infinite+0)+j));
}
return (ISchanges);
}
int singletonIS (char ***IS, int mnumber, int secnumber ){
int number,site,singleton, i, j, l, dist;
singleton=0;
char *chain;
chain = malloc(1*sizeof(char));
for(i=0;i<mnumber;i++){
dist = strlen(*(*(IS+0)+i));
//printf("dist = %i ",dist);
for(l=0;l<dist;l++){
site = 0;
for(j=0;j<secnumber;j++){
sprintf(chain,"%c",*(*(*(IS+j)+i)+l));
number = atoi(chain);
if(number == 1){site++;}
}
if(site==1){singleton++;}else if (site == (secnumber -1)){singleton++;}
}
}
free(chain);
return(singleton);
}
float msitesvarIS(char ***IS, int mnumber, int secnumber){
int i, j, k;
int *sites;
sites = malloc(mnumber*sizeof(int));
for (j=0;j<mnumber;j++){
*(sites +j) = strlen(*(*(IS+0)+j));
}
float mean = 0;
for(i=0;i<mnumber;i++){
mean = mean + *(sites +i);
// fprintf(stderr, "mean = %f\n",mean);
}
mean = mean/mnumber;
//fprintf(stderr, "mean = %i\n",mean);
rs.sum = 0;
rs.squaresum = 0;
for (k=0;k<mnumber;k++){
rs.sum = rs.sum + *(sites + k);
rs.squaresum = rs.squaresum + (*(sites + k) * *(sites + k));
}
float variance;
variance = (rs.squaresum -((rs.sum*rs.sum)/mnumber))/(mnumber - 1);
//fprintf(stderr, "variance = %f\n",variance);
free(sites);
return(variance);
}
float heteroIS(char ***IS, int mnumber, int secnumber){
int i, j, k;
rs.microflag = NULL;
rs.microflag = malloc(secnumber * sizeof(int));
char *chain;
int ISchanges;
int length;
ISchanges = 0;
for (j=0;j<mnumber;j++){
ISchanges = ISchanges + strlen(*(*(IS+0)+j));
//printf("%s",*(*(infinite+0)+j));
}
rs.microchain = malloc (secnumber*sizeof(char*));
for (i=0;i<secnumber;i++){
*(rs.microchain + i) = malloc((ISchanges)*sizeof(char));
strcpy(*(rs.microchain + i),"");
}
for (i=0;i<secnumber;i++){
for (j=0;j<mnumber;j++){
length = strlen(*(*(IS+0)+j));
chain = malloc (length*sizeof(char));
sprintf(chain,"%s",*(*(IS+i)+j));
strcat(*(rs.microchain + i),chain);
free(chain);
}
}
float heterozygosismean = 0;
for (k=0;k<secnumber;k++){
*(rs.microflag + k) =0;
}
for (k=0;k<secnumber;k++){
rs.homopart = 1./secnumber;
if(*(rs.microflag + k) ==0){
for (j=k+1;j<secnumber;j++){
if((strcmp(*(rs.microchain + k),*(rs.microchain + j)))==0){
rs.homopart = rs.homopart + (1./secnumber);
*(rs.microflag + j) = 1;
}
}
heterozygosismean = heterozygosismean + rs.homopart * rs.homopart;
}
}
heterozygosismean = 1- heterozygosismean;
heterozygosismean = ((heterozygosismean)/(secnumber -1))*secnumber;
for (i=0;i<secnumber;i++){
free(*(rs.microchain + i));
}
free(rs.microflag);
free(rs.microchain);
return(heterozygosismean);
}
float configmicvarIS (char ***IS, int mnumber, int secnumber){
int i, j, k;
int *micros;
micros = malloc(secnumber * sizeof(int));
float meannumberconfig = 0.0;
int numberconfigurations;
int *config;
config = malloc(mnumber * sizeof(int));
float mean = 0.0;
for(k=0;k<mnumber;k++){
for (i=0;i<secnumber;i++){
*(micros + i) =0;
}
numberconfigurations = secnumber;
for(i=0;i<secnumber;i++){
if(*(micros + i) == 0){
for(j=i+1;j<secnumber;j++){
if(strcmp(*(*(IS + i)+k), *(*(IS + j)+k))==0){
*(micros + j) = 1;
numberconfigurations = numberconfigurations -1;
}
}
}
}
*(config + k) =numberconfigurations;
mean = mean + numberconfigurations;
//fprintf(stderr,"k = %i, number = %i\n",mnumber,*(config + k));
}
mean = mean / mnumber;
//fprintf(stderr,"va\n");
//printf("\nnumber of config =%f\n",meannumberconfig);
rs.sum = 0;
rs.squaresum = 0;
for(i=0;i<mnumber;i++){
rs.sum = rs.sum + *(config + i);
rs.squaresum = rs.squaresum + (*(config + i) * *(config + i));
}
meannumberconfig = (rs.squaresum -((rs.sum*rs.sum)/mnumber))/(mnumber - 1);
//printf("\nTu nmero de configuraciones es %i",rs.numberconfigurations);
//printf("%i\n",rs.numberconfigurations);
free(micros);
return (meannumberconfig);
}
|
C
|
//
// Created by csatl on 5/5/2020.
//
#include "hashTable.h"
#include "io.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
void initHashTable(int N)
{
//! initialize hash table with length "INITIAL_HT_SIZE_FACTOR" of N (1/4 of N)
size = (INITIAL_HT_SIZE_FACTOR * N);
hashTable = (char**)malloc(sizeof(char*) * size);
for(int i=0;i<size;i++)
{
hashTable[i] = (char*)calloc(MAX_STRING_LENGTH + 1,sizeof(char));
}
}
float getFillFactor()
{
//! return the fill factor of the hash table
float fillFactor = -1;
float counter = 0;
for(int i=0; i < size; i++)
{
if (strlen(hashTable[i]) > 0)
{
counter++;
}
}
fillFactor = counter / size;
return fillFactor;
}
void resizeHashTable()
{
numberOfResizes++;
//! reconstruct the hash table by (usually) doubling its size
//! only call this when the current fill factor of your hash table > MAX_FILL_FACTOR
//! careful, when resizing, the 'size' variable should be changed as well such that the 'hashFunction's distribution will work
//! be double careful! all the elements which are already in the hash table have to be RE-hashed! (explanation @ lab)
int oldSize = size;
char ** tempHashTable;
tempHashTable = (char**)malloc(sizeof(char*) * oldSize);
for(int i=0;i<oldSize;i++)
{
tempHashTable[i] = (char*)calloc(MAX_STRING_LENGTH + 1,sizeof(char));
strcpy(tempHashTable[i],hashTable[i]);
hashTable[i] = NULL;
free(hashTable[i]);
}
free(hashTable);
size *= 2;
hashTable = (char**)malloc(sizeof(char*) * size);
for(int i=0;i<size;i++)
{
hashTable[i] = (char*)calloc(size,sizeof(char));
}
for (int i = 0; i < oldSize; ++i)
{
if(strlen(tempHashTable[i])!=0)
{
if(strlen(tempHashTable[i]) > 0)
insertElement(tempHashTable[i]);
}
}
}
int insertElement(char * element)
{
//! insert an element
//! returns the number of collisions which occurred before the element was inserted
if(getFillFactor() > MAX_FILL_FACTOR)
resizeHashTable();
int i=0;
int index = hashFunction(element,i);
while(strlen(hashTable[index])!=0)
{
i++;
index = hashFunction(element,i);
}
strcpy(hashTable[index],element);
return i;
}
int h1(char * content, int i)
{
int length = strlen(content);
int k, sum;
for (sum=0, k=0; k < length; k++)
{
sum += content[k];
}
return (sum+i) % size;
}
int h2(char * content, int i)
{
return (strlen(content)+i) % size;
}
int h3(char * content, int i)
{
int sum = 0;
for(int i = 0; i < strlen(content); i+=5)
{
sum +=content[i];
sum = sum%size;
}
sum = sum + i % size;
sum = content[i] + sum;
return sum % size;
}
int hashFunction(char * content, int i)
{
return h1(content,i);
}
|
C
|
#include <stdio.h>
int main()
{
int c;
for(c=1;c<=5;++c){
for(int j=1;j<=c;j++){
printf("*");
}
printf("\n");
}
return 0;
}
|
C
|
#include <stdio.h>
int main ()
{
int i = 171;
float f = 3567.654;
printf ("Principais caracteres de formatao em C:\n\n");
printf ("%%c\t\tCaracter\n");
printf ("%%d ou %%i\tInteiro\n");
printf ("%%e ou %%E\tNotao cientfica\n");
printf ("%%f\t\tFloat\n");
printf ("%%o\t\tOctal\n");
printf ("%%s\t\tCadeia de caracteres (string)\n");
printf ("%%u\t\tInteiro sem sinal\n");
printf ("%%x ou %%X\tHexadecimal\n");
printf ("%%%%\t\tSmbolo de porcentagem (%%)\n");
printf ("\n\nAlguns exemplos:\n\n");
printf ("i = %d [%%d]\n", i);
printf ("i = %i [%%i]\n", i);
printf ("i = %c [%%c]\n", i);
printf ("i = %o [%%o]\n", i);
printf ("i = %u [%%u]\n", i);
printf ("i = %x [%%x]\n", i);
printf ("i = %X [%%X]\n", i);
printf ("\nf = %f [%%f]\n", f);
printf ("f = %.1f [%%.1f]\n", f);
printf ("f = %e [%%e]\n", f);
printf ("f = %E [%%E]\n", f);
}
|
C
|
// RUN: %tool "%s" > "%t"
// RUN: %diff %CORRECT "%t"
int main() {
int x;
x = ((1 + 1) <= (0 + 2));
assert x == 1;
x = 5 != 7;
assert x == 1;
x = x + (x == x) == !(x != x) + x - 1 + 1;
assert x == 1;
x = 1 << 2;
assert x == 4;
x = 1 << 3;
assert x == 7 + 1;
x = 1 << 31;
assert x == 2147483648;
x = x + 1;
assert x == -2147483647;
x = 15 >> 2;
assert x == 3;
x = x >> 10;
assert x == 0;
return 0;
}
|
C
|
/*
* Copyright (c) 2012 Roland Philippsen <roland DOT philippsen AT gmx DOT net>
*
* BSD license:
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of
* contributors to this software may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR THE CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DTRANS_HEAP_H
#define DTRANS_HEAP_H
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
Internal key comparison function pointer type. Allows to use the
heap as min heap or max heap. For convenience, just use the
maxheap_create and minheap_create functions.
*/
typedef double (*heap_keycmp_t)(double, double);
/**
Heap data structure object. Keys are double, and the values are
stored as void* (you are responsible for managing the necessary
casts and the memory of the values). Uses an array-backed tree with
the first element stored at index 1. This wastes a bit of storage
but makes the index arithmetic a tad easier and faster. But it
means you have to be careful if you want to grab the first element,
for instance in order to peek at the top of a priority queue. Use
the HEAP_PEEK_KEY and HEAP_PEEK_VALUE macros for convenience, but
they do not check whether the heap actually contains elements. Use
HEAP_LENGTH or HEAP_EMPTY in case of doubt.
*/
typedef struct heap_s {
heap_keycmp_t keycmp;
double * key; /* first element at data[1], using length+1 storage size */
const void ** value;
size_t capacity;
size_t length;
} heap_t;
/**
Utility macro for reading the length (actual number of elements)
of the heap.
*/
#define HEAP_LENGTH(heap) ((heap)->length)
/**
Utility macro for determining whether a heap is empty.
*/
#define HEAP_EMPTY(heap) ((heap)->length == 0)
/**
Utility macro for peeking at the key of the element that is at top
of the heap. Note that the heap wastes the array index zero in
order to keep arithmetic a bit easier, so this will return the key
at index one.
*/
#define HEAP_PEEK_KEY(heap) ((heap)->key[1])
/**
Utility macro for peeking at the value of the element that is at top
of the heap. Note that the heap wastes the array index zero in
order to keep arithmetic a bit easier, so this will return the value
at index one.
*/
#define HEAP_PEEK_VALUE(heap) ((heap)->value[1])
/**
Internal function used as key comparison for max heaps.
*/
double heap_keycmp_more (double lhs, double rhs);
/**
Internal function used as key comparison for min heaps.
*/
double heap_keycmp_less (double lhs, double rhs);
/**
Internal function for creating a heap, with a given key comparison
function. You can just use maxheap_create or minheap_create instead
of worrying about which internal key comparison function you have
to pick for which kind of heap.
\return A freshly created heap, or NULL in case of failure (which
stems from calloc, so you can use errno to get a system error
message).
*/
heap_t * heap_create (size_t capacity, heap_keycmp_t keycmp);
/**
Create a clone of a given heap. The capacity of the clone will be
exactly the length of the original.
\return A freshly allocated clone with all keys and data properly
copied, or NULL on failure (in which case you can use errno to see
what it's about, probably out of memory from calloc).
*/
heap_t * heap_clone (heap_t * heap);
/**
Create and properly initialize a max heap. It is an error to pass
capacity=0, that'll cause infinite loops.
\return A freshly created max heap, or NULL in case of failure
(which stems from calloc, so you can use errno to get a system
error message).
*/
heap_t * maxheap_create (size_t capacity);
/**
Create and properly initialize a min heap. It is an error to pass
capacity=0, that'll cause infinite loops.
\return A freshly created min heap, or NULL in case of failure
(which stems from calloc, so you can use errno to get a system
error message).
*/
heap_t * minheap_create (size_t capacity);
/**
Destroy a heap. Properly frees any memory allocated by the heap,
but you are still responsible for freeing up, if applicable, any of
the values that you had stored in the heap.
*/
void heap_destroy (heap_t * heap);
/**
Internal function for doubling the capacity of a heap. This is
triggered when you insert an element into a heap that is full. At
the time of writing, a heap will never deallocate any of its memory
even if it shrinks.
\return 0 on success, -1 on failure (which stems from realloc, so
you can use errno to get a system error message).
*/
int heap_grow (heap_t * heap);
/**
Internal function for swapping two elements of the heap.
*/
void heap_swap (heap_t * heap, size_t ii, size_t jj);
/**
Internal function for adjusting the heap property after an insertion.
*/
void heap_bubble_up (heap_t * heap, size_t index);
/**
Insert a given value into the heap at a position determined by the
given key. The position depends on whether you have created a min
heap or a max heap.
\return 0 on success, or -1 on failure (which stems from a failed
heap_grow, thus from realloc, and thus you can use errno).
*/
int heap_insert (heap_t * heap, double key, const void * value);
/**
Internal (recursive) function to find an element with a given key
and value in the subtree rooted at the given location. Used by
heap_change_key.
\return The index of the sought element, or zero in case of failure
(remember, the array storage starts at index one, so a zero can be
used to signify "not found" in this implementation).
*/
size_t heap_find_element (heap_t * heap, double key, const void * value, size_t root);
/**
Modify the key of an element already stored in the heap. You need
to specify the old key under which the value is currently stored,
in order to allow finding the element. After the element is found
and the key changed, the appropriate up or down bubble operation is
performed to restore the heap property.
\note Both the old_key and the value have to match, and the
implementation uses a straightforward pointer comparison on the
value. So beware of heaps that store strings or similar possibly
identical duplicates for the value.
\return 0 on success, -1 if the given key-value pair is not in the
heap, and -2 if there is some problem detecting whether this is a
max heap or a min heap. The latter is either a bug, or you have not
used maxheap_create or minheap_create to create this heap.
*/
int heap_change_key (heap_t * heap, double old_key, double new_key, const void * value);
/**
Internal function for adjusting the heap property after a removal.
*/
void heap_bubble_down (heap_t * heap, size_t index);
/**
Remove the topmost element, and return its value. In case you need
to get at the key as well, you can use the HEAP_PEEK_KEY macro. If
you need to read the topmost value without removing it, use
HEAP_PEEK_VALUE instead. Depending on whether you have created a min
heap or a max heap, the topmost element is either the one with the
smallest key (min heap), or with the biggest key (max heap).
\return A pointer to the value that used to be on top, or NULL in
case the heap was empty (or maybe you had actually put a zero on
there somewhere).
*/
void * heap_pop (heap_t * heap);
#ifdef __cplusplus
}
#endif
#endif
|
C
|
/*
* cutmorph.c
*
* Created on: 2013/11/01
* Author: IwabuchiK
*/
#ifndef STDIO_H
#define STDIO_H
#include <stdio.h>
#endif
#ifndef STRING_H
#define STRING_H
#include <string.h>
#endif
#ifndef D_1_H
#define D_1_H
#include "d_1.h"
#endif
#define MAX 65535 * 3
int getsource(char *s);
int main()
{
char source [MAX] = "あいうえお";
// char source [MAX];
int numchar;
// //v-1.0.1
// int i;
// for(i = 1; i < 20; i++){
//
// putchar(0x7E + i);
//
// }
//
// putchar('\n');
//
// putchar(0x8270); //=> 'p'
// putchar('\n');
//
// show_shift_jis();
// v-1.0.0
// numchar = getsource(source);
// source = "あいうえお";
printf("numchar=%d\n", numchar);
printf("source=%s\n", source);
// printf(__FILE__);
// printf("\n");
//
// printf("EOF=%d\n", EOF);
// printf("\n");
return 0;
}
int getsource(char *s)
{
int n=0;
while((s[n++] = getchar()) != EOF);
return n;
}
|
C
|
void adjListInit(int N){
for(i=1;i<=N;i++){
for(j=1;j<=N;j++){
graph[i][j] = 0;
}
}
}
void printInitAdj(int N){
for(i=1;i<=N;i++){
for(j=1;j<=N;j++){
printf("%d ",graph[i][j]);
}
printf("\n");
}
}
void graphEdges(){
for(i=1;i<=edge;i++){
for(j=1;j<=edge;j++){
scanf("%d%d",&start,&end);
graph[start][end] = 1;
}
}
}
|
C
|
#include<stdio.h>
int main()
{
int n,a[50],b[50],count=0;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
int large;
large=a[0];
for(int i=0;i<n;i++)
{
if(large<a[i])
large=a[i];
}
for(int i=0;i<n;i++)
{
if(large==a[i])
count++;
}
for(int i=0;i<count;i++)
{
b[i]=large;
}
for(int i=0;i<n;i++)
{
if(a[i]!=large) {
a[i]=a[i]; }
}
int j=0;
for(int i=count;i<n;i++)
{
b[i]=a[j];
j++;
}
for(int i=0;i<n;i++)
{
printf("%d\n",b[i]);
}
return 0;
}
|
C
|
#ifndef __COMMANDS_H
#define __COMMANDS_H
#include "ws2801.h"
// GRAPHIC + COMMAND TYPES
// mode / command enum
enum mode_t {
MODE_FADE = 0,
MODE_STROBE = 1,
MODE_CHASE = 2,
MODE_RAINBOW = 3
};
// primitives
// used by FADE mode
struct fade_info_t {
color_t start, finish; // colours to fade between
uint8_t speed; // how many steps to fade each frame. 0 means jump instantly, 1 means take 256 frames for the fade, 2 means 128 frames, etc.
};
struct fade_mode_state_t {
uint8_t n_fade; // index into payload.fades
uint8_t fade_pos; // how many steps (0-255) through we are
};
struct fade_mode_payload_t {
uint8_t n_fades; // # of fades to perform
fade_info_t fades[4]; // start / finish / speed info for each fade
};
// used by STROBE mode
struct strobe_mode_state_t {
uint8_t n_color; // which colour we should show
};
struct strobe_mode_payload_t {
uint8_t n_colors; // # of colours to strobe through (max 9)
color_t colors[9]; // colours to strobe through
};
// used by CHASE and RAINBOW modes
struct chase_mode_state_t {
uint8_t pos;
};
#endif
|
C
|
#include "./tests.h"
static void child_main(libforks_ServerConn conn, int socket_fd) {
(void)socket_fd;
(void)conn;
exit(23);
}
int main() {
libforks_ServerConn conn;
check(libforks_start(&conn) == libforks_OK);
int exit_fd;
pid_t child_pid;
libforks_Result r = libforks_fork(
conn,
&child_pid, // pid_ptr
NULL, // socket_fd_ptr
&exit_fd, // exit_fd_ptr
child_main
);
check(r == libforks_OK);
libforks_ExitEvent event;
check(read(exit_fd, &event, sizeof event) == sizeof event);
check(event.pid == child_pid);
check(WIFEXITED(event.wait_status));
check(WEXITSTATUS(event.wait_status) == 23);
check(libforks_stop(conn) == libforks_OK);
return 0;
}
|
C
|
/*
* Modellierung dynamischer Systeme
* Praktikum 1
* Teil 1
*
* Lösung steifer Differentialgleichungen
*
* y' = 10 - 500 * y + 5000 * x y(0)=1
*/
#include <chplot.h>
#include <math.h>
#define h 0.001
#define x_End 0.2
double Ableitung(double x, double y){
return 10 - (500*y) + (5000*x);
}
double AbleitungImplizitEuler(double xiplus1, double y){
return ( y + (10*h) + (5000*xiplus1*h) )/( (500*h) + 1 );
}
double AbleitungAnalytisch(double x, double y){
return 10 * x + pow(exp(1),(-500.0*x));
}
int main() {
int steps = x_End/h;
int i;
double k1, k2;
double xEulerExpl[steps], yEulerExpl[steps],
xRK2[steps], yRK2[steps],
xEulerImpl[steps], yEulerImpl[steps],
xAnalytisch[steps], yAnalytisch[steps];
class CPlot plot0, plot1;
plot0.title("Praktikum 1 - Teil 1 (h=0.001 ; xEnd = 0.2)");
plot1.title("Praktikum 1 - Teil 1 [Abweichungen] (h=0.001 ; xEnd = 0.2)");
// Init
xEulerExpl[0]=0;
yEulerExpl[0]=1;
xRK2[0]=0;
yRK2[0]=1;
xEulerImpl[0]=0;
yEulerImpl[0]=1;
xAnalytisch[0]=0;
yAnalytisch[0]=1;
//explizite EULER
for(i=0; i<steps-1; i++){
yEulerExpl[i+1] = yEulerExpl[i] + h * Ableitung(xEulerExpl[i],yEulerExpl[i]);
xEulerExpl[i+1] = xEulerExpl[i] + h;
}
plot0.data2D(xEulerExpl,yEulerExpl);
plot0.legend("explizite EULER", 0);
//RK2
for(i=0; i<steps-1; i++){
k1= h * Ableitung(xRK2[i], yRK2[i]);
k2= h * Ableitung(xRK2[i]+h/2, yRK2[i]+k1/2);
yRK2[i+1] = yRK2[i] + k2;
xRK2[i+1] = xRK2[i] + h;
}
plot0.data2D(xRK2,yRK2);
plot0.legend("RK2", 1);
//implizite EULER
for(i=0; i<steps-1; i++){
xEulerImpl[i+1] = xEulerImpl[i] + h; //X Muss zuerst gesetzt werden!
yEulerImpl[i+1] = AbleitungImplizitEuler(xEulerImpl[i+1],yEulerImpl[i]);
}
plot0.data2D(xEulerImpl,yEulerImpl);
plot0.legend("implizite EULER", 2);
//analytisch
for(i=0; i<steps-1; i++){
yAnalytisch[i+1] = AbleitungAnalytisch(xAnalytisch[i],yAnalytisch[i]);
xAnalytisch[i+1] = xAnalytisch[i] + h;
}
plot0.data2D(xAnalytisch,yAnalytisch);
plot0.legend("analytisch", 3);
plot0.plotting();
double yEulerExplyAnalytisch[steps];
double yRK2Analytisch[steps];
double yEulerImplAnalytisch[steps];
for(i = 0; i < steps; i++)
{
yEulerExplyAnalytisch[i] = yEulerExpl[i]- yAnalytisch[i];
yRK2Analytisch[i] = yRK2[i]- yAnalytisch[i];
yEulerImplAnalytisch[i] = yEulerImpl[i]- yAnalytisch[i];
}
plot1.data2D(xEulerExpl,yEulerExplyAnalytisch);
plot1.legend("explizite EULER",0);
plot1.data2D(xRK2,yRK2Analytisch);
plot1.legend("RK2",1);
plot1.data2D(xEulerImpl,yEulerImplAnalytisch);
plot1.legend("implizite EULER",2);
plot1.plotting();
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
char g1[100],g2[100];
int res;
clrscr();
printf("Enter g1 and g2:");
gets(g1);
gets(g2);
res=strcmp(g1,g2);
if(res==0)
printf("Strings are equal");
else
printf("Strings are not equal");
getch();
}
int strcmp(char *g1,char *g2)
{
int i=0;
while(g1[i]!='\0'||g2[i]!='\0')
{
if(g1[i]!=g2[i])
return (g2[i]-g1[i]);
i++;
}
return 0;
}
|
C
|
#include "date.h"
#include "tldlist.h"
#include <stdio.h>
#include <string.h>
#define USAGE "usage: %s begin_datestamp end_datestamp [file] ...\n"
static void process(FILE *fd, TLDList *tld) {
char bf[1024], sbf[1024];
Date *d;
while (fgets(bf, sizeof(bf), fd) != NULL) {
char *q, *p = strchr(bf, ' ');
if (p == NULL) {
fprintf(stderr, "Illegal input line: %s", bf);
return;
}
strcpy(sbf, bf);
*p++ = '\0';
while (*p == ' ')
p++;
q = strchr(p, '\n');
if (q == NULL) {
fprintf(stderr, "Illegal input line: %s", sbf);
return;
}
*q = '\0';
d = date_create(bf);
(void) tldlist_add(tld, p, d);
date_destroy(d);
}
}
int main(int argc, char *argv[]) {
Date *begin = NULL, *end = NULL;
int i;
FILE *fd;
TLDList *tld = NULL;
TLDIterator *it = NULL;
TLDNode *n;
double total;
if (argc < 3) {
fprintf(stderr, USAGE, argv[0]);
return -1;
}
begin = date_create(argv[1]);
if (begin == NULL) {
fprintf(stderr, "Error processing begin date: %s\n", argv[1]);
goto error;
}
end = date_create(argv[2]);
if (end == NULL) {
fprintf(stderr, "Error processing end date: %s\n", argv[2]);
goto error;
}
if (date_compare(begin, end) > 0) {
fprintf(stderr, "%s > %s\n", argv[1], argv[2]);
goto error;
}
tld = tldlist_create(begin, end);
if (tld == NULL) {
fprintf(stderr, "Unable to create TLD list\n");
goto error;
}
if (argc == 3)
process(stdin, tld);
else {
for (i = 3; i < argc; i++) {
if (strcmp(argv[i], "-") == 0)
fd = stdin;
else
fd = fopen(argv[i], "r");
if (fd == NULL) {
fprintf(stderr, "Unable to open %s\n", argv[i]);
continue;
}
process(fd, tld);
if (fd != stdin)
fclose(fd);
}
}
total = (double)tldlist_count(tld);
it = tldlist_iter_create(tld);
if (it == NULL) {
fprintf(stderr, "Unable to create iterator\n");
goto error;
}
while ((n = tldlist_iter_next(it))) {
printf("%6.2f %s\n", 100.0 * (double)tldnode_count(n)/total, tldnode_tldname(n));
}
tldlist_iter_destroy(it);
tldlist_destroy(tld);
date_destroy(begin);
date_destroy(end);
return 0;
error:
if (it != NULL) tldlist_iter_destroy(it);
if (tld != NULL) tldlist_destroy(tld);
if (end != NULL) date_destroy(end);
if (begin != NULL) date_destroy(begin);
return -1;
}
|
C
|
//CPE-400
//SECTION: 1001
//Luis Ruiz
//Client code
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define TRUE 1
#define FALSE 0
//display error messages
void error(char *msg)
{
perror(msg);
exit(0);
}
void getIp(struct sockaddr_in serv_addr,struct sockaddr_in cli_addr)
{
//get the server ip and convert it to a readable string
struct sockaddr_in* IPV4_client = (struct sockaddr_in*)&cli_addr;
//string that will hold the servers ip
char client[INET_ADDRSTRLEN];
inet_ntop( AF_INET, &IPV4_client, client, INET_ADDRSTRLEN );
//get the client ip and convert it to a readable string
struct sockaddr_in* IPV4_server = (struct sockaddr_in*)&serv_addr;
struct in_addr server_addr = IPV4_server->sin_addr;
//string that will hold the clients ip
char server_ip[INET_ADDRSTRLEN];
inet_ntop( AF_INET, &server_addr, server_ip, INET_ADDRSTRLEN );
//print to stdout the two ips
fprintf(stderr,"\nServer:%s\nClient:%s\n",server_ip,client);
}
int main (int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr, cli_addr;
struct hostent *server;
char buffer[500];
//check if hostname of server and port number is provided
if (argc < 3)
{
fprintf(stderr, "%s\n", "ERROR:");
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
//get desired port connection
portno = atoi(argv[2]);
//creating our socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
//get the host name
server = gethostbyname(argv[1]);
if (server == NULL)
{
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
//zero out the address first
bzero((char *) &serv_addr, sizeof(serv_addr));
//assign values to serv_addr variable
serv_addr.sin_family = AF_INET; //for IPv4 communication
//copy h_addr to s_addr
bcopy((char *)server->h_addr,(char *) &serv_addr.sin_addr.s_addr,server->h_length);
//port number
serv_addr.sin_port = htons(portno);
getIp(serv_addr,cli_addr);
//requesting connection to server
if (connect(sockfd,(struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR connecting");
while(TRUE)
{
bzero(buffer,500);
fprintf(stderr, "%s\n", "If you wish to exit, you can CTRL+C or simply press enter");
fprintf(stderr, "%s","Enter string you wish to transmit:" );
//get string
fgets(buffer,500,stdin);
//if the buffer is empty end the client communication
if(strlen(buffer) == 1 )
return 0;
//sending message to host server
send(sockfd,buffer,sizeof(buffer),0);
bzero(buffer,500);
//recieving message from host server
recv(sockfd,buffer,sizeof(buffer),0);
printf("%s\n",buffer);
bzero(buffer,500);
}
//close file descriptor
if(close(sockfd) < 0)
error("ERROR: on closing");
return 0;
}
|
C
|
//if else ladder - with no return type and no argument
#include<stdio.h>
#include<conio.h>
void fun();
void main()
{
clrscr();
fun();
getch();
}
void fun()
{
int a,b,c;
printf("enter the numbers ");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c)
{
printf("a is greater : %d",a);
}
else if(b>c && b>a)
{
printf("b is greater: %d",b);
}
else if(c>a && c>b)
{
printf("c is greater : %d",c);
}
else
{
printf("none of the above condition is match ");
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void greeting(char name [150]){
printf("hello %s",name);
}
int main(){
hello();
char myname[150];
gets(myname);
greeting(myname);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int i, numero, par = 0, impar = 0;
printf("Insira 200 números:\n");
for(i = 0; i < 200; ++i)
{
scanf("%d", &numero);
if (numero % 2 == 0)
{
++ par;
}
else
{
++ impar;
}
}
printf("A quantidade de números pares são %d\n", par);
printf("A quantidade de números ímpares são %d\n", impar);
return 0;
}
|
C
|
#include <stdio.h>
void main()
{
int m;
for (m = 5; m < 8; m++) { /* m 5 ~ 7 3ȸ ݺ */
if (m == 6) continue; /* m 6 continue Ѵ */
printf("m(%d)\n", m);
}
}
|
C
|
#include<stdio.h>
int main() {
int k,d;
scanf("%d%d",&k,&d);
int i;
if(d==0){
if(k==1){
printf("0\n");
}else{
printf("No solution\n");
}
}else{
//d大于等于k就够分了!
//以平均值的办法去分!
while(1){
if(d>=k)break;
d=d*10;
}
int average=d/k;
int more=d-average*k;
printf("%d",average+more);
for(i=0;i<k-1;i++){
printf("%d",average);
}
printf("\n");
}
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
//#include<stdio.h>
//#include<string.h>
//#include<stdlib.h>
//#include "slist.h"
////linecode* Listsort(linecode* head, lineconttype x)
////{
//// linecode *newhead = NULL, *cur = head, *fron = NULL, *cur1;
//// //newhead
//// if (head->cont < x)
//// {
//// newhead = head;
//// while (cur)
//// {
//// if (cur->cont >= x)
//// {
//// head = cur;
//// break;
//// }
//// fron = cur;
//// cur = cur->next;
//// }
//// fron->next = head->next;
//// cur = cur->next;
//// head->next = NULL;
//// cur1 = head;
//// while (cur)
//// {
//// if (cur->cont >= x)
//// {
//// fron->next = cur->next;
//// cur1->next = cur;
//// cur->next = NULL;
//// cur = fron->next;
//// cur1 = cur1->next;
//// }
//// fron = cur;
//// cur = cur->next;
//// }
//// fron->next = head;
//// return newhead;
//// }
//// else
//// {
//// while (cur)
//// {
//// if (cur->cont < x)
//// {
//// newhead = cur;
//// break;
//// }
//// else
//// {
//// fron = cur;
//// cur = cur->next;
//// }
//// }
//// fron->next = newhead->next;
//// cur = cur->next;
//// newhead->next = NULL;
//// cur1 = newhead;
//// while (cur)
//// {
//// if (cur->cont < x)
//// {
//// fron->next = cur->next;
//// cur1->next = cur;
//// cur->next = NULL;
//// cur = fron->next;
//// cur1 = cur1->next;
//// }
//// else
//// {
//// fron = cur;
//// cur = cur->next;
//// }
//// }
//// cur1->next = head;
//// return newhead;
//// }
////}
////
////linecode* Listsort(linecode* cur, lineconttype x)
////{
//// linecode* lesshead = (linecode*)malloc(sizeof(linecode));
//// linecode* lesstail = (linecode*)malloc(sizeof(linecode));
//// linecode* greathead = (linecode*)malloc(sizeof(linecode));
//// linecode* greattail = (linecode*)malloc(sizeof(linecode));
//// greathead->next = lesshead->next = NULL;
//// lesstail = lesshead;
//// greattail = greathead;
//// while (cur)
//// {
//// if (cur->cont < x)
//// {
//// lesstail->next = cur;
//// lesstail = lesstail->next;
//// cur = cur->next;
//// }
//// else
//// {
//// greattail->next = cur;
//// greattail = greattail->next;
//// cur = cur->next;
//// greattail->next = NULL;
//// }
//// }
//// lesstail->next = greathead->next;
//// linecode* newhead = lesshead->next;
//// free(greathead);
//// free(lesshead);
//// return newhead;
////}
////linecode* ListCommen(linecode* head1, linecode* head2)
////{
//// //
//// int l1 = 0, l2 = 0;
//// //struct ListNode *head1 = headA, *head2 = headB;
//// linecode* cur1 = head1, *cur2 = head2;
//// while (cur1)
//// {
//// l1++;
//// cur1 = cur1->next;
//// }
//// while (cur2)
//// {
//// l2++;
//// cur2 = cur2->next;
//// }
//// cur1 = head1;
//// cur2 = head2;
//// if (l1 > l2)
//// {
//// int x = l1 - l2, i;
//// for (i = 0; i < x; i++)
//// {
//// cur1 = cur1->next;
//// }
//// }
//// else
//// {
//// int x = l2 - l1, i;
//// for (i = 0; i < x; i++)
//// {
//// cur2 = cur2->next;
//// }
//// }
//// while (cur1)
//// {
//// if ((cur1 == cur2))
//// {
//// return cur1;
//// }
//// if ((cur1->next == cur2->next))
//// {
//// return cur1->next;
//// }
////
//// cur1 = cur1->next;
//// cur2 = cur2->next;
//// }
//// return cur1;
////}
////linecode* ListCircle(linecode* head)
////{
//// linecode *fast = head, *slow = head, *meet = NULL;
//// while (fast && fast->next)
//// {
//// fast = fast->next->next;
//// slow = slow->next;
//// if (fast == slow)
//// {
//// break;
//// }
//// }
//// //printf("%d\n", fast->val);
//// meet = fast;
//// while (meet)
//// {
//// if (meet == head)
//// {
//// break;
//// }
//// meet = meet->next;
//// head = head->next;
//// }
//// return meet;
////}
////linecode* Listcopy(linecode* head)
////{
//// linecode* cur = head;
//// while (cur)
//// {
//// linecode* copy = (linecode*)malloc(sizeof(linecode));
//// copy->cont = cur->cont;
//// copy->next = cur->next;
//// cur->next = copy;
//// copy->random = cur->random;
//// cur = copy->next;
//// copy->random = NULL;
//// }
//// cur = head;
//// linecode *back = head->next;
//// while (cur)
//// {
//// if (cur->random)
//// {
//// back->random = cur->random->next;
//// }
//// else
//// {
//// back->random = NULL;
//// }
//// cur = cur->next->next;
//// if(back->next)
//// back = back->next->next;
//// }
//// cur = head;
//// back = head->next;
//// linecode* cur1 = back;
//// while (cur1->next)
//// {
//// cur->next = cur->next->next;
//// cur1->next = cur1->next->next;
//// cur = cur->next;
//// cur1 = cur1->next;
//// }
//// cur->next = NULL;
//// return back;
////}
////void printrandom(linecode* head)
////{
//// while (head)
//// {
//// if (head->random)
//// {
//// printf("%d->", head->random->cont);
//// }
//// else
//// {
//// printf("NULL->");
//// }
//// head = head->next;
//// }
//// printf("NULL\n");
////}
////int main()
////{
//// linecode* s = NULL;
//// linecode* k = NULL;
//// //ͷ
//// /*slistpushhead(&s, 'm');
//// slistpushhead(&s, 'n');
//// slistpushhead(&s, 'q');
//// slistprint(&s);*/
//// //ͷɾ
//// /*slistpophead(&s);
//// slistpophead(&s);*/
////
//// /*slistprint(&s);*/
//// //β
//// //slistpushback(&s, 1);
//// //slistpushback(&s, 'b');
//// //slistpushback(&s, 'c');
//// //slistpushback(&s, 'd');
//// //slistpushback(&s, 'c');
//// /*slistpushback(&s, 2);
//// slistpushback(&s, 4);
//// slistpushback(&s, 5);
//// slistpushback(&s, 3);
//// slistpushback(&s,8);
//// slistpushback(&k, 3);
//// slistpushback(&k, 6);
//// slistpushback(&k, 5);
//// slistpushback(&k, 3);
//// slistpushback(&k, 8);*/
//// s = (linecode*)malloc(sizeof(linecode));
//// k = (linecode*)malloc(sizeof(linecode));
//// linecode* a = (linecode*)malloc(sizeof(linecode));
//// linecode* b = (linecode*)malloc(sizeof(linecode));
//// linecode* c = (linecode*)malloc(sizeof(linecode));
//// linecode* d = (linecode*)malloc(sizeof(linecode));
//// linecode* e = (linecode*)malloc(sizeof(linecode));
//// linecode* f = (linecode*)malloc(sizeof(linecode));
//// /*s->cont = 2;
//// s->next = a;
//// a->cont = 1;
//// a->next = d;
//// d->cont = 6;
//// d->next = e;
//// e->cont = 7;
//// e->next = f;
//// f->cont = 8;
//// f->next = NULL;
//// k->cont = 3;
//// k->next = b;
//// b->cont = 4;
//// b->next = c;
//// c->cont = 5;
//// c->next = d;*/
//// /*s->cont = 1;
//// s->next = NULL;
//// k = s;*/
//// s->cont = 1;
//// s->next = a;
//// s->random = b;
//// a->cont = 2;
//// a->next = b;
//// a->random = c;
//// b->cont = 3;
//// b->next = c;
//// b->random = a;
//// c->cont = 4;
//// c->next = d;
//// c->random = NULL;
//// d->cont = 5;
//// d->next = NULL;
//// d->random = s;
//// slistprint(&s);
//// //slistprint(&k);
//// linecode* m = Listcopy(s);
//// printrandom(s);
//// printrandom(m);
////
//// slistprint(&m);
//// /*linecode* m = ListCircle(s);*/
//// /*slistprint(&m);*/
//// /*linecode* m = Contback(s,k);
//// slistprint
//// //βɾ
//// /*slistpopback(&s);
//// slistpopback(&s);
//// slistprint(&s);*/
//// //м
//// //slistpushmid(&s, 'a','b');//'a'һַ
//// //slistpushmid(&s, 'a', 'c');//'a'һַ
//// //slistprint(&s);
//// //мɾ
//// //slistpopmid(&s, 'c');//'c'ַɾ
//// //slistpopmid(&s, 'c');//'c'ַɾ
////
//// /*slistprint(&s);*/
////
//// return 0;
////}
////
////#include<stdio.h>
////#include<stdlib.h>
////#include<windows.h>
////#include<string.h>
////void Add();
////void Show();
////void save();
////void read();
////void del();
////int search(int sid);
////void update();
////void sortinage();
////char username[20] = "abcd";
////char passwords[20] = "123";
////#define M 10
////void pressAnyKey() {
//// printf("\n=================================\n");
//// printf("\npress any key to continue!!!...\n");
//// printf("\n=================================\n");
//// system("pause");
////}
////typedef struct student
////{
//// int sid;
//// char sname[20];
//// int age;
//// int c;
//// int math;
////}stu;
////stu arr[100];
////int num = 0;
////void menu1()
////{
//// int input, flag = 1;
//// do
//// {
//// system("cls");
//// printf("**********************************************\n");
//// printf("\t\tѧϵͳӭ\n");
//// printf("\t\t1.ѧ\n");
//// printf("\t\t2.ɾѧ\n");
//// printf("\t\t3.ѧϢ\n");
//// printf("\t\t4.ʾѧϢ\n");
//// printf("\t\t5.\n");
//// printf("\t\t6.ĵ½\n");
//// printf("\t\t7.ע\n");
//// printf("**********************************************\n");
//// printf("ѡ:");
//// scanf("%d", &input);
//// switch (input)
//// {
//// case 1:
//// Add();
//// break;
//// case 2:
//// del();
//// break;
//// case 3:
//// update();
//// break;
//// case 4:
//// Show();
//// break;
//// case 5:
//// sortinage();
//// break;
//// case 6:
//// break;
//// case 7:
//// save();
//// printf("˳ɹѱ\n");
//// system("pause");
//// flag = 0;
//// break;
//// default:
//// printf("!\n");
//// break;
//// }
//// } while (flag);
////}
////void menu()
////{
//// printf("%sû,ӭ¼\n", username);
//// //pressAnyKey();
//// read();
//// printf("¼ݳɹ!\n");
//// system("pause");
//// system("cls");
//// menu1();
////}
////void aboutUs() {
//// printf("+++++++++++++++++++++++++++++++++++++++++++++++++\n");
//// printf("\tѧɼϵͳV1.0\n");
//// printf("\t:zy\n");
//// printf("\tȨУԷ¼...\n");
//// printf("+++++++++++++++++++++++++++++++++++++++++++++++++\n");
//// pressAnyKey();
////}
////int logout() {
//// char ch;
//// int i;
////
//// printf("ףȷҪ˳?(y for yes, no for no):");
//// scanf("%c", &ch);
//// if (ch == 'y') {
//// //10...
//// for (i = 0; i<3; i++) {
//// printf("%c", 7);
//// printf("........");
//// Sleep(1000);
//// }
//// printf("\n");
//// return 1;
//// }
//// return 0;
////}
////int login()
////{
//// char uname[20];
//// char uwords[20];
//// int sum = 3;
//// while (sum)
//// {
//// printf("û");
//// scanf("%s", uname);
//// printf("룺");
//// scanf("%s", uwords);
//// if (strcmp(uname, username) == 0 && strcmp(uwords, passwords) == 0)
//// {
//// return 1;
//// }
//// printf("û룡\n");
//// sum--;
//// }
//// printf("½ʧܣ\n");
//// system("pause");
//// return 0;
////}
////int main(int argc, char *argv[]) {
//// int ch; //ѡ
//// do {
//// system("cls"); //
//// printf("**********************************************\n");
//// printf("\t\t ϻʼҹѧԺѧɼϵͳ\n");
//// printf("\t\t 汾:v1.0\n");
//// printf("\t\t 1.¼\n");
//// printf("\t\t 2.\n");
//// printf("\t\t 3.˳\n");
//// printf("**********************************************\n");
//// printf("ѡ:(1,2,3):");
//// scanf("%d", &ch); // 3 س ->
//// fflush(stdin); //ռ
//// switch (ch) {
//// case 1:
//// if (login())
//// {
//// printf("¼ɹ\n");
//// system("pause");
//// menu();
//// }
//// break;
//// case 2: aboutUs(); break;
//// case 3:
//// if (logout()) {
//// printf("˳ɹ\n");
//// exit(1);
//// }
//// break;
//// default:
//// printf("\nûѡȷ...\n");
//// pressAnyKey();
//// }
//// } while (1);
//// pressAnyKey();
//// return 0;
////}
////void Add()
////{
//// int count = 0;
//// char ch;
//// do
//// {
//// count++;
//// printf("%dѧ\n", (num + 1));
//// printf("ѧid:");
//// scanf("%d", &arr[num].sid);
//// printf("ѧ:");
//// fflush(stdin);
//// scanf("%s", arr[num].sname);
//// printf("ѧ:");
//// scanf("%d", &arr[num].age);
//// printf("ѧcɼ:");
//// scanf("%d", &arr[num].c);
//// printf("ѧѧɼ:");
//// scanf("%d", &arr[num].math);
//// printf("ǷҪٴμ¼ѧ");
//// num++;
//// fflush(stdin);
//// scanf("%c", &ch);
//// if (ch != 'y')
//// {
//// printf("¼");
//// printf("μ¼%dѧݣ%d\n", count, num);
//// system("pause");
//// break;
//// }
////
//// } while (1);
////}
////void Show()
////{
//// // printf("%d\n",arr[3].sid) ;
//// // system("pause");
//// if (num == 0)
//// {
//// printf("ûѧݣ");
//// system("pause");
//// return;
//// }
//// int max, min, i;
//// double ave = 0;
//// max = arr[0].age;
//// min = arr[0].age;
//// stu ma, mi;
//// printf("id\t\t\tcɼ\tѧɼ\n");
//// for (i = 0; i<num; i++)
//// {
//// printf("%d\t%s\t%d\t%d\t%d\n", arr[i].sid, arr[i].sname, arr[i].age, arr[i].c, arr[i].math);
//// if (arr[i].age>max)
//// {
//// max = arr[i].age;
//// ma = arr[i];
//// }
//// if (arr[i].age<min)
//// {
//// min = arr[i].age;
//// mi = arr[i];
//// }
//// ave += arr[i].age;
//// }
//// printf("Ϊ%d,%s,СΪ:%d,%s,ƽΪ%.1lf\n", max, ma.sname, min, mi.sname, (1.0)*ave / num);
//// system("pause");
////}
////void save()
////{
//// FILE* pf = fopen("date.txt", "w");
//// if (pf == NULL)
//// {
//// printf("ûļ\n");
//// system("pause");
//// return;
//// }
//// fwrite(arr, sizeof(stu), num, pf);
//// fclose(pf);
////}
////void read()
////{
//// FILE* pf = fopen("date.txt", "r");
//// if (pf == NULL)
//// {
//// printf("ûļ\n");
//// system("pause");
//// return;
//// }
//// while (fread(&arr[num], sizeof(stu), 1, pf))
//// {
//// num++;
//// }
//// fclose(pf);
////}
////
////void del()
////{
//// system("cls");
//// int sid, i;
//// printf("Ҫɾѧѧţ");
//// scanf("%d", &sid);
//// int indix = search(sid);
//// if (indix<0)
//// {
//// printf("ѧѧ\n");
//// system("pause");
//// return;
//// }
//// for (i = indix; i<num; i++)
//// {
//// arr[i] = arr[i + 1];
//// }
//// num--;
//// printf("ɾ%dѧɹ\n", sid);
//// system("pause");
////}
////int search(int sid)
////{
//// int i;
//// stu s;
//// for (i = 0; i<num; i++)
//// {
//// s = arr[i];
//// if (s.sid == sid)
//// {
//// return i;
//// }
//// }
//// return -1;
////}
////void update()
////{
//// system("cls");
//// int sid;
//// printf("Ҫĵѧѧţ");
//// scanf("%d", &sid);
//// int indix = search(sid);
//// if (indix<0)
//// {
//// printf("ѧѧ\n");
//// system("pause");
//// return;
//// }
//// stu s = arr[indix];
//// printf("ԭѧϢ>>\nid\t\t\tcɼ\tѧɼ\n");
//// printf("%d\t%s\t%d\t%d\t%d\n", s.sid, s.sname, s.age, s.c, s.math);
//// printf("µ");
//// scanf("%s", arr[indix].sname);
//// printf("µ䣺");
//// scanf("%d", &arr[indix].age);
//// printf("µcɼ");
//// scanf("%d", &arr[indix].c);
//// printf("µѧɼ");
//// scanf("%d", &arr[indix].math);
//// printf("ѧΪ%dѧϢɹ\n", sid);
//// system("pause");
////}
////void sortinage()
////{
//// int i, j;
//// for (i = 0; i<num - 1; i++)
//// {
//// for (j = 0; j<num - 1 - i; j++)
//// {
//// if (arr[j].age>arr[j + 1].age)
//// {
//// stu tmp = arr[j];
//// arr[j] = arr[j + 1];
//// arr[j + 1] = tmp;
//// }
//// }
//// }
//// printf("ɣ\n");
//// system("pause");
////}
////void hidden_input(char* pwd) {
//// char input_char;
//// int index = 0;
//// fflush(stdin);//뻺
//// //ʾ*֧˸
//// while ((input_char = getch()) != '\r') {//з
//// if (input_char == '\b') {//˸
//// if (index < 0)
//// continue;
//// if (index > 0) {
//// putchar('\b');
//// putchar(' ');
//// putchar('\b');
//// index--;
//// }
//// }
//// else {
//// printf("*");
//// pwd[index++] = input_char;
//// }
//// }
//// pwd[index] = '\0';//
////}
////int main()
////{
//// char pwd[20];
//// hidden_input(pwd);
//// printf("%s\n", pwd);
//// return 0;
////}
//
////#include<time.h>
////int main()
////{
//// srand((unsigned int)time(NULL));
//// int x = rand() % 10;
//// int y = rand() % 10;
//// int z = rand() % 10;
//// int num = x * 100 + y * 10 + z;
//// printf("%d\n",num);
//// return 0;
////}
//#include<conio.h>
//#include <stdio.h>
//#include <stdlib.h>
//#include<windows.h>
//#include<time.h>
//#include<string.h>
//#define MAX 1000
//typedef struct user {
// int sid;
// char name[20];
// char type[20];
// double money;
//}user;
//user users[MAX];
//int num = 0;
///* run this program using the console pauser or add your own getch, system("pause") or input loop */
//int logout();
//int login();
//void pressanykey();
//void aboutus();
//void read1();
//void hidden_input(char* pwd);
//void menu();
//void add();
//void show();
//void save();
//void read();
//void del();
//int findStudent(int sid);
//char username[20];
//char passwords[20];
//int main(int argc, char *argv[]) {
// int i;
// do {
// system("cls");
// printf("***********************************************************\n");
// printf("\t\t\tûϵͳ\n");
// printf("\t\t\t1.¼\n");
// printf("\t\t\t2.\n");
// printf("\t\t\t3.˳\n");
// printf("***********************************************************\n");
// printf("ѡ:(1,2,3)\n");
// scanf("%d", &i);
// fflush(stdin);
// switch (i) {
// case 1:
// read1();
// if (login())
// {
// read();
// printf("Ѽأ\n");
// system("pause");
// menu();
// }
// else
// {
// printf("δµ¼\n");
// }
// break;
// case 2:
// aboutus();
// break;
// case 3:
// if (logout() == 1) {
// printf("˳ɹ\n");
// system("pause");
// exit(1);
// }
// printf("ȡ˳\n");
// system("pause");
// break;
// }
// } while (1);
//
// system("pause");
// pressanykey();
// return 0;
//}
//int logout() {
// char ch;
// int i;
// printf(",Ҫ˳?(y for yes n for no)\n");
// scanf("%c", &ch);
// if (ch == 'y') {
// for (i = 0; i<3; i++) {
// printf("%c", 7);
// printf(".....");
// Sleep(1000);
// }
// printf("\n");
// return 1;
// }
// return 0;
//}
//void pressanykey() {
// printf("\n=============\n");
// printf("\npress any key to continue\n");
// printf("\n=============\n");
// getch();//Ӽһ
//}
//
//void aboutus() {
// printf("***********************************************************\n");
// printf("\t\t\tһСĿ:\n");
// printf("\t\t\tܴ,ŷܣԹͬ\n");
// printf("\t\t\tǹߵһ\n");
// printf("***********************************************************\n");
// pressanykey();
//}
//
//int login()
//{
// int i = 3;
// while (i)
// {
// int pro;
// char uname[20];
// char uword[20];
// srand((unsigned int)time(NULL));
// int x = (rand() % 9) + 1;
// int y = rand() % 10;
// int z = rand() % 10;
// int num = x * 100 + y * 10 + z;
// printf("û");
// scanf("%s", uname);
// fflush(stdin);
// printf("룺");
// hidden_input(uword);
// printf("\n");
// printf("֤(%d):", num);
// scanf("%d", &pro);
// if (strcmp(uname, username) == 0 && strcmp(uword, passwords) == 0 && pro == num)
// {
// printf("¼ɹ\n");
// system("pause");
// return 1;
// }
// if (pro != num)
// {
// printf("֤룺\n");
// continue;
// }
// printf("û룺\n");
// i--;
// }
// return 0;
//}
//void read1()
//{
// FILE* pf = fopen("loge.txt", "r");
// fread(username, 20, 1, pf);
// fread(passwords, 20, 1, pf);
// fclose(pf);
//}
//
//void hidden_input(char* pwd) {
// char input_char;
// int index = 0;
// fflush(stdin);//뻺
// //ʾ*֧˸
// while ((input_char = getch()) != '\r') {//з
// if (input_char == '\b') {//˸
// if (index < 0)
// continue;
// if (index > 0) {
// putchar('\b');
// putchar(' ');
// putchar('\b');
// index--;
// }
// }
// else {
// printf("*");
// pwd[index++] = input_char;
// }
// }
// pwd[index] = '\0';//
//}
//void menu() {
// // struct tm *ptr;
// // int choice,flag=1;
// // time_t t=time(0);
// // char str[80];
// // ptr=localtime(&t);
// int choice, flag = 1;
// do {
// system("cls");
// // strftime(str,sizeof(str),"%Y/%m%d %X %A",ptr);
// // printf("ӭ%s,ǣ%s \n",username,str);
// printf("**********************************************\n");
// printf("\t\tûѹϵͳӭ\n");
// printf("\t\t1.û\n");
// printf("\t\t2.ɾû\n");
// printf("\t\t3.鿴ûϢ\n");
// printf("\t\t4.ûϢ\n");
// printf("\t\t5.ܽ\n");
// printf("\t\t6.û\n");
// printf("\t\t7.ע\n");
// printf("**********************************************\n");
// printf("ѡ(1,2,3,4,5,6,7):\n");
// scanf("%d", &choice);
// fflush(stdin);
// switch (choice) {
// case 1:add();
// break;
// case 2:
// del();
// break;
// case 3:
// show();
// break;
// case 4:
// break;
// case 5:
// break;
// case 6:
// break;
// case 7:
// save();
// printf("˳ɹѱ棡\n");
// system("pause");
// flag = 0;
// break;
// default:
// printf("ûѡȷϺ.\n");
// }
// } while (flag);
//}
//
//void add() {
// char ch;
// int count = 0;
// do {
// count++;
// printf("%dû:\n", (num + 1));
// printf("ûid:");
// scanf("%d", &users[num].sid);
// printf("û:");
// scanf("%s", users[num].name);
// fflush(stdin);
// printf("(ҾӣԷ):");
// scanf("%s", users[num].type);
// printf(":");
// fflush(stdin);
// scanf("%lf", &users[num].money);
// num++;
// printf("һû(y/n)\n");
// fflush(stdin);
// scanf("%c", &ch);
// if (ch != 'y')
// {
// printf("\nѧϢ\n");
// printf("%dѧܹ%dѧ\n", count, num);
// system("pause");
// break;
// }
// } while (1);
//}
//
//void show() {
// system("cls");
// int i;
// double maxMoney, minMoney;
// double sumMoney = 0;//
// struct user usermaxMoney;
// if (num == 0) {
// printf("ϵͳлû...\n");
// return;
// }
// maxMoney = users[0].money;
// minMoney = users[0].money;
// printf("û£\n");
// printf("%-8s\t%-8s\t%-8s\t%-8s\n", "ûid", "", "", "ѽ");
// for (i = 0; i<num; i++) {
// struct user s = users[i];
// printf("%-8d\t%-8s\t%-8s\t%-8.2lf\n", s.sid, s.name, s.type, s.money);
// sumMoney += s.money;
// if (s.money>maxMoney) {
// maxMoney = s.money;
// usermaxMoney = s;
// }
// if (s.money<minMoney) {
// minMoney = s.money;
// }
// }
// printf("ͳ£\n");
// printf("ûƽΪ%.1lf,Ϊ%.2lf,Ϊ%.2lf,ߵǣ%s\n", sumMoney / num, maxMoney, minMoney, usermaxMoney.name);
// system("pause");
//}
//
//void save() {
// FILE* fp = fopen("date2.txt", "w");
// fwrite(users, sizeof(struct user), num, fp);
// fclose(fp);
//}
//
//void read() {
//
// FILE *fp = fopen("date2.txt", "r");
// if (fp == NULL) {
// printf("ûļ...\n");
// getch();
// return;
// }
// while (fread(&users[num], sizeof(struct user), 1, fp)) {
// num++;
// }
// fclose(fp);
//}
//
//void del() {
// system("cls");
// int i;
// int sid;
// int index;
// printf("Ҫɾid");
// scanf("%d", sid);
// index = findStudent(sid);
// if (index<0) {
// printf("ѧ%dѧɾ...\n", sid);
// system("pause");
// return;
// }
// //ѭ飬һǰһ
// for (i = index; i<num; i++)
// {
// users[i] = users[i + 1];
// }
// num--;
// printf("ɾ%dѧûɹ\n", sid);
// system("pause");
//}
//int findStudent(int sid)
//{
// int i;
// for (i = 0; i<num; i++)
// {
// if (users[i].sid == sid)
// {
// return i;
// }
// }
// return -1;
//}
//#include <stdio.h>
//#include <stdlib.h>
//#include<windows.h>
//#include<time.h>
//#include<conio.h>
//#include<string.h>
//#define MAX 1000
//#include<mmsystem.h>
//#pragma comment(lib,"Winmm.lib")
//HANDLE hout;
//color(int c)
//{
// SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), c);
//}
//
//typedef struct user {
// int sid;
// char name[20];
// char type[20];
// double money;
//}user;
//user users[MAX];
//int num = 0;
///* run this program using the console pauser or add your own getch, system("pause") or input loop */
//int logout();
//int login();
//void pressanykey();
//void aboutus();
//void read1();
//void hidden_input(char* pwd);
//void menu();
//void add();
//void show();
//void save();
//void read();
//void del();
//void update();
//void sortinmoney();
//void Modify();
//int findStudent(int sid);
//char username[20];
//char passwords[20];
//int main() {
// int i;
// PlaySound(TEXT("1.wav"), NULL, SND_FILENAME | SND_ASYNC | SND_LOOP);
// do {
// system("cls");
// printf("***********************************************************\n");
// printf("\t\t\tûϵͳ\n");
// printf("\t\t\t1.¼\n");
// printf("\t\t\t2.\n");
// printf("\t\t\t3.˳\n");
// printf("***********************************************************\n");
// printf("ѡ:(1,2,3)\n");
// scanf("%d", &i);
// fflush(stdin);
// switch (i) {
// case 1:
// read1();
// if (login())
// {
// read();
// printf("¼ɹ\n");
// printf("Ѽأ\n");
// system("pause");
// menu();
// }
// else
// {
// color(4);
// printf("δµ¼\n");
// color(7);
// system("pause");
// }
// break;
// case 2:
// aboutus();
// break;
// case 3:
// if (logout() == 1) {
// printf("˳ɹ\n");
// PlaySound(NULL, NULL, SND_FILENAME);
// system("pause");
// exit(1);
// }
// printf("ȡ˳\n");
// system("pause");
// break;
// }
// } while (1);
//
// system("pause");
// pressanykey();
// return 0;
//}
//int logout() {
// char ch;
// int i;
// color(4);
// printf(",Ҫ˳?(y for yes n for no)\n");
// color(7);
// fflush(stdin);
// scanf("%c", &ch);
// if (ch == 'y') {
// for (i = 0; i<3; i++) {
// printf("%c", 7);
// printf(".....");
// Sleep(1000);
// }
// printf("\n");
// return 1;
// }
// return 0;
//}
//void pressanykey() {
// printf("\n=============\n");
// printf("\npress any key to continue\n");
// printf("\n=============\n");
// _getch();//Ӽһ
//}
//
//void aboutus() {
// printf("***********************************************************\n");
// printf("\t\t\tһСĿ:\n");
// printf("\t\t\tܴ,ŷܣԹͬ\n");
// printf("\t\t\tǹߵһ\n");
// printf("***********************************************************\n");
// pressanykey();
//}
//
//int login()
//{
// int i = 3;
// while (i)
// {
// int pro;
// char uname[20];
// char uword[20];
// srand((unsigned int)time(NULL));
// int x = (rand() % 9) + 1;
// int y = rand() % 10;
// int z = rand() % 10;
// int num = x * 100 + y * 10 + z;
// fflush(stdin);
// printf("û");
// scanf("%s", uname);
// fflush(stdin);
// printf("룺");
// hidden_input(uword);
// printf("\n");
// printf("֤(%d):", num);
// scanf("%d", &pro);
// if (strcmp(uname, username) == 0 && strcmp(uword, passwords) == 0 && pro == num)
// {
// return 1;
// }
// if (pro != num)
// {
// color(4);
// printf("֤룺\n");
// color(7);
// i--;
// continue;
// }
// color(4);
// printf("û룺\n");
// color(7);
// i--;
// }
// return 0;
//}
//void read1()
//{
// FILE* pf = fopen("loge.txt", "r");
// fread(username, 20, 1, pf);
// fread(passwords, 20, 1, pf);
// fclose(pf);
//}
//
//void hidden_input(char* pwd) {
// char input_char;
// int index = 0;
// fflush(stdin);//뻺
// //ʾ*֧˸
// while ((input_char = _getch()) != '\r') {//з
// if (input_char == '\b') {//˸
// if (index < 0)
// continue;
// if (index > 0) {
// putchar('\b');
// putchar(' ');
// putchar('\b');
// index--;
// }
// }
// else {
// printf("*");
// pwd[index++] = input_char;
// }
// }
// pwd[index] = '\0';//
//}
//void menu() {
// // struct tm *ptr;
// // int choice,flag=1;
// // time_t t=time(0);
// // char str[80];
// // ptr=localtime(&t);
// int choice, flag = 1;
// do {
// system("cls");
// // strftime(str,sizeof(str),"%Y/%m%d %X %A",ptr);
// // printf("ӭ%s,ǣ%s \n",username,str);
// printf("**********************************************\n");
// printf("\t\tûѹϵͳӭ\n");
// printf("\t\t1.û\n");
// printf("\t\t2.ɾû\n");
// printf("\t\t3.鿴ûϢ\n");
// printf("\t\t4.ûϢ\n");
// printf("\t\t5.ܽ\n");
// printf("\t\t6.û\n");
// printf("\t\t7.ע\n");
// printf("**********************************************\n");
// printf("ѡ(1,2,3,4,5,6,7):\n");
// scanf("%d", &choice);
// fflush(stdin);
// switch (choice) {
// case 1:add();
// break;
// case 2:
// del();
// break;
// case 3:
// show();
// break;
// case 4:
// update();
// break;
// case 5:
// sortinmoney();
// printf("ɹ\n");
// system("pause");
// break;
// case 6:
// if (login())
// {
// printf("֤ûϢɹ\n");
// Modify();
// printf("ûɹµ¼\n");
// system("pause");
// flag = 0;
// }
// break;
// case 7:
// save();
// printf("˳ɹѱ棡\n");
// system("pause");
// flag = 0;
// break;
// default:
// printf("ûѡȷϺ.\n");
// }
// } while (flag);
//}
//
//void add() {
// char ch;
// int count = 0;
// do {
// count++;
// printf("%dû:\n", (num + 1));
// printf("ûid:");
// scanf("%d", &users[num].sid);
// printf("û:");
// scanf("%s", users[num].name);
// fflush(stdin);
// printf("(ҾӣԷ):");
// scanf("%s", users[num].type);
// printf(":");
// fflush(stdin);
// scanf("%lf", &users[num].money);
// num++;
// printf("һû(y/n)\n");
// fflush(stdin);
// scanf("%c", &ch);
// if (ch != 'y')
// {
// printf("\nѧϢ\n");
// printf("%dѧܹ%dѧ\n", count, num);
// system("pause");
// break;
// }
// } while (1);
//}
//
//void show() {
// system("cls");
// int i;
// double maxMoney, minMoney;
// double sumMoney = 0;//
// struct user usermaxMoney = users[0];
// if (num == 0) {
// printf("ϵͳлû...\n");
// return;
// }
// maxMoney = users[0].money;
// minMoney = users[0].money;
// printf("û£\n");
// printf("%-8s\t%-8s\t%-8s\t%-8s\n", "ûid", "", "", "ѽ");
// for (i = 0; i<num; i++) {
// struct user s = users[i];
// printf("%-8d\t%-8s\t%-8s\t%-8.2lf\n", s.sid, s.name, s.type, s.money);
// sumMoney += s.money;
// if (s.money>maxMoney) {
// maxMoney = s.money;
// usermaxMoney = s;
// }
// if (s.money<minMoney) {
// minMoney = s.money;
// }
// }
// printf("ͳ£\n");
// printf("ûƽΪ%.1lf,Ϊ%.2lf,Ϊ%.2lf,ߵǣ%s\n", sumMoney / num, maxMoney, minMoney, usermaxMoney.name);
// system("pause");
//}
//
//void save() {
// FILE* fp = fopen("date2.txt", "w");
// fwrite(users, sizeof(struct user), num, fp);
// fclose(fp);
// fp = NULL;
//}
//
//void read() {
//
// FILE *fp = fopen("date2.txt", "r");
// if (fp == NULL) {
// printf("ûļ...\n");
// _getch();
// return;
// }
// while (fread(&users[num], sizeof(struct user), 1, fp)) {
// num++;
// }
// fclose(fp);
// fp = NULL;
//}
//
//void del() {
// system("cls");
// int i;
// int sid;
// int index;
// printf("Ҫɾid");
// scanf("%d", &sid);
// index = findStudent(sid);
// if (index<0) {
// printf("ѧ%dûɾ...\n", sid);
// system("pause");
// return;
// }
// //ѭ飬һǰһ
// for (i = index; i<num - 1; i++)
// {
// users[i] = users[i + 1];
// }
// num--;
// printf("ɾ%dѧûɹ\n", sid);
// system("pause");
//}
//int findStudent(int sid)
//{
// int i;
// for (i = 0; i<num; i++)
// {
// if (users[i].sid == sid)
// {
// return i;
// }
// }
// return -1;
//}
//
//
//void update()
//{
// system("cls");
// int sid;
// int index;
// printf("Ҫĵid");
// scanf("%d", &sid);
// index = findStudent(sid);
// if (index<0) {
// printf("ѧ%dû...\n", sid);
// system("pause");
// return;
// }
// printf("ԭϢ£\n");
// printf("%-8s\t%-8s\t%-8s\t%-8s\n", "ûid", "", "", "ѽ");
// printf("%-8d\t%-8s\t%-8s\t%-8.2lf\n", users[index].sid, users[index].name, users[index].type, users[index].money);
// printf("û:");
// scanf("%s", users[index].name);
// fflush(stdin);
// printf("µ(ҾӣԷ):");
// scanf("%s", users[index].type);
// printf("µĽ:");
// fflush(stdin);
// scanf("%lf", &users[index].money);
// printf("%dѧûɹ\n", sid);
// system("pause");
//}
//
//void sortinmoney()
//{
// int i, j;
// for (i = 0; i<num - 1; i++)
// {
// for (j = 0; j<num - 1 - i; j++)
// {
// if (users[j].money>users[j + 1].money)
// {
// user tmp = users[j];
// users[j] = users[j + 1];
// users[j + 1] = tmp;
// }
// }
// }
//}
//
//void Modify()
//{
// FILE* pf = fopen("loge.txt", "w");
// char uname[20];
// char uword[20];
// printf("µû");
// scanf("%s", uname);
// printf("µ룺");
// scanf("%s", uword);
// fwrite(uname, 20, 1, pf);
// fwrite(uword, 20, 1, pf);
// fclose(pf);
// pf = NULL;
//}
|
C
|
//Program to understand synchronization among the processes using the unnamed semaphores
#include<stdio.h>
#define MAX_VAL 10000000
#include<pthread.h>
#include<stdlib.h>
#include<sys/ipc.h>//for ftok()
#include<sys/shm.h>//for shmget(),shmat(),shmctl(),shmdt()
#include<sys/wait.h>//for waitpid()
#include<unistd.h>//for fork()
#include<semaphore.h>//for sem_open(),sem_close(),sem_unlink()
#include<fcntl.h>//for O_CREAT
//to activate the debug statements
//#define __DEBUG__
//global pointer for holding address of shared memory
long long *global_ptr ;
//create a global semaphore pointer
sem_t *sem;
/* Increment function for increment value pointed by global pointer*/
void inc_func()
{
#ifdef __DEBUG__
printf("In Increment function\n");
#endif
for(int i = 0;i<MAX_VAL;i++){
//decrement sem variable
if( sem_wait(sem) != 0)
{
perror("Error in waiting for semaphore decrement thread\n");
}
#ifdef __DEBUG__
printf("After the semaphore wait in increment function......\n");
#endif
/************Critical section Starts ********************************************************/
++*global_ptr;
/************Critical section Ends ********************************************************/
if( sem_post(sem) != 0)
{
perror("Error in posting for semaphore in decrement thread\n");
}
#ifdef __DEBUG__
printf("After the semaphore post in increment function......\n\n\n");
#endif
}
}
/* Decrement function for decrement value pointed by global pointer*/
void dec_func()
{
#ifdef __DEBUG__
printf("In Decrement function\n");
#endif
for(int i = 0;i<MAX_VAL;i++){
//decrement sem variable
if( sem_wait(sem) != 0)
{
perror("Error in waiting for semaphore decrement function\n");
}
#ifdef __DEBUG__
printf("After the semaphore wait in decrement function......\n");
#endif
/************Critical section Starts ********************************************************/
--*global_ptr;
/************Critical section Ends ********************************************************/
if( sem_post(sem) != 0)
{
perror("Error in posting for semaphore in decrement function\n");
}
#ifdef __DEBUG__
printf("After the semaphore post in decrement function......\n\n\n");
#endif
}
}
int main()
{
key_t key1;
int shmid_sem,shmid_global_ptr;
/*********************** CREATE SHARED MEMORY FOR GLOBAL PTR START ********************/
//generate a unique key
if( ( key1 = ftok("shmfile_global_ptr",67) ) == -1)
{
perror("Error in creating the key\n");
return EXIT_FAILURE;
}
/*creating shared memory of 8 bytes size with RW permissions
for user,group and others with shmid1*/
if( (shmid_global_ptr = shmget(key1,8,IPC_CREAT | 0666) ) == -1) {
perror("Error in creating the shared memory\n");
return EXIT_FAILURE;
}
//attach the shared memory to global_ptr
if( (global_ptr = (long long*)shmat(shmid_global_ptr,NULL,0)) == (void*)-1)
{
perror("Error in attaching the shared memory\n");
return EXIT_FAILURE;
}
*global_ptr = 0;//initalize global_ptr as 0 in shared memory
/************** CREATION OF SHARED MEMORY FOR GLOBAL PTR ENDS************************/
/****************** CREATE SHARED MEMORY FOR SEMAPHORE PTR START*****************************/
key_t key2;
//generate a unique key
if( ( key2 = ftok("shmfile_sem_ptr",67) ) == -1)
{
perror("Error in creating the key\n");
return EXIT_FAILURE;
}
/*creating shared memory of 8 bytes size with RW permissions
for user,group and others with shmid1*/
if( (shmid_sem = shmget(key2,8,IPC_CREAT | 0666) ) == -1) {
perror("Error in creating the shared memory\n");
return EXIT_FAILURE;
}
//attach the shared memory to semaphore ptr
if( (sem = (sem_t*)shmat(shmid_sem,NULL,0)) == (void*)-1)
{
perror("Error in attaching the shared memory\n");
return EXIT_FAILURE;
}
//Initializing the semaphore with value 1
if( (sem_init(sem,2,1) ) == -1) {
perror("Error in opening semaphore\n");
return EXIT_FAILURE;
}
/****************** CREATE SHARED MEMORY FOR SEMAPHORE PTR END*****************************/
pid_t cpid = fork();
/******************Child Process Start*****************************************************/
/* Child Process Increment the global pointer value*/
if(cpid == 0)
{
#ifdef __DEBUG__
printf("In child process\n");
#endif
inc_func();
if(shmdt(global_ptr) == -1)
{
perror("Error in detaching shared memory in Child process\n");
return EXIT_FAILURE;
}
#ifdef __DEBUG__
printf("Shared Memory detached in Child Process.....\n");
#endif
/*
if(sem_close(sem) == -1)
{
perror("Error in closing named semaphore\n");
return EXIT_FAILURE;
}*/
/* Detach the sem ptr*/
if(shmdt(sem) == -1)
{
perror("Error in detaching shared memory semaphore pointer in Child process\n");
return EXIT_FAILURE;
}
#ifdef __DEBUG__
printf("Semaphore detached in Child Process.....\n");
#endif
printf("\n\n");
}
/******************Child Process Ends*****************************************************/
/******************Parent Process Start*****************************************************/
else
{
#ifdef __DEBUG__
printf("In Parent Process.....\n");
#endif
dec_func();
#ifdef __DEBUG__
printf("Waiting for child to finish......\n");
#endif
if(waitpid(cpid,NULL,0) == -1)//waiting for child to complete
{
perror("Error in waiting for the child\n");
return EXIT_FAILURE;
}
//print the global_ptr value
printf("In Parent global_val = %lld\n",*global_ptr);
if(shmdt(global_ptr) == -1)
{
perror("Error in detaching shared memory in Parent process\n");
return EXIT_FAILURE;
}
#ifdef __DEBUG__
printf("Global Ptr Shared Memory detached in Parent Process.....\n");
#endif
//detach the semaphore pointer
if(shmdt(sem) == -1)
{
perror("Error in detaching semaphore ptr in Parent process\n");
return EXIT_FAILURE;
}
#ifdef __DEBUG__
printf("Semaphore ptr Shared Memory detached in Parent Process.....\n");
#endif
//mark to delete the global Ptr shared memory
if(shmctl(shmid_global_ptr,IPC_RMID,NULL) == -1)
{
perror("Error in deleting Global Ptr shared memory in Parent process\n");
sem_destroy(sem);
return EXIT_FAILURE;
}
#ifdef __DEBUG__
printf("Global_Ptr Shared Memory deleted in Parent Process.....\n");
#endif
//mark to delete the global Ptr shared memory
if(shmctl(shmid_sem,IPC_RMID,NULL) == -1)
{
perror("Error in deleting Semaphore Ptr shared memory in Parent process\n");
sem_destroy(sem);
return EXIT_FAILURE;
}
#ifdef __DEBUG__
printf("Sem_Ptr Shared Memory deleted in Parent Process.....\n");
#endif
if(sem_destroy(sem) == -1)
{
perror("Error in detaching semaphore ptr in Parent process\n");
return EXIT_FAILURE;
}
#ifdef __DEBUG__
printf("Semaphore deleted in Parent Process.....\n");
#endif
}
/******************Parent Process Ends*****************************************************/
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
#include <time.h>
void Read_file(char* File_name, int Count ,int *stars);
void calculate_gravitational_force(int Count ,int *stars,double gravitational_force_list[],int treat_count);
double calculate_distance(int *stars,int main_star_index,int other_star_index);
void calculate_2Norm(int Count,double gravitational_force_list[],int thread_count);
void write_file(double gravitational_force_list[],int Count);
int main(int argc, char* argv[]){
char* File_name;
int Star_count;
int thread_count;
// get variables from input
File_name=argv[1];
Star_count=atoi(argv[2]);
thread_count=atoi(argv[3]);
//Allocate stars array pointer and graviatational force array with malloc
int *stars = (int *)malloc(Star_count * 4 * sizeof(int)); //Star İnformation Array
double *gravitational_force_list = (double *)malloc(Star_count * sizeof(double)); //Gravitational Force List
//Get Stars From File
Read_file(File_name,Star_count,stars);
//Calculate Gravitational Force
calculate_gravitational_force(Star_count ,stars,gravitational_force_list,thread_count);
//Calculate 2 Norm
calculate_2Norm(Star_count,gravitational_force_list,thread_count);
//Write to file
write_file(gravitational_force_list,Star_count);
free(stars);
free(gravitational_force_list);
return 0;
}
//Get Stars From File
void Read_file(char* File_name, int Count ,int *stars){
FILE *file;
file = fopen(File_name, "r");
if(file){
for(int i=0;i<Count;i++){
for(int j=0;j<4;j++){
fscanf(file, "%d", (stars +i*4+j));
}
}
printf("Star informations were got from file ! \n");
}
else{
printf("File can not be opened !! \n");
}
fclose(file);
}
//Calculate Fravitational force
void calculate_gravitational_force(int Count ,int *stars,double gravitational_force_list[],int thread_count){
const double gravitational_constat=0.0006674; //Gravitational Constant (G)
double temp_force=0; //Gravitational Force between 2 Stars
double distance=0; //Gravitational Distance between 2 Stars
double start; //Start Calculating time
double end; //Finish Calculating time
//Filling the pointer inside
for(int i=0; i<Count; i++){
gravitational_force_list[i]=0;
}
printf("Calculating... ( the process may take a long time ) \n");
//Start time
start = omp_get_wtime();
# pragma omp parallel for num_threads(thread_count)
for(int i=0; i<Count; i++){
for(int k=0;k<Count;k++){
if(i!=k){
//Calculate Distance
distance= calculate_distance(stars,i,k);
//Calculate force between two stars
temp_force=(gravitational_constat * (*(stars +i*4+3)) * (*(stars +k*4+3)) / (pow(distance,2)));
// Add to total
gravitational_force_list[i]+=temp_force;
temp_force=0;
}
}
}
// Finish time
end = omp_get_wtime();
double time_spent = (double)(end - start);
printf("Calculating was finished!\n");
printf("Calculation Time : %lf Seconds \n",time_spent);
}
//Calculate distance between two stars
double calculate_distance(int *stars,int main_star_index,int other_star_index){
//Get 3 locations and and subtract
double main_distance=0;
double distance_1D=*(stars +main_star_index*4+0)- *(stars +other_star_index*4+0);
double distance_2D=*(stars +main_star_index*4+1)- *(stars +other_star_index*4+1);
double distance_3D=*(stars +main_star_index*4+2)- *(stars +other_star_index*4+2);
//get exponential
double squared_distances=pow(distance_1D,2) + pow(distance_2D,2) + pow(distance_3D,2);
//get squared
main_distance= sqrt(squared_distances);
return main_distance;
}
//Calculate 2 norm
void calculate_2Norm(int Count,double gravitational_force_list[],int thread_count){
double total=0;
int i = 0;
# pragma omp parallel for num_threads(thread_count) reduction(+:total)
for(i=0;i<Count;i++){
# pragma omp critical
total+=pow(gravitational_force_list[i],2);
}
total= sqrt(total);
printf("2-Norm : %2.13E \n",total);
}
//Write to file
void write_file(double gravitational_force_list[],int Count){
FILE *file;
file = fopen("forces.txt", "w");
for(int i = 0; i < Count;i++){
fprintf (file, "%lf \n",gravitational_force_list[i]);
}
printf("Gravitational Forces were writed to file! \n");
fclose(file);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <locale.h>
#include <math.h>
void bubble_sort();
void comb_sort();
void merge();
void mergeSort();
void ed_cnts(double* sv, long* cnts, long N)
{
unsigned short i;
unsigned char* bp = (unsigned char*)sv;
unsigned char* svEnd = (unsigned char*)(sv + N);
for (int i = 0; i < 256 * sizeof(double); i++)
cnts[i] = 0;
while (bp != svEnd)
{
for (i = 0; i < sizeof(double); i++)
cnts[256 * i + *(bp++)]++;
}
}
void Radix_Pass(short Offset, long N, double* source, double* dl, long* cnt, int *per)
{
unsigned char* bp;
double* as;
long s = 0, d, i, * dc = cnt;
for (i = 256; i > 0; i--, ++dc)
{
d = *dc;
*dc = s;
s += d;
}
bp = (unsigned char*)source + Offset;
as = source;
for (i = N; i > 0; --i, bp += sizeof(double), ++as)
{
dc = cnt + *bp; dl[*dc] = *as; (*dc)++; per[0] = per[0] + 1;
}
}
void Radix_Sort(double* vh, double* iz, long* cnts, long N, int *zx)
{
long* cnt;
unsigned short i;
int k = 0;
ed_cnts(vh, cnts, N);
for (i = 0; i < sizeof(double); i++)
{
cnt = cnts + 256 * i;
Radix_Pass(i, N, vh, iz, cnt, zx);
for (long j = 0; j < N; j++){
vh[j] = iz[j];
zx[0] = zx[0] + 1;
}
}
while (vh[k] >= 0 && k < N)
k++;
for (int i = 0; i < N - k; i++)
{
vh[i] = iz[N - 1 - i];
}
for (int i = 0; i < k; i++)
{
vh[N - k + i] = iz[i];
}
}
int compare ();
int main()
{
int pr[1] = {0};
int sr[1] = {0};
int E;
long int g;
int i=0;
setlocale(0,"");
printf(" \n1 - \n2 - \n3 - \n4 - \n5 - \n");
scanf("%d", &E);
printf(" - : ");
scanf("%ld", &g);
if (E==1){
double *arr;
arr = (double*)malloc(g*sizeof(double));
printf(" : ");
for(i=0;i<g;i++)
scanf("%lf", &arr[i]);
bubble_sort(arr, g);
printf(" : ");
for(i=0 ; i<g ; i++)
printf("%lf ",arr[i]);
}
if (E==2){
double *arr;
arr = (double*)malloc(g*sizeof(double));
printf(" : ");
for(i=0;i<g;i++)
scanf("%lf", &arr[i]);
comb_sort(arr, g);
printf(" : ");
for(i=0 ; i<g ; i++)
printf("%lf ",arr[i]);
}
if (E==3)
{
double *arr;
arr = (double*)malloc(g*sizeof(double));
printf(" : ");
for(i=0;i<g;i++)
scanf("%lf", &arr[i]);
mergeSort(arr, 0, g - 1, sr, pr);
printf(" : ");
for(i=0 ; i<g ; i++)
printf("%lf ",arr[i]);
printf("\n");
printf(" : %d\n", pr[0]);
printf(" : %d\n", sr[0]);
}
if (E==4)
{
double* arr = (double*)malloc(g * sizeof(double));
double* arr1 = (double*)malloc(g * sizeof(double));
long* cnts = (long*)malloc(1024 * sizeof(double));
printf("\n");
printf(" : ");
for(i=0;i<g;i++)
scanf("%lf", &arr[i]);
Radix_Sort(arr, arr1, cnts,g, pr);
printf(" : ");
for(i=0 ; i<g ; i++)
printf("%lf ",arr[i]);
printf("\n : %d\n", pr[0]);
}
if(E==5) {
double arr[g];
printf(" : ");
for(i=0;i<g;i++)
scanf("%lf", &arr[i]);
qsort(arr, g, sizeof(double), compare);
printf("\n : ");
for( i = 0 ; i < g; i++ )
printf("%lf ", arr[i]);
}
return(0);
}
void bubble_sort(double *arr, int g)
{
double q;
int i=0,j=0;
int s,p;
s=0;
p=0;
for(i=0 ; i<g-1 ; i++) {
for(j=0 ; j<g-i-1 ; j++){
if(arr[j]>arr[j+1]) {
q=arr[j];
arr[j]=arr[j+1];
arr[j+1]=q;
s++;
p++;
}
else
s++;
}
}
printf("%d - - \n%d - - \n", s, p);
}
void comb_sort(double *arr, int size)
{
int s,p;
double factor = 1.2473309;
int step=size-1;
while (step >=1 )
{
for(int i=0; i+step<size;i++)
{
if (arr[i]>arr[i+step])
{
double tmp=arr[i];
arr[i]=arr[i+step];
arr[i+step]=tmp;
s++;
p++;
}
else
s++;
}
step=step/factor;
}
printf("%d - - \n%d - - \n", s,p);
}
void merge(double arr[], int l, int m, int r, int *s, int *p)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
double Left[n1], Right[n2];
for (i = 0; i < n1; i++){
Left[i] = arr[l + i];
}
for (j = 0; j < n2; j++){
Right[j] = arr[m + 1 + j];
}
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (Left[i] <= Right[j]) {
arr[k] = Left[i];
i++;
p[0]++;
s[0]++;
}
else {
arr[k] = Right[j];
j++;
p[0]++;
s[0]++;
}
k++;
}
while (i < n1) {
arr[k] = Left[i];
i++;
k++;
p[0]++;
}
while (j < n2) {
arr[k] = Right[j];
j++;
k++;
p[0]++;
}
}
void mergeSort(double arr[], int l, int r, int *s, int *p)
{
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m, s, p);
mergeSort(arr, m + 1, r, s, p);
merge(arr, l, m, r, s, p);
}
}
int compare (const void * a, const void * b)
{
if (*(double*)a > *(double*)b) return 1;
else if (*(double*)a < *(double*)b) return -1;
else return 0;
}
|
C
|
#include <stdio.h>
#include <stddef.h>
//structure of the employee table
typedef struct
{
/* data */
long number; //four bytes
char *name; //four bytes
char *phone; //four bytes
double salary; //eight bytes
} Employee, *PtrToEmployee; // two variable names
// once initialized, cant be changed pointer of type Employee
typedef const Employee *PtrToConstEmployee;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.