language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
//Write a program to accept a number and print unique pairs of numbers such that multiplication of //the pair is given number
//Input: 24
//Output:
//1 * 24 = 24
// 2 * 12 = 24
// 3 * 8 = 24
// 4 * 6 = 24
#include<stdio.h>
int main()
{
int no,i = 1,mul;
printf("Enter number: ");
scanf("%d", &no);
while(i < no)
{
if(no % i == 0)
{
if(i < no/i)
printf("\n %d * %d = %d",i,no/i,no);
}
i++;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_flags_fun.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: helvi <helvi@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/20 18:47:20 by hhuhtane #+# #+# */
/* Updated: 2021/03/24 20:14:17 by hhuhtane ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
/*
**********************
** '#' (hash) -FLAG **
****************************************************************
**
** The value should be converted to an ``alternate form''.
** For c, d, i, n, p, s, and u conversions, this option has
** no effect. For o conversions, the precision of the number
** is increased to force the first character of the output
** string to a zero. For x and X conversions, a non-zero
** result has the string `0x' (or `0X' for X conversions)
** prepended to it. For a, A, e, E, f, F, g, and G conver-
** sions, the result will always contain a decimal point,
** even if no digits follow it (normally, a decimal point
** appears in the results of those conversions only if a
** digit follows). For g and G conversions, trailing zeros
** are not removed from the result as they would otherwise
** be.
**
****************************************************************
*/
void ft_flag_hash(void *param)
{
t_all *all;
all = (t_all *)param;
if ((all->format_id & CDINPSU_MASK))
return ;
if (((all->format_id >> O_INDEX) & 1) && \
(all->arg_uint != 0 || \
((all->format_info & (1 << PRECISION_INDEX)) && \
all->precision == 0 && all->arg_uint == 0)))
{
ft_strcpy(all->prefix, "0");
all->prefix_len = 1;
}
else if (((all->format_id >> X_INDEX) & 1) && all->arg_uint != 0)
{
ft_strcpy(all->prefix, "0x");
all->prefix_len = 2;
}
else if (((all->format_id >> UPX_INDEX) & 1) && all->arg_uint != 0)
{
ft_strcpy(all->prefix, "0X");
all->prefix_len = 2;
}
}
/*
**********************
** '0' (zero) -FLAG **
****************************************************************
**
** Zero padding. For all conversions except n, the converted
** value is padded on the left with zeros rather than blanks.
** If a precision is given with a numeric conversion (d, i,
** o, u, i, x, and X), the 0 flag is ignored.
**
****************************************************************
*/
void ft_flag_zero(void *param)
{
t_all *all;
all = (t_all *)param;
if ((all->format_id & (1 << N_INDEX)))
return ;
if ((all->format_id & (DIOUXX_MASK)) && \
(all->format_info & (1 << PRECISION_INDEX)))
{
all->format_info = all->format_info & ~(1 << ZERO_INDEX);
return ;
}
if ((all->format_info & (1 << MINUS_INDEX)))
{
all->format_info = all->format_info & ~(1 << ZERO_INDEX);
return ;
}
else
all->padding_char = '0';
}
/*
************************
** '-' (minus) -FLAG **
************************
**
** A negative field width flag; the converted value is to be
** left adjusted on the field boundary. Except for n conver-
** sions, the converted value is padded on the right with
** blanks, rather than on the left with blanks or zeros. A -
** overrides a 0 if both are given.
**
************************
*/
void ft_flag_minus(void *param)
{
t_all *all;
all = (t_all *)param;
all->padding_char = ' ';
}
/*
***********************
** ' ' (space) -FLAG **
***********************
**
** A blank should be left before a positive number produced
** by a signed conversion (a, A, d, e, E, f, F, g, G, or i).
**
***********************
*/
void ft_flag_space(void *param)
{
t_all *all;
all = (t_all *)param;
if ((all->format_info & (1 << PLUS_INDEX)))
{
all->format_info = all->format_info & ~(1 << SPACE_INDEX);
return ;
}
if ((all->format_id & DI_MASK))
{
if (all->arg_int >= 0)
{
ft_strcpy(all->prefix, " ");
all->prefix_len = 1;
}
}
else if ((all->format_id & AAEEFFGG_MASK))
{
if (all->arg_double >= 0)
{
ft_strcpy(all->prefix, " ");
all->prefix_len = 1;
}
}
}
/*
**********************
** '+' (plus) -FLAG **
**********************
**
** A sign must always be placed before a number produced by a
** signed conversion. A + overrides a space if both are
** used.
**
**********************
*/
void ft_flag_plus(void *param)
{
t_all *all;
all = (t_all *)param;
if ((all->format_id & DI_MASK))
{
if (all->arg_int >= 0)
{
ft_strcpy(all->prefix, "+");
all->arg_len = 1;
}
}
else if ((all->format_id & AAEEFFGG_MASK))
{
if (all->arg_double >= 0)
{
ft_strcpy(all->prefix, "+");
all->arg_len = 1;
}
}
}
|
C
|
/*
BASEADO NESTE EXEMPLO, FOI POSSÍVEL ATIVAR A IRQ8 - RTC
REAL TIME CLOCK
http://math.haifa.ac.il/ronn/realtime/lab6/
clk70.c
*/
#include <stdio.h>
#include <dos.h>
int convert_to_binary(int x)
{
int i;
int temp, scale, result;
temp =0;
scale = 1;
for(i=0; i < 4; i++)
{
temp = temp + (x % 2)*scale;
scale *= 2;
x = x >> 1;
} // for
result = temp;
temp = 0;
scale = 1;
for(i=0; i < 4; i++)
{
temp = temp + (x % 2)*scale;
scale *= 2;
x = x >> 1;
} // for
temp *= 10;
result = temp + result;
return result;
} // convert_to_binary
volatile int global_flag;
void interrupt (*old0x70isr)(void);
void interrupt new0x70isr(void)
{
global_flag = 1;
asm {
PUSH AX
PUSH BX
IN AL,70h // Read existing port 70h
MOV BX,AX
MOV AL,0Ch // Set up "Read status register C"
OUT 70h,AL //
MOV AL,8Ch //
OUT 70h,AL //
IN AL,71h
MOV AX,BX // Restore port 70h
OUT 70h,AL //
MOV AL,20h // Set up "EOI" value
OUT 0A0h,AL // Notify Secondary PIC
OUT 020h,AL // Notify Primary PIC
POP BX
POP AX
} // asm */
} // new0x70isr
void readclk(char str[])
{
int i;
int hour, min, sec;
hour = min = sec = 0;
asm {
PUSH AX
MOV AL,0
OUT 70h,AL
IN AL,71h
MOV BYTE PTR sec,AL
//
MOV AL,2
OUT 70h,AL
IN AL,71h
MOV BYTE PTR min,AL
//
MOV AL,4
OUT 70h,AL
IN AL,71h
MOV BYTE PTR hour,AL
//
POP AX
} // asm
sec = convert_to_binary(sec);
min = convert_to_binary(min);
hour = convert_to_binary(hour);
sprintf(str,"%2d:%2d:%2d", hour, min, sec);
} // readclk
int main()
{
char str[16];
int local_flag = 1, x71h1=0, x71h2=0, x71h3;
char old_0A1h_mask, old_70h_A_mask;
old0x70isr = getvect(0x70);
setvect(0x70, new0x70isr);
asm {
CLI // Disable interrupts
PUSH AX // Interrupt may occur while updating
IN AL,0A1h // Make sure IRQ8 is not masked
MOV old_0A1h_mask,AL
AND AL,0FEh // Set bit 0 of port 0A1 to zero
OUT 0A1h,AL //
IN AL,70h // Set up "Write into status register A"
MOV AL,0Ah //
OUT 70h,AL //
MOV AL,8Ah //
OUT 70h,AL //
IN AL,71h //
MOV BYTE PTR x71h1,AL // Save old value
MOV old_70h_A_mask,AL
AND AL,11110000b // Change only Rate
OR AL,0110b // Make sure it is Rate =0110 (1Khz)
OUT 71h,AL // Write into status register A
IN AL,71h // Read to confirm write
IN AL,70h // Set up "Write into status register B"
MOV AL,0Bh //
OUT 70h,AL //
MOV AL,8Bh //
OUT 70h,AL //
IN AL,71h //
MOV BYTE PTR x71h2,AL // Save Old value
AND AL,8Fh // Mask out PI,AI,UI
OR AL,10h // Enable update interrupts (UI=1) only
OUT 71h,AL // Write into status register B
IN AL,71h // Read to confirm write
MOV byte ptr x71h3,AL // Save old value
IN AL,021h // Make sure IRQ2 is not masked
AND AL,0FBh // Write 0 to bit 2 of port 21h
OUT 021h,AL // Write to port 21h
IN AL,70h // Set up "Read into status resister C"
MOV AL,0Ch // Required for for "Write into port 71h"
OUT 70h,AL
IN AL,70h
MOV AL,8Ch //
OUT 70h,AL
IN AL,71h // Read status register C
// (we do nothing with it)
IN AL,70h // Set up "Read into status resister C"
MOV AL,0Dh // Required for for "Write into port 71h"
OUT 70h,AL
IN AL,70h
MOV AL,8Dh
OUT 70h,AL
IN AL,71h // Read status register D
// (we do nothing with it)
STI
POP AX
} // asm
printf("x71h1 = %x, x71h2 = %x, x72h3 = %x\n", x71h1, x71h2, x71h3);
while(local_flag)
{
putchar(13);
global_flag = 0;
while(global_flag == 0) // Wait for interrupt
; // Do not print all the time
readclk(str);
printf(str);
asm {
PUSH AX // Press any key to terminate
MOV AH,1 // Check If key has been pressed
INT 16h //
PUSHF
POP AX
AND AX,64 // isolate zf
MOV local_flag,AX
POP AX
} // asm
} // while
asm {
PUSH AX // Cancel key pressed
MOV AH,0
INT 16h
POP AX
} // asm
asm {
MOV AL,old_0A1h_mask
OUT 0A1h,AL
IN AL,70h // restore A status register
MOV AL,0Ah
OUT 70h,AL
MOV AL,8Ah
OUT 70h,AL
IN AL,71h
MOV AL,old_70h_A_mask
OUT 71h,AL
IN AL,71h
} // asm
setvect(0x70, old0x70isr);
} // main
|
C
|
#include <stdio.h>
#define STACK_MAX 100
typedef struct
{
/* data */
int top;
int data[STACK_MAX];
} Stack;
int push(Stack* s, int data);
int pop(Stack *s);
int main(void){
Stack my_stack;
int item;
my_stack.top = 0;
push(&my_stack, 1);
push(&my_stack, 2);
push(&my_stack, 3);
item = pop(&my_stack);
printf("%d\n", item);
item = pop(&my_stack);
printf("%d\n", item);
}
int push(Stack* s, int data){
if (s->top < STACK_MAX){
s->data[s->top] = data;
s->top = s->top + 1;
} else
{
printf("Stack is full!");
}
}
int pop(Stack *s){
int item;
if (s->top == 0){
printf("Stack is empty!");
return -1;
} else
{
s->top = s->top - 1;
item = s->data[s->top];
}
return item;
}
|
C
|
#include "holberton.h"
/**
* _pow_recursion - prototype function
* Description: return the value of x raised by the power of y
* @x: our value
* @y: our power to
* Return: if y lower than 0 return -1
*/
int _pow_recursion(int x, int y)
{
if (y < 0)
return (-1);
else if (y == 0)
return (1);
else
return (x * _pow_recursion(x, y - 1));
}
|
C
|
#include "../inc/table_declaration.h"
#include "../inc/html.h"
void init_table_decla()
{
int i;
prochaine_place_libre = TAILLE_TAB_HASH;
decalage_bc = 0;
for (i = 0; i < TAILLE_TABLE_DECLARATION; i++) {
Tab_dec[i].nature = -1;
Tab_dec[i].suivant = -1;
}
}
int test_place_libre()
{
if (prochaine_place_libre >= TAILLE_TABLE_DECLARATION) {
fprintf(stderr, "erreur memoire trop de declaration \n");
exit(-1);
}
return 0;
}
int taille_type(int type)
{
if (Tab_dec[type].nature == -1) {
/*erreur*/
fprintf(stderr, "erreur declaration le type %s n'est pas declare\n", get_lexeme(type));
exit(-1);
}
if (Tab_dec[type].nature != TYPE_B && Tab_dec[type].nature != TYPE_T && Tab_dec[type].nature != TYPE_S) {
fprintf(stderr, "erreur declaration le type %s n'est pas un type \n", get_lexeme(type));
exit(-1);
}
return Tab_dec[type].execution; /*ici ca risque d etre modif*/
}
int indice_pour_lexem(int lexem){
int index=lexem;
while(Tab_dec[index].suivant!=-1){
index=Tab_dec[index].suivant;
}
if(Tab_dec[index].nature!=-1){
Tab_dec[index].suivant=prochaine_place_libre;
index=prochaine_place_libre;
prochaine_place_libre++;
test_place_libre();
}
return index;
}
void ajoute_type_base(int lexem)
{
int index = indice_pour_lexem(lexem);
Tab_dec[index].nature = TYPE_B;
Tab_dec[index].suivant = -1;
Tab_dec[index].region = region_actu();
Tab_dec[index].description = -1;
Tab_dec[index].execution = 1;
}
void ajoute_variable(int lexem, int type)
{
int index = indice_pour_lexem(lexem);
Tab_dec[index].nature = VAR;
Tab_dec[index].suivant = -1;
Tab_dec[index].region = region_actu();
Tab_dec[index].description = type;
Tab_dec[index].execution = decalage_bc;
decalage_bc += taille_type(type); /*c'est pas sa car c'est la decalage en fonction de BC*/
}
/*il faut regarder pour les deux tab et struct car j'utilise la file de donner donc il faut voir l'ordre et tout et l'implementer */
int nbr_case_tableau(int index)
{ /*hein ?*/
int nbr_dim;
int i;
int res = 1;
int prem, deux;
index++;
nbr_dim = Table_rep_type[index];
for (i = 0; i < nbr_dim; i++) {
index++;
prem = Table_rep_type[index];
index++;
deux = Table_rep_type[index];
res *= deux - (prem - 1);
}
return res;
}
void ajoute_tableau(int lexem)
{
int index = indice_pour_lexem(lexem);
Tab_dec[index].nature = TYPE_T;
Tab_dec[index].suivant = -1;
Tab_dec[index].region = region_actu();
Tab_dec[index].description = Index_table_rep_type;
rp_ajoute_tableau();
Tab_dec[index].execution = taille_type(Table_rep_type[Tab_dec[index].description]) * nbr_case_tableau(Tab_dec[index].description);
}
int calcule_taille_struct(int index)
{ /*probleme ici pour le calcule du champ exec*/
int res = 0;
int nbr_var = Table_rep_type[index];
int i;
index += 2;
for (i = 0; i < nbr_var; i++) {
Table_rep_type[index + 1] = res;
res += taille_type(Table_rep_type[index]);
index += 3;
}
return res;
}
void ajoute_struct(int lexem)
{
int index = indice_pour_lexem(lexem);
Tab_dec[index].nature = TYPE_S;
Tab_dec[index].suivant = -1;
Tab_dec[index].region = region_actu();
Tab_dec[index].description = Index_table_rep_type;
rp_ajoute_struct();
Tab_dec[index].execution = calcule_taille_struct(Tab_dec[index].description);
}
/*jen suis ici pour le yacc il faut verif*/
int taille_arg(int index, int nbr)
{
int i;
int res = 0;
for (i = 0; i < nbr; i++) {
res += taille_type(Table_rep_type[index + 1]);
index += 2;
}
return res;
}
void declare_arg(int index, int nbr)
{
int i;
for (i = 0; i < nbr; i++) {
ajoute_variable(Table_rep_type[index], Table_rep_type[index + 1]);
index += 2;
}
}
void ajoute_fonction(int lexem)
{
int index = indice_pour_lexem(lexem);
Tab_dec[index].nature = FUNC;
Tab_dec[index].suivant = -1;
Tab_dec[index].region = region_actu();
Tab_dec[index].description = Index_table_rep_type;
rp_ajoute_fonction();
nouvelle_region();
Tab_dec[index].execution = region_actu();
decalage_bc = 0;
declare_arg(Tab_dec[index].description + 2, Table_rep_type[Tab_dec[index].description]);
}
void ajoute_proc(int lexem)
{
int index = indice_pour_lexem(lexem);
Tab_dec[index].nature = PROC;
Tab_dec[index].suivant = -1;
Tab_dec[index].region = region_actu();
Tab_dec[index].description = Index_table_rep_type;
rp_ajoute_proc();
nouvelle_region();
Tab_dec[index].execution = region_actu();
decalage_bc = 0;
declare_arg(Tab_dec[index].description + 1, Table_rep_type[Tab_dec[index].description]);
}
void taille_de_la_region()
{
ajoute_taille_region(decalage_bc);
}
void fin_proc_fonc_region(type_arbre* a)
{
ajoute_arbre_table_region(a);
fin_region();
}
|
C
|
#include "include/s7lib_parser.h"
uint8_t * s7lib_parser_write_bool(uint8_t * byte_array, int byte_index, int bit_index, bool value)
{
if(value == true)
byte_array[byte_index] |= ((uint8_t) 1 << bit_index);
else
byte_array[byte_index] &= ((uint8_t) ~(1<< bit_index));
return byte_array;
}
uint8_t * s7lib_parser_write_int(uint8_t * byte_array, int byte_index, int16_t value)
{
byte_array[byte_index + 1] = ((uint8_t*) &value)[0];
byte_array[byte_index] = ((uint8_t*) &value)[1];
return byte_array;
}
uint8_t * s7lib_parser_write_dword(uint8_t * byte_array, int byte_index, int32_t value)
{
byte_array[byte_index + 3] = ((uint8_t*)&value)[0];
byte_array[byte_index + 2] = ((uint8_t*)&value)[1];
byte_array[byte_index + 1] = ((uint8_t*)&value)[2];
byte_array[byte_index] = ((uint8_t*)&value)[3];
return byte_array;
}
uint8_t * s7lib_parser_write_real(uint8_t * byte_array, int byte_index, float value)
{
byte_array[byte_index + 3] = ((uint8_t*)&value)[0];
byte_array[byte_index + 2] = ((uint8_t*)&value)[1];
byte_array[byte_index + 1] = ((uint8_t*)&value)[2];
byte_array[byte_index] = ((uint8_t*)&value)[3];
return byte_array;
}
static uint8_t s7lib_parser_get_string_length(int string_length, int size)
{
return ((string_length >= size) ? size : string_length);
}
uint8_t * s7lib_parser_write_string(uint8_t * byte_array, int byte_index, char * string, uint8_t size)
{
snprintf((char*) (byte_array+byte_index), size+3, "%c%c%s", size, s7lib_parser_get_string_length(strlen(string), size), string);
return byte_array;
}
bool s7lib_parser_read_bool(uint8_t * byte_array, int byte_index, int bit_index)
{
return (byte_array[byte_index] & (1 << bit_index));
}
int16_t s7lib_parser_read_int(uint8_t * byte_array, int byte_index)
{
uint32_t value = (byte_array[byte_index+1]);
((uint8_t*)&value)[1] = (byte_array[byte_index]);
return value;
}
uint32_t s7lib_parser_read_dword(uint8_t * byte_array, int byte_index)
{
uint32_t value = (byte_array[byte_index+3]);
((uint8_t*)&value)[1] = (byte_array[byte_index+2]);
((uint8_t*)&value)[2] = (byte_array[byte_index+1]);
((uint8_t*)&value)[3] = (byte_array[byte_index]);
return value;
}
float s7lib_parser_read_real(uint8_t * byte_array, int byte_index)
{
float value = (byte_array[byte_index+3]);
((uint8_t*)&value)[1] = (byte_array[byte_index+2]);
((uint8_t*)&value)[2] = (byte_array[byte_index+1]);
((uint8_t*)&value)[3] = (byte_array[byte_index]);
return value;
}
char * s7lib_parser_read_string(uint8_t * byte_array, int byte_index, uint8_t size)
{
uint8_t length = byte_array[byte_index + 1] > size ? size : byte_array[byte_index + 1];
char * string = malloc(sizeof(char)*length+1);
memset(string, 0, length+1);
strncpy(string, (char*) (byte_array+byte_index+2), length);
return string;
}
|
C
|
#include <stdio.h>
#include "Index.h"
#include <math.h>
/*
* Initializes the rectangle and assigns all the coordinates as 0
*/
void init_Rect(struct Rectangle* newRectangle)
{
register struct Rectangle* rectangleR = newRectangle;
for (int i=0;i<4;i++)
{
rectangleR->boundary[i]=(float)0;
}
}
/*
* Computes minimum value between two double variables
*/
float computeMinimum(double p1, double p2)
{
return p1<p2?p1:p2;
}
/*
* Computes maximum value between two double variables
*/
float computeMaximum(double p1, double p2)
{
return p1>p2?p1:p2;
}
/*
* Constructs a rectangle that can contain the passed two rectangles.
*/
struct Rectangle combineRect(struct Rectangle *R1, struct Rectangle *R2)
{
register struct Rectangle *r1 = R1, *r2=R2;
struct Rectangle new_rect;
new_rect.boundary[0] = computeMinimum(r1->boundary[0],r2->boundary[0]);
new_rect.boundary[1] = computeMinimum(r1->boundary[1],r2->boundary[1]);
new_rect.boundary[2] = computeMaximum(r1->boundary[2],r2->boundary[2]);
new_rect.boundary[3] = computeMaximum(r1->boundary[3],r2->boundary[3]);
return new_rect;
}
/*
* Returns 1 if the two rectangles overlap.
* Two rectangles do not overlap under the following conditions
* 1) One rectangle is on the left side of the left edge of other rectangle
* 2) One rectangle is above top edge of other rectangle
* Return 1 if either of the above conditions fail.
*/
int checkIfOverlaps(struct Rectangle *R1, struct Rectangle *R2)
{
register struct Rectangle *r1 = R1, *r2 = R2;
if(r1->boundary[0]>r2->boundary[2] || r2->boundary[0]>r1->boundary[2])
return 0;
if(r1->boundary[1]>r2->boundary[3] || r2->boundary[1]>r1->boundary[3])
return 0;
return 1;
}
/*
* Returns 1 if the index_rect is contained within window
*/
int isContained(struct Rectangle *index_rect, struct Rectangle *window)
{
register struct Rectangle *iR = index_rect, *w = window;
register int isXContained, isYContained;
isXContained = iR->boundary[0] >= w->boundary[0] && iR->boundary[2]<=w->boundary[2];
isYContained = iR->boundary[1] >= w->boundary[1] && iR->boundary[3]<=w->boundary[3];
return isXContained && isYContained;
}
/*
* Rectangle spherical volume is computed instead of area to remove zero width/length anomaly.
* Spherical volume [for 2 dimensions] = [pow(((x2-x1)/2),2) + pow(((y2-y1)/2),2)]*UnitSphericalVol(2)
* UnitSpherical(2) = 3.141593 [Precomputed]
*/
float rectSphericalVol(struct Rectangle *input_Rect)
{
register struct Rectangle *iR = input_Rect;
register double sumOfSquares=0;
double half_len = iR->boundary[2]-iR->boundary[0];
sumOfSquares += half_len*half_len;
half_len = iR->boundary[3]-iR->boundary[1];
sumOfSquares += half_len*half_len;
return (float)(sumOfSquares*3.141593);
}
void print_Rectangle(struct Rectangle *index_Rect, int depth)
{
register struct Rectangle *rR = index_Rect;
provideTabSpace(depth);
printf("rect:\n");
provideTabSpace(depth+1);
printf("%f\t%f\n", rR->boundary[0], rR->boundary[2]);
provideTabSpace(depth+1);
printf("%f\t%f\n", rR->boundary[1], rR->boundary[3]);
}
|
C
|
#include <stdio.h>
#include "test_helpers.h"
#include "dominion.h"
int main()
/*
test card adventurer
Reveal cards from your deck until you reveal 2 Treasure cards.
Put those Treasure cards into your hand and discard the other revealed cards.
*/
{
printf("Testing card: adventurer\n\n");
printf("Test with normal usage.\n");
struct gameState state;
int hand[] = {adventurer, -1};
int deck[] = {village, village, silver, gold, village, village, -1};
int discard[] = {-1};
initGameState(2, &state);
addCards(0, hand, deck, discard, &state);
asserttrue(state.handCount[0] == 1);
asserttrue(state.deckCount[0] == 6);
asserttrue(state.discardCount[0] == 0);
asserttrue(state.numActions == 1);
playCard(0, -1, -1, -1, &state);
printf("\nPlayed adventurer.\n\n");
debugGameState(0, &state);
asserttrue(state.handCount[0] == 2);
asserttrue(state.deckCount[0] == 4);
asserttrue(state.discardCount[0] == 2);
asserttrue(state.numActions == 0);
printf("\nTest with shuffle.\n");
int hand1[] = {adventurer, -1};
int deck1[] = {village, village, copper, village, village, -1};
int discard1[] = {gold, -1};
initGameState(2, &state);
addCards(0, hand1, deck1, discard1, &state);
asserttrue(state.handCount[0] == 1);
asserttrue(state.deckCount[0] == 5);
asserttrue(state.discardCount[0] == 1);
asserttrue(state.numActions == 1);
playCard(0, -1, -1, -1, &state);
printf("\nPlayed adventurer.\n\n");
debugGameState(0, &state);
asserttrue(state.handCount[0] == 2);
asserttrue(state.deckCount[0] == 4);
asserttrue(state.discardCount[0] == 2);
asserttrue(state.numActions == 0);
printf("\nTest without enough treasure.\n");
int hand2[] = {adventurer, -1};
int deck2[] = {village, village, village, village, -1};
int discard2[] = {gold, -1};
initGameState(2, &state);
addCards(0, hand2, deck2, discard2, &state);
asserttrue(state.handCount[0] == 1);
asserttrue(state.deckCount[0] == 4);
asserttrue(state.discardCount[0] == 1);
asserttrue(state.numActions == 1);
playCard(0, -1, -1, -1, &state);
printf("\nPlayed adventurer.\n\n");
debugGameState(0, &state);
asserttrue(state.handCount[0] == 1);
asserttrue(state.deckCount[0] == 4);
asserttrue(state.discardCount[0] == 2);
asserttrue(state.numActions == 0);
printf("\nadventurer tests done.\n\n");
}
|
C
|
#include <stdio.h>
int main(int argc, char *argv[])
{
int a=10;
int *p=&a;
printf("&a=0x%x\n",&a);
printf("p=0x%x\n", p);
printf("p+1=0x%x\n", p+1);
printf("&p=0x%x\n",&p);
printf("&p+1=0x%x\n",&p+1);
// printf("&(p+1)=0x%x\n",&(p+1));
return 0;
}
|
C
|
#include<bits/stdc++.h>
using namespace std;
string s;
int n;
int main()
{
int x=1;
while(1)
{
//memset(dp,-1,sizeof(dp));
cin>>s;
if(s[0]=='-')
break;
n=s.length();
int ans=0;
stack<char>st;
for(int i=0;i<n;i++)
{
if(st.empty()&&s[i]=='}')
{
ans++;
st.push('{');
}
else if(s[i]=='{')
st.push('{');
else
st.pop();
}
ans+=(st.size()/2);
printf("%d. %d\n",x++,ans);
}
return 0;
}
|
C
|
/*====================================================================*
*
* void copyquote (SCAN * content, char buffer [], signed length);
*
* scan.h
*
* copy the current token to a user supplied buffer of specified
* length; the token is assumed to be enclosed in quotes of some
* kind which are discarded before the token is copied;
*
*. released 2005 by charles maier associates ltd. for public use;
*: compiled on debian gnu/linux with gcc 2.95 compiler;
*; licensed under the gnu public license version two;
*
*--------------------------------------------------------------------*/
#ifndef COPYQUOTE_SOURCE
#define COPYQUOTE_SOURCE
# include "../scan/scan.h"
void copyquote (SCAN * content, char buffer [], signed length)
{
content->first++;
content->final--;
copytoken (content, buffer, length);
content->first--;
content->final++;
return;
}
#endif
|
C
|
#include <string.h>
#include <stdlib.h>
int startX, startY;
int goalX, goalY;
int head, tail;
bool visited[MAP_HEIGHT][MAP_WIDTH];
//y, x,parent, manhattendistance, distance from start
int queue[MAP_HEIGHT*MAP_WIDTH][5];
struct Node {
int x;
int y;
};
void reset() {
for (int y = 0; y < MAP_HEIGHT; y++)
for (int x = 0; x < MAP_WIDTH; x++)
visited[y][x] = false;
}
void findStart(int **map) {
for (int y = 0; y < MAP_HEIGHT; y++)
for (int x = 0; x < MAP_WIDTH; x++)
{
if (map[y][x] == 2)
{
startX = x;
startY = y;
map[y][x] = 5;
break;
}
}
}
void findGoal(int **map) {
for (int y = 0; y < MAP_HEIGHT; y++)
for (int x = 0; x < MAP_WIDTH; x++)
{
if (map[y][x] == 3)
{
goalX = x;
goalY = y;
return;
}
}
}
bool isValid(int **map, int x, int y) {
if (x < 0 || x > MAP_WIDTH - 1 || y < 0 || y > MAP_HEIGHT - 1)
return false;
else if (map[y][x] == 0 || map[y][x] == 3)
return true;
else {
visited[y][x] = true;
return false;
}
}
int ManhattenDistance(Node n) {
int nx = n.x, ny = n.y;
int md = 0;
if (nx > goalX)
md += nx - goalX;
else
md += goalX - nx;
if (ny > goalY)
md += ny - goalY;
else
md += goalY - ny;
return md;
}
void initializeQueue() {
Node n;
n.x = startX;
n.y = startY;
queue[0][0] = startY;
queue[0][1] = startX;
queue[0][2] = -1;
queue[0][3] = ManhattenDistance(n);
queue[0][4] = 0;
}
int min(int num1, int num2) {
if (num1 < num2)
return num1;
else if (num2 < num1)
return num2;
else
return num1;
}
int TieBreak(int index1, int index2) {
if (queue[index1][1] == queue[index2][1])
return ((queue[index1][0] < queue[index2][0]) ? index1 : index2);
else
return ((min(queue[index1][1], queue[index2][1]) == queue[index1][1]) ? index1 : index2);
}
Node expand(int x, int y, int index) {
int tempx = x, tempy = y;
switch (index) {
case 0:
tempx = x + 1;
break;
case 1:
tempy = y + 1;
break;
case 2:
tempx = x - 1;
break;
case 3:
tempy = y - 1;
break;
}
Node n;
n.x = tempx;
n.y = tempy;
return n;
}
int ScanFrontier() {
int minIndex = 0;
int currIndex = 0;
int minMD = queue[currIndex][3];
int currX = queue[currIndex][1], currY = queue[currIndex][0];
bool minFound = false;
while (currIndex < tail) {
currX = queue[currIndex][1];
currY = queue[currIndex][0];
if (!visited[currY][currX]) {
if (queue[currIndex][3] < minMD)
{
minIndex = currIndex;
minMD = queue[minIndex][3];
}
else if (queue[currIndex][3] == minMD) {
minIndex = TieBreak(minIndex, currIndex);
minMD = queue[minIndex][3];
}
if (!minFound) {
minIndex = currIndex;
minMD = queue[minIndex][3];
}
minFound = true;
}
currIndex++;
}
if (!minFound) {
minIndex = tail;
}
return minIndex;
}
bool astar(int **map) {
bool found = false;
head = 0;
tail = 1;
int currX = startX, currY = startY;
int currIndex = 0; //Track the curr index of the frontier
int md;
int iterations = 0;
while (!found && currIndex < tail) {
//set current
currY = queue[currIndex][0];
currX = queue[currIndex][1];
md = queue[currIndex][4];
//check goal
if (map[currY][currX] == 3) {
found = true;
break;
}
//Update map and visited
map[currY][currX] = 4;
visited[currY][currX] = true;
//Expand the current node
for (int i = 0; i < 4; i++) {
Node n = expand(currX, currY, i);
int nx = n.x, ny = n.y;
//Check for validity and redundancy
if (isValid(map, nx, ny) && !visited[ny][nx]) {
queue[tail][0] = ny;
queue[tail][1] = nx;
queue[tail][2] = currIndex;
queue[tail][3] = md + 1 + ManhattenDistance(n);
queue[tail][4] = md + 1;
tail++;
}
}
//Scan frontier for lowest
//Tie Break if necessary
//Update currIndex
currIndex = ScanFrontier();
}
//Change the path to be 5
if (found) {
while (queue[currIndex][2] != -1) {
currY = queue[currIndex][0];
currX = queue[currIndex][1];
map[currY][currX] = 5;
currIndex = queue[currIndex][2];
}
//Change starting position too (parent = -1)
map[startY][startX] = 5;
}
return found;
}
bool astar_search(int **map)
{
bool found = false;
// PUT YOUR CODE HERE
// access the map using "map[y][x]"
// y between 0 and MAP_HEIGHT-1
// x between 0 and MAP_WIDTH-1
reset();
findStart(map);
findGoal(map);
initializeQueue();
return astar(map);
}
|
C
|
/*
** EPITECH PROJECT, 2020
** CPE_lemin_2019
** File description:
** GEt nb of rooms
*/
#include "lemin.h"
size_t get_nb_rooms(char ***array3d)
{
size_t nb_rooms = 0;
for (size_t i = 0; array3d[i]; i++) {
if (word_array_len(array3d[i]) == 3)
nb_rooms++;
}
return nb_rooms;
}
|
C
|
#include<stdio.h>
int main()
{
int N,i,j=1,sum=0,cnt=0,flag=0;
int Number[1001]={0};
double A[6]={0};
scanf("%d",&N);
for(i=0;i<N;i++)
{
scanf("%d",&Number[i]);
}
for(i=0;i<N;i++)
{
switch(Number[i]%5)
{
case 0:
if(Number[i]%2==0)
{
A[1]+=Number[i];
}
break;
case 1:
A[2]+=j*Number[i];/*A[2]=0һҪNҪһflag¼*/
j*=-1;
flag++;
break;
case 2:
A[3]++;
break;
case 3:
sum+=Number[i];
cnt++;
break;
case 4:
if(Number[i]>A[5]){
A[5]=Number[i];
}
break;
}
}
if(cnt!=0)/*˴ж׳*/
{
A[4]=sum/(double)cnt;
}
for(i=1;i<6;i++)
{
if(i==2)
{
if(flag==0)
{
printf("N");
}else
{
printf("%d",(int)(A[i]));
}
}else if(i==4)
{
if(A[i]==0)
{
printf("N");
}else
{
printf("%0.1f",A[i]);
}
}else
{
if(A[i]==0)
{
printf("N");
}else
{
printf("%d",(int)(A[i]));
}
}
if(i!=5)
{
printf(" ");
}
}
// for(i=1;i<6;i++)
// {
// if(A[i]==0)
// {
// printf("N");
// }else
// {
// if(i==4)
// {
// printf("%0.1f",A[i]);
// }elseif(i==2)
// {
// if()
// }else
// {
// printf("%d",(int)(A[i]));
// }
// }
// if(i!=5){
// printf(" ");
// }
// }
return 0;
}
|
C
|
/* declaration de fonctionnalites supplementaires */
#include <stdlib.h> /* EXIT_SUCCESS */
#include <stdio.h> /* printf */
/* declaration constantes et types utilisateurs */
/* declaration de fonctions utilisateurs */
/* fonction principale */
int main()
{
/* declaration et initialisation variables */
int age = 16; /* age de la personne */
if(age >= 18) /* majeur */
{
/* affiche majeur */
printf("Vous tes majeur.\n");
}
else /* mineur */
{
/* affiche mineur */
printf("Vous tes mineur.\n");
}
/* retour fonction */
return EXIT_SUCCESS; /* renvoie OK */
}
/* definitions des fonctions utilisateurs */
|
C
|
/*
*堆栈的链表方式实现
×
*/
#ifndef _STACK_LINKED_LIST_H_
#define _STACK_LINKED_LIST_H_
#define ERROR -1
#define SUCCESS 0
#include <malloc.h>
typedef int ElementType;
typedef struct SNode * Stack;
struct SNode{
ElementType Data;
Stack Next;
};
Stack CreateStack();
int Push(Stack S,ElementType x);
ElementType Pop(Stack S);
int IsEmpty(Stack S);//return 1 is empty
Stack CreateStack(){
Stack S=(Stack)malloc(sizeof(struct SNode));
S->Next=NULL;
return S;
}
int Push(Stack S,ElementType x){
Stack p=(Stack)malloc(sizeof(struct SNode));
if(p==NULL) return ERROR;
else{
p->Data=x;
p->Next=S;
S=p;
return SUCCESS;
}
}
ElementType Pop(Stack S){
if(IsEmpty(S)) return NULL;//如果堆栈S空 返回NULL
Stack p=S;
ElementType Temp=p->Data;
S=S->Next;
free(p);
return Temp;
}
int IsEmpty(Stack S){
return S->Next==NULL;
}
#endif
|
C
|
/*
** EPITECH PROJECT, 2021
** copy_tab.c
** File description:
** copy_tab function
*/
#include "../../include/my.h"
#include <stdlib.h>
char **copy_tab(char **tab)
{
char **tab_cpy;
int len = 0;
for (; tab[len]; len++);
tab_cpy = malloc(sizeof(char*) * (len + 1));
for (int i = 0; i < len; i++)
tab_cpy[i] = my_strdup(tab[i]);
tab_cpy[len] = NULL;
return (tab_cpy);
}
|
C
|
#include "holberton.h"
#include <stdio.h>
/**
*print_diagsums - prints the sum of the two diagonals of a square matrix
*
*@a: pointer that contains the address of the beginning of the matrix
*@size: size of the square matrix
*
*Return: nothing
*/
void print_diagsums(int *a, int size)
{
int i, j;
int d1 = 0, d2 = 0;
for (i = 0; i < size * size; i = i + (size + 1))
{
d1 = d1 + a[i];
}
for (j = size - 1; j < size * size - 1; j = j + (size - 1))
{
d2 = d2 + a[j];
}
printf("%d, %d\n", d1, d2);
}
|
C
|
#ifndef _DIRECTORY_H_
#define _DIRECTORY_H_
#include <time.h>
#include "../file/file.h"
#include "../utils/utils.h"
typedef struct directory {
char* name;
char* fullpath; // caminho completo do diretório
struct directory* preview; // diretório irmão anterior
struct directory* next; // próximo diretório irmão
struct directory* father; // diretório pai
struct directory* sub_dirs; // diretórios filhos
struct file* files; // arquivos presentes no diretório
struct tm creation_time; // data de criação do diretório
} Directory;
// Inicializa o diretório root e faz wd apontar para seu endereço
void init(void);
// Retorna uma cópia do diretório root
Directory get_root_dir(void);
// Retorna referência para o diretório atual (working directory)
Directory* pwd(void);
// Aloca espaço na memória para conter uma struct Directory
Directory* alloc_directory(const char* name);
// Simula um mkdir, ou seja, cria um novo diretório no 'wd' atual
ret_t mkdir(const char* pathname);
// Muda o diretório atual para o passado via parâmetro
ret_t cd(const char* pathname);
// Remove os diretório do caminho passado. Se o diretório não estiver vazio, pergunta se deve remover os outros elementos
ret_t rmdir(const char* pathname);
#endif // _DIRECTORY_H_
|
C
|
/*
************ RANDOM.H ***********
This include file contains routines for getting a uniformly distributed
random variable in the interval [0,1], a gaussian
distributed random variable with zero mean and unity variance,
an exponential distributed random variable, and a
and a cauchy distributed random variable with
To use them (x & y declared as floats),
x = uniform(&idum);
y = normal(&idum);
z = cauchy(&idum);
u = expdev(&idum);
Notice that a pointer to "idum" is used.
The file also contains routines for getting uniformly
generated integers over specified intervals.
Before you use any of these routines, you must initialize
the long variable "idum" (declared in this file). To do this
you must include in your main program the following:
#include <time.h>
int main(void )
{
.
.
.
srand((unsigned) time(NULL));
idum = -rand();
}
*/
#include <math.h>
#define IA 16807
#define IM 2147483647
#define AM (1.0/IM)
#define IQ 127773
#define IR 2836
#define NTAB 32
#define NDIV (1+(IM-1)/NTAB)
#define EPSILON 1.2e-7
#define RNMX (1.0-EPSILON)
//random between 0 and 1
float uniform(long *idum);
float normal(long *idum);
float expdev(long *idum);
/* gives cachy r.v. centered about 0 with pdf
f(x) = 1/(pi*(1+x*x)). */
double cauchy(long *idum);
/* returns a random integer in the interval [0,n-1] */
int r0n(int n);
/* returns a random integer in the interval [n,m] */
int rnm(int n, int m);
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* create_bitmap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ajeannot <ajeannot@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/07 11:23:09 by ajeannot #+# #+# */
/* Updated: 2020/02/08 18:46:07 by ajeannot ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/cub3d.h"
void set_bitmap_header(int fd, int bmp_size, int totalheader_size)
{
write(fd, "BM", 2);
write(fd, &bmp_size, 4);
write(fd, "\0\0\0\0", 4);
write(fd, &totalheader_size, 4);
}
void set_bitmap_infoheader(int fd, int infoheader_size)
{
int planes;
int cmp;
cmp = 0;
planes = 1;
write(fd, &infoheader_size, 4);
write(fd, &g_win->width, 4);
write(fd, &g_win->height, 4);
write(fd, &planes, 2);
write(fd, &g_img->bpp, 2);
while (cmp < 28)
{
write(fd, "\0", 1);
cmp++;
}
}
void set_data_bitmap(int fd)
{
int cmp;
int cmp_w;
cmp = g_win->width * g_win->height + 1;
while (cmp >= 0)
{
cmp_w = 0;
cmp = cmp - g_win->width;
while (cmp_w < g_win->width)
{
write(fd, &g_img->data[cmp * g_img->bpp / 8], 4);
cmp_w++;
cmp++;
}
cmp = cmp - g_win->width;
}
}
void create_bitmap(void)
{
int fd;
int bmp_size;
int header_size;
int infoheader_size;
int totalheader_size;
fd = open("save.bmp", O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU);
header_size = 14;
infoheader_size = 40;
totalheader_size = header_size + infoheader_size;
bmp_size = totalheader_size + (g_win->width * g_win->height * 4);
set_bitmap_header(fd, bmp_size, totalheader_size);
set_bitmap_infoheader(fd, infoheader_size);
set_data_bitmap(fd);
close(fd);
exit_game(NULL);
}
|
C
|
/*****************************************************
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
*******************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int firstMissingPositive(int* nums, int numsSize)
{
int i, tmp;
for(i = 0; i < numsSize; i++)
{
tmp = nums[i];
while(tmp != i+1)
{
if(tmp > numsSize || tmp < 1 || tmp == nums[tmp-1])
{
nums[i] = 0;
break;
}
nums[i] = nums[tmp-1];
nums[tmp-1] = tmp;
tmp = nums[i];
}
}
for(i = 0; i < numsSize; i++)
{
if(nums[i] == 0) return i+1;
}
return numsSize+1;
}
int main()
{
int set[] = {3, 4, -1, 1};
printf("first missing positive is %d\n",
firstMissingPositive(set, sizeof(set)/sizeof(int)));
}
|
C
|
#pragma once
#include <stdint.h>
static inline uint32_t bswap16(uint16_t val) {
return ((val & 0xff00) >> 8) |
((val & 0x00ff) << 8);
}
static inline uint32_t bswap32(uint32_t val) {
return ((val & 0xff000000) >> 24) |
((val & 0x00ff0000) >> 8) |
((val & 0x0000ff00) << 8) |
((val & 0x000000ff) << 24);
}
static inline uint64_t bswap64(uint64_t val) {
return ((val & 0x00000000000000ffULL) << 56) |
((val & 0x000000000000ff00ULL) << 40) |
((val & 0x0000000000ff0000ULL) << 24) |
((val & 0x00000000ff000000ULL) << 8) |
((val & 0x000000ff00000000ULL) >> 8) |
((val & 0x0000ff0000000000ULL) >> 24) |
((val & 0x00ff000000000000ULL) >> 40) |
((val & 0xff00000000000000ULL) >> 56);
}
static inline uint16_t get_be16(const void *src) {
const unsigned char *p = src;
return p[0] << 8 |
p[1] << 0;
}
static inline uint32_t get_be32(const void *src) {
const unsigned char *p = src;
return p[0] << 24 |
p[1] << 16 |
p[2] << 8 |
p[3] << 0;
}
static inline uint64_t get_be64(const void *src) {
const unsigned char *p = src;
return (uint64_t) get_be32(p + 0) << 32 |
(uint64_t) get_be32(p + 4) << 0;
}
static inline void put_be32(void *dst, uint32_t val) {
unsigned char *p = dst;
p[0] = val >> 24;
p[1] = val >> 16;
p[2] = val >> 8;
p[3] = val >> 0;
}
static inline void put_be64(void *dst, uint64_t val) {
unsigned char *p = dst;
p[0] = val >> 56;
p[1] = val >> 48;
p[2] = val >> 40;
p[3] = val >> 32;
p[4] = val >> 24;
p[5] = val >> 16;
p[6] = val >> 8;
p[7] = val >> 0;
}
# if defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN || \
defined(__BIG_ENDIAN__) || \
defined(__ARMEB__) || \
defined(__THUMBEB__) || \
defined(__AARCH64EB__) || \
defined(_MIBSEB) || defined(__MIBSEB) || defined(__MIBSEB__)
# define BIG_ENDIAN
# elif defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN || \
defined(__LITTLE_ENDIAN__) || \
defined(__ARMEL__) || \
defined(__THUMBEL__) || \
defined(__AARCH64EL__) || \
defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__)
# define LITTLE_ENDIAN
# else
# error "Cannot determine endianness!"
# endif
# if defined(BIG_ENDIAN) && !defined(LITTLE_ENDIAN)
# define ntohl(n) (n)
# define htonl(n) (n)
# define ntohll(n) (n)
# define htonll(n) (n)
# elif defined(LITTLE_ENDIAN) && !defined(BIG_ENDIAN)
# define ntohl(n) bswap32(n)
# define htonl(n) bswap32(n)
# define ntohll(n) bswap64(n)
# define htonll(n) bswap64(n)
# endif
|
C
|
// Created by Kyle Goodale. See header for details
#include "processControlBlock.h"
#include "memory.h"
#include <stddef.h>
#include <stdlib.h>
#include <printf.h>
int ProcessCount = 0; // How many processes we currently have
const int MAX_PROCESSES = 10;
const int MAX_MEM_PER_PROC = 100; // How many lines each process gets in main memory
// The PCBNode struct is just a wrapper around the PCB struct that contains a link to the next PCB.
// We use a separate struct because we shouldn't and don't need to expose that externally.
typedef struct PCBNode PCBNode;
struct PCBNode {
PCBNode *NextPCB;
PCB *pcb;
} ;
// The head and Tail of our PCB linked list
PCBNode *PCBListHead = NULL;
// Find the node and remove it and set its previous node to the current nodes next, 0 on success, -1 on not found
int removePCBNode( int PID ){
struct PCBNode *CurrentNode = PCBListHead;
struct PCBNode *PreviousNode = NULL;
while( CurrentNode != NULL ) {
if( CurrentNode->pcb->PID == PID ){
// Update the previous node if it exists
if( PreviousNode != NULL ) {
PreviousNode->NextPCB = CurrentNode->NextPCB;
}
// Free our memory
destroyPCB( CurrentNode->pcb );
free( CurrentNode );
return 0;
}
PreviousNode = CurrentNode;
CurrentNode = CurrentNode->NextPCB;
}
return -1; // PCB with that PID not found
}
PCB *getPCB( int PID ){
struct PCBNode *CurrentNode = PCBListHead;
while( CurrentNode != NULL ) {
if( CurrentNode->pcb->PID == PID ){
return CurrentNode->pcb;
}
CurrentNode = CurrentNode->NextPCB;
}
return NULL; // PCB with that PID not found
}
// Creates a new pcb and pcbnode and adds it to the linked list
int newPCB() {
if( ProcessCount == MAX_PROCESSES ) {
printf("Error: Max process count exceeded. A maximum of %i programs may be loaded at once.\n", MAX_PROCESSES);
return -1;
}
ProcessCount++;
// Create the PCBNode that will contain the PCB in our linked list
PCBNode *NewPCBNode;
NewPCBNode = ( PCBNode * ) malloc( sizeof( PCBNode ) );
// Initialize the new PCB with default data
PCB *NewPCB;
NewPCB = ( PCB * ) malloc( sizeof( PCB ) );
NewPCB->PID = ProcessCount;
NewPCB->PC = 0;
NewPCB->R0, NewPCB->R1, NewPCB->R2, NewPCB->R3 = 0;
NewPCB->P0, NewPCB->P1, NewPCB->P2, NewPCB->P3 = 0;
NewPCB->BaseReg = MAX_MEM_PER_PROC * (ProcessCount-1); // Each program gets 100 lines of memory
NewPCB->LimitReg = NewPCB->BaseReg + MAX_MEM_PER_PROC - 1;
// Add the PCB to the node
NewPCBNode->pcb = NewPCB;
NewPCBNode->NextPCB = NULL;
// Insert our node into the end of the linked list
if( PCBListHead == NULL ){ // This is the first element
PCBListHead = NewPCBNode;
} else {
PCBNode *CurrentPCBNode = PCBListHead;
while (CurrentPCBNode->NextPCB != NULL) {
CurrentPCBNode = CurrentPCBNode->NextPCB;
}
CurrentPCBNode->NextPCB = NewPCBNode;
}
return NewPCB->PID;
}
static void destroyPCB( PCB* targetPCB ){
_memoryClearBlock( targetPCB->BaseReg, MAX_MEM_PER_PROC );
free( targetPCB );
}
|
C
|
/*
** EPITECH PROJECT, 2018
** CPE_BSQ_bootstrap_22018
** File description:
** load a content of a file and put it in memory
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include "./../include/my.h"
#include "./../include/bootstrap.h"
char *load_file_in_mem(char const *filepath)
{
int fd = fs_open_file(filepath);
struct stat *size = malloc(sizeof(*size));
char *file_content;
stat(filepath, size);
file_content = malloc(sizeof(char) * (size->st_size + 1));
my_memset(file_content, '~', (size->st_size - 1));
file_content[size->st_size] = '\0';
read(fd, file_content, size->st_size);
file_content[size->st_size] = '\0';
close(fd);
free(size);
return (file_content);
}
int set_at_map(char const *str)
{
int i = 0;
while (str[i] != '\n') {
i = i + 1;
}
return (i + 1);
}
char **load_2d_arr_from_file(position_t *position)
{
index_t *index = malloc(sizeof(*index));
char **tab = mem_alloc_2d_array(position->y_max, position->x_max);
int i = set_at_map(position->str);
index->rows = 0;
index->cols = 0;
while (position->str[i] != '\0') {
if (position->str[i] == '\n') {
tab[index->rows][index->cols] = '\0';
index->rows = index->rows + 1;
index->cols = 0;
} else {
c_filter(position->str[i]);
tab[index->rows][index->cols] = position->str[i];
index->cols = index->cols + 1;
}
i = i + 1;
}
return (tab);
}
int is_square_of_size(position_t *position, index_t *index, int square_size)
{
int i_col = index->cols;
int i_row = index->rows;
int const col_max = index->cols + square_size;
int const row_max = index->rows + square_size;
if ((row_max) >= position->y_max)
return (0);
if ((col_max) >= position->x_max)
return (0);
while (i_row <= row_max && position->map[i_row] != NULL) {
while (i_col <= col_max && position->map[i_row][i_col] == '.') {
i_col = i_col + 1;
}
if (position->map[i_row][i_col] != '.')
return (0);
i_row = i_row + 1;
i_col = index->cols;
}
return (1);
}
position_t *draw_the_square(position_t *position, res_t *res)
{
int i_col = res->col;
int i_row = res->row;
int const col_max = res->col + res->size;
int const row_max = res->row + res->size;
if (res->size < 2) {
if (position->x_max != 1 && position->y_max != 1) {
return (position);
}
}
while (i_row <= row_max) {
while (i_col <= col_max) {
position->map[i_row][i_col] = 'x';
i_col = i_col + 1;
}
i_row = i_row + 1;
i_col = res->col;
}
return (position);
}
|
C
|
#include<stdio.h>
int main(){
float a,b=50.0,c=1.0,s=0.0;
for (a=0;a<=2;a++)
{
if (a>0)
c*=2;
s+=(1+2*a)/c;
}
printf("The sum of the numbers is %f",s);
return 0;
}
|
C
|
#include <stdio.h>
#define xcat(x,y) x##y
#define xxcat(x,y) cat(x,y)
int main()
{
int a = (xcat(xcat(3, 0), xcat(2, 0)));
printf("a");
return 0;
}
|
C
|
#pragma once
typedef unsigned long DWORD;
typedef unsigned int UINT;
struct TriMeshFace
{
TriMeshFace() {}
TriMeshFace(DWORD I0, DWORD I1, DWORD I2)
{
I[0] = I0;
I[1] = I1;
I[2] = I2;
}
DWORD I[3];
};
struct GRIDCELL {
Vec3 p[8]; //position of each corner of the grid in world space
float val[8]; //value of the function at this grid corner
};
//given a grid cell, returns the set of triangles that approximates the region where val == 0.
/*
Given a grid cell and an isolevel, calculate the triangular
facets required to represent the isosurface through the cell.
Return the number of triangular facets, the array "triangles"
will be loaded up with the vertices at most 5 triangular facets.
0 will be returned if the grid cell is either totally above
of totally below the isolevel.
*/
int Polygonise(GRIDCELL& Grid, TriMeshFace* Triangles, int& NewVertexCount, Vec3* Vertices);
/*
Linearly interpolate the position where an isosurface cuts
an edge between two vertices, each with their own scalar value
*/
static Vec3 VertexInterp(Vec3& p1, Vec3& p2, float valp1, float valp2)
{
return p1 + (p2.subtract(p1)).multiply(valp1 / (valp1 - valp2));
}
|
C
|
#include "assets/colour/colour.h"
STATUS_CODE game_surface__init(Game* game)
{
SDL_Color bg_colour = BG_COLOUR;
#if SDL_BYTEORDER == SDL_BIGENDIAN
#endif
u32 bg_bitmask = (bg_colour.a | (bg_colour.r << 16) | (bg_color.g << 8) | bg_color.b)
if (SDL_MUSTLOCK(game_surface)) {
if (SDL_LockSurface(game_surface) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to lock game surface: %s\n", SDL_GetError());
return SURFACE_FAILURE_CODE;
}
}
for (int game_surface_row = 0; game_surface_row < game_width; ++game_surface_row) {
game_surface_pixel = (u32 *)((u8 *)(game_surface_pixels) + game_surface_row * game_surface_pitch);
for (int game_surface_col = 0; game_surface_col < game_height; ++game_surface_col) {
if (UBORDER_COLLISION(game_surface_row, game_surface_col)) {
*game_surface_pixel++ = bg_bitmask;
}
}
}
if (SDL_MUSTLOCK(game_surface)) {
SDL_UnlockSurface(game_surface);
}
return SUCCESS_CODE;
}
INTERNAL STATUS_CODE game__set_surface_pixel_colour(SDL_Surface* game_surface, int x, int y, SDL_Color* colour)
{
if (ASSERT_IF(game_surface != NULL && colour != NULL, "Null parameters")) {
return INVALID_ARGUMENTS;
}
if (SDL_MUSTLOCK(game_surface)) {
if (SDL_LockSurface(game_surface) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to lock game surface: %s\n", SDL_GetError());
return SURFACE_FAILURE_CODE;
}
}
u8* surface_pixel = (u8 *)game_surface->pixels;
surface_pixel += (y * game_surface->pitch) + (x * sizeof(u8));
*surface_pixel = (colour->a | (colour->r << 16) | (colour->g << 8) | (colour->b));
if (SDL_MUSTLOCK(game_surface)) {
SDL_UnlockSurface(game_surface);
}
return SUCCESS_CODE;
}
|
C
|
//
// Created by hugbr on 2016/1/21.
//
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}Qnode;
typedef struct queue{
Qnode *begin,*end;
}Queue;
Queue * init(){
Queue *q = malloc(sizeof(Queue));
Qnode *t = malloc(sizeof(Qnode));
t->next = NULL;
q->begin = t;
q->end = t;
return q;
}
int isEmpty(Queue *q){
if(q->begin ==q->end){
printf("waring-------Ϊ!!!\n");
return 1;
} else return 0;
}
int push(Queue *q,int x){
Qnode *n = malloc(sizeof(Qnode));
n->data = x;
n->next = NULL;
q->end->next = n;
q->end = n;
printf("%d\n",x);
return 1;
}
int pop(Queue *q,int *x){
if(isEmpty(q)) return 0;
else{
*x = q->begin->next->data;
q->begin->next = q->begin->next->next;
printf("%d\n",*x);
return 1;
}
}
void show(Queue *q){
isEmpty(q);
Qnode *n;
int i=1;
n = q->begin->next;
while (n!=NULL){
printf("еĵ%dԪΪ%d\n",i++,n->data);
n = n->next;
}
}
main(){
printf("-------------\nгʼ\n");
Queue *q = init();
printf("-------------\nʼɹ\n");
int x;
printf("\n");
scanf("%d",&x);
while (x!=0){
push(q,x);
scanf("%d",&x);
}
show(q);
pop(q,&x);
pop(q,&x);
show(q);
printf("\n");
scanf("%d",&x);
while (x!=0){
push(q,x);
scanf("%d",&x);
}
show(q);
pop(q,&x);
show(q);
}
|
C
|
//******************************************************************************
// MSP430FR69xx Demo - eUSCI_B0 I2C Master TX bytes to Multiple Slaves
//
// Description: This demo connects two MSP430's via the I2C bus.
// The master transmits and receive data via I2C to / from slave addresses 0x02
// This is a master code.
//
// IIC_TX is to send one byte to motor board to control the rotation direction and speed.
// The most significant 4 bit is for direction control
// 0 - stop
// 1 - anti-clockwise
// 2 - clockwise
// 3 - reset motor rotation counter
//
// The Least significant 4 bit is to control the rotation speed of motor
// form 0000 to 1111
//
// IIC_RX is to receive two bytes of data from slave
// This two bytes tell the number (int format) of rotation of motor.
// The first byte is the low byte
// The second byte is the upper byte of an integer
//
// ACLK = n/a, MCLK = SMCLK = DCO = 4MHz
//
//
// /|\ /|\
// MSP430G2553 10k 10k MSP430FR6989
// slave | | master
// ----------------- | | -----------------
// -|XIN P1.6/UCB0SDA|<-|----+->|P1.6/UCB0SDA XIN|-
// | | | | |
// -|XOUT | | | XOUT|-
// | P1.7/UCB0SCL|<-+------>|P1.7/UCB0SCL |
// | | | |
//
//******************************************************************************
#include "msp430FR6989.h"
#include "IIC.h"
unsigned char TXData[5];
volatile unsigned char TXByteCtr;
volatile unsigned char RXByteCtr;
void Set_IIC_Timeout()
{
TA1CTL = TASSEL__ACLK ;
TA1CCTL0 = CCIE; // TACCR0 interrupt enabled
TA1CCR0 = 32768;
}
void Set_IIC()
{
Set_IIC_Timeout();
// Configure GPIO
P1SEL0 |= BIT6 | BIT7; // I2C pins
// Configure USCI_B0 for I2C mode
UCB0CTLW0 = UCSWRST; // put eUSCI_B in reset state
UCB0CTLW0 |= UCMODE_3 | UCSYNC | UCMST | UCSSEL__SMCLK;
// I2C master mode, SMCLK
UCB0CTLW1 |= UCASTP_2 | UCCLTO_3; // Automatic stop generated,
// after UCB0TBCNT is reached
UCB0BRW = 0x0010; // baudrate = SMCLK / 16
UCB0TBCNT = 0x0002; // number of bytes to be received
UCB0I2CSA = Slave_Add;
UCB0CTLW0 &= ~UCSWRST; // clear reset register
UCB0IE |= UCTXIE | UCRXIE | UCSTPIE | UCNACKIE | UCCLTOIE; // Enable interrupts
RXByteCtr = 0;
}
void IIC_TX(unsigned char Data)
{
UCB0TBCNT = 0x0001; // number of bytes to be received
TXByteCtr = 0; // Load TX byte counter
TXData[0] = Data;
while (UCB0CTLW0 & UCTXSTP); // Ensure stop condition got sent
UCB0CTLW0 |= UCTR | UCTXSTT; // I2C TX, start condition
TA1CTL |= TACLR;
TA1CTL |= MC_1;
__bis_SR_register(LPM0_bits | GIE); // Enter LPM0 w/ interrupts
// Remain in LPM0 until all data
// is TX'd
TA1CTL &= ~MC_1;
}
void IIC_RX()
{
UCB0TBCNT = 0x0002; // number of bytes to be received
RXByteCtr = 0;
while (UCB0CTL1 & UCTXSTP); // Ensure stop condition got sent
UCB0CTLW0 &= ~UCTR;
UCB0CTLW0 |= UCTXSTT; // I2C RX, start condition
TA1CTL |= TACLR;
TA1CTL |= MC_1;
__bis_SR_register(LPM0_bits | GIE); // Enter LPM0 w/ interrupts
// Remain in LPM0 until all data
TA1CTL &= ~MC_1;
}
#pragma vector = USCI_B0_VECTOR
__interrupt void USCI_B0_ISR(void)
{
switch(__even_in_range(UCB0IV, USCI_I2C_UCBIT9IFG))
{
case USCI_NONE: break; // Vector 0: No interrupts
case USCI_I2C_UCALIFG: break; // Vector 2: ALIFG
case USCI_I2C_UCNACKIFG: // Vector 4: NACKIFG
// UCB0CTLW0 |= UCTXSTT; // resend start if NACK
Set_IIC(); // Reset I2C
__bic_SR_register_on_exit(LPM0_bits ); // Exit LPM0
break;
case USCI_I2C_UCSTTIFG: break; // Vector 6: STTIFG
case USCI_I2C_UCSTPIFG:
// Stop condition generated, I2C communication completed
__bic_SR_register_on_exit(LPM0_bits ); // Exit LPM0
break; // Vector 8: STPIFG
case USCI_I2C_UCRXIFG3: break; // Vector 10: RXIFG3
case USCI_I2C_UCTXIFG3: break; // Vector 12: TXIFG3
case USCI_I2C_UCRXIFG2: break; // Vector 14: RXIFG2
case USCI_I2C_UCTXIFG2: break; // Vector 16: TXIFG2
case USCI_I2C_UCRXIFG1: break; // Vector 18: RXIFG1
case USCI_I2C_UCTXIFG1: break; // Vector 20: TXIFG1
case USCI_I2C_UCRXIFG0: // Vector 22: RXIFG0
{
Master_RXData[RXByteCtr] = UCB0RXBUF; // Get RX data
RXByteCtr++;
}
break;
case USCI_I2C_UCTXIFG0: // Vector 24: TXIFG0
UCB0TXBUF = TXData[TXByteCtr]; // Load TX buffer
TXByteCtr++;
break;
case USCI_I2C_UCBCNTIFG: break; // Vector 26: BCNTIFG
case USCI_I2C_UCCLTOIFG:
Set_IIC(); // reset IIC
__bic_SR_register_on_exit(LPM0_bits ); // Exit LPM0
break; // Vector 28: clock low timeout
case USCI_I2C_UCBIT9IFG: break; // Vector 30: 9th bit
default: break;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define M_PI 3.14159265358979323846
#define TWO_PI 6.2831853071795864769252866
#define c 0.817
#define Gmax 5000
#define error 0.00001
#define ranf() ((double)rand()/(1.0+(double)RAND_MAX)) //intervalo uniforme de [0,1)
#define e1(x1,x3) (((-1)*x1)+(0.0193*x3))
#define e2(x2,x3) (((-1)*x2)+(0.0095*x3))
#define e3(x3,x4) (1296000-((4/3)*M_PI*pow(x3,3))-(M_PI*pow(x3,2)*x4))
#define e4(x4) (x4-240)
double aleatorio(double,double);
double *vector(double *,int);
void inic_padre(double *,int);
double evaluarF(double*);
int restriccion(double *);
double genGausse(double, double);
double genGauss(double media, double desE)
{
double x1,x2,w,y1;
static double y2;
static int utiliza_ult=0;
if(utiliza_ult)
{
y1=y2;
utiliza_ult =0;
}
else
{
do{
x1 = 2.0 * ranf() - 1.0;
x2 = 2.0 * ranf() - 1.0;
w = x1 * x1 + x2 * x2;
} while ( w >= 1.0 );
w = sqrt( (-2.0 * log( w ) ) / w );
y1 = x1 * w;
y2 = x2 * w;
utiliza_ult =1;
}
return (media + y1 * desE);
}
double aleatorio(double min, double max)
{
double scaled = ranf();
return (max - min)*scaled + min;
}
double *vector(double *dato,int tam)
{
dato = (double*)malloc(tam*sizeof(double));
}
double evaluarF(double *x)
{
return ((0.6224*x[0]*x[2]*x[3])+(1.7781*x[1]*pow(x[2],2))+(3.1661*pow(x[0],2)*x[3])+((19.84*pow(x[0],2)*x[2])));
}
int restriccion(double *x)
{
if (e1(x[0],x[2])<=0 && e2(x[1],x[2])<=0 && e3(x[2],x[3])<=0 && e4(x[3])<=0)
{
return 1;
}
else
{
return 0;
}
}
void inic_padre(double * padre,int num_var)
{
int i;
for(i=0;i<num_var;i++)
{
if((i==0) || (i==1))
{
padre[i]=aleatorio(1.0,99.0)*0.0625;
}
else if ((i==2) || (i==3))
{
padre[i]=aleatorio(10.0,200.0);
}
}
}
int main()
{
double delta, *padre=NULL, *hijo=NULL, padreFunc, hijoFunc,num,aprox,*padres=NULL,**matr_Pad=NULL;
int t, num_var,i,x,ps, ve=0,mu;
t =0;
ps =0;
num_var =4;
delta = 10; //explorar mas el espacio de busqueda reproduccion
srand(time(0));
hijo=vector(hijo,num_var);
aprox =1;
mu= 10;
//formando el conjunto de padres
padres = vector(padres,mu);
matr_Pad=(double **) malloc (mu*sizeof(double*));
for (x=0;x<mu;x++)
{
int y;
double datosP;
matr_Pad[x] = vector(matr_Pad[x],num_var);
for(y=0;y<num_var;y++)
{
if((y==0) || (y==1))
{
datosP=aleatorio(1.0,99.0)*0.0625;
}
else if ((y==2) || (y==3))
{
datosP=aleatorio(10.0,200.0);
}
matr_Pad[x][y] = datosP; //se evalua la funcion
}
padres[x]=evaluarF(matr_Pad[x]);
}
while((t<Gmax) && (aprox>error))
{
printf("--- Iteracion Numero %d ---\n",t+1);
//evaluar soluciones
int y, num_ale=0,num_ale2=0, x=0, pos=0,s,opt;
for (x=0;x<mu;x++)
{
for (y=0;y<num_var;y++)
{
printf("%f ",matr_Pad[x][y]);
}
printf("%f\n",padres[x]);
}
/*se esscogen 2 sol aleatorias*/
do
{
num_ale = rand()%(10);
num_ale2 = rand()%(10);
if (num_ale ==num_ale2)
{
x=1;
}
else
{
x=0;
}
}
while(x==1);
//printf("--%d --%d\n",num_ale,num_ale2);
for(i=0;i<num_var;i++){
num=genGauss(0,11);//semilla de aleatorios
//hijo[i]=padre[i]+delta*num; // mutando el vector
hijo[i]= ((matr_Pad[num_ale][i]+matr_Pad[num_ale2][i])/2)+delta*num; // mutando el vector
/* printf(" Delta: %f Aleatorio: %f \n",delta,num);
printf(" Padre %d : %f \n",i+1,padre[i]);*/
printf(" Hijo %d : %f \n",i+1,hijo[i]);
}
hijoFunc=evaluarF(hijo);
printf("%f %d",hijoFunc,restriccion(hijo));
for(s=1;s<mu;s++)
{
if (padres[0]<padres[s])
{
pos=s;
}
}
for(s=1;s<mu;s++)
{
if (padres[0]>padres[s])
{
opt=s;
}
}
//buscando al mejor de los padres
printf("\n----%d \n",opt);
//cambiando por la peor solucion
for(i=0;i<num_var;i++)
{
matr_Pad[pos][i]=hijo[i];
}
aprox=fabs(padres[opt]-hijoFunc);
if(hijoFunc<padres[opt])
{
ps++;
}
padres[pos]=hijoFunc;
printf(" Error: %f \n",aprox);
/*printf(" Evaluacion padre: %f \n",padreFunc);
printf(" Evaluacion hijo: %f \n",hijoFunc);
aprox=fabs(padreFunc-hijoFunc);
printf(" Error: %f \n",aprox);
//printf("%f,%f",hijoFunc,padreFunc);*/
/*if (restriccion(hijo)==0 && restriccion(padre)==0)
{
//printf("mejor actitud");
if(hijoFunc<padreFunc)
{
printf(" HIJO SUSTITUYO AL PADRE \n");
for(i=0;i<num_var;i++)
{
matr_Pad[pos][i]=hijo[i];
}
padreFunc=hijoFunc;
ps++;
ve++;
}
else
{
printf(" SE MANTIENE EL PADRE\n");
}
}
else if (restriccion(hijo)==1 && restriccion(padre)==0)
{
//printf("mejor actitud");
printf(" HIJO SUSTITUYO AL PADRE \n");
for(i=0;i<num_var;i++)
{
matr_Pad[pos][i]=hijo[i];
}
padreFunc=hijoFunc;
ps++;
ve++;
}
else if (restriccion(hijo)==0 && restriccion(padre)==1)
{
//printf("mejor actitud");
printf(" EL PADRE SE MANTIENE \n");
}
else if (restriccion(hijo)==1 && restriccion(padre)==1)
{
//printf("mejor actitud");
if(hijoFunc<padreFunc)
{
printf(" HIJO SUSTITUYO AL PADRE \n");
for(i=0;i<num_var;i++)
{
matr_Pad[pos][i]=hijo[i];
}
padreFunc=hijoFunc;
ps++;
ve++;
}
else
{
printf(" SE MANTIENE EL PADRE\n");
}
}*/
//usando el 1/5
if((t%(10*num_var)) == 0){
if(ps<(2*num_var)){
delta= delta*c;
}else if(ps>(2*num_var)){
delta=delta/c;
}else{
delta=delta;
}
ps=0;
}
t++;
}
printf("\n---%d",ve);
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
//int fib(int n)
//{
//
// if (n == 3)
// count++;
// if (n <= 2)
// return 1;
// else
// return fib(n - 1) + fib(n - 2);
//
//}
//int fib(int n)
//{
// int a = 1;
// int b = 1;
// int c = 0;
// while (n > 2)
// {
// c = a + b;
// a = b;
// b = c;
// n--;
// }
// return c;
//}
//int main()
//{
// int n = 0;
// int ret = 0;
//
// scanf("%d",&n);
// ret = fib(n);
// printf("%d\n", ret);
// system("pause");
//
// return 0;
//}
//int main()
//{
// int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// int k = 7;
//
// int left = 0;
// int right = sizeof(arr)/sizeof(arr[0])- 1;
// int mid = 0;
//
// while (left <= right)
// {
// mid = left + (right - left) / 2;
// if (arr[mid] < k)
// {
// left = mid + 1;
// }
// else if (arr[mid]>k)
// {
// right = mid - 1;
// }
// else
// {
// printf("ҵˣ±ǣ%d\n",mid);
// break;
// }
// }
// if (left > right)
// printf("Ҳ\n");
// system("pause");
// return 0;
//}
int binary_search(int arr[], int k, int left,int right)
{
int mid = 0;
while (left <= right)
{
mid = left + (right - left) / 2;
if (arr[mid] < k)
{
left = mid + 1;
}
else if (arr[mid]>k)
{
right = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int k = 7;
int sz = sizeof(arr) / arr[0]-1;
int left = 0;
int right = sz - 1;
int ret = binary_search(arr, k, left, right);
if (ret == -1)
{
printf("Ҳѽ\n");
}
else
{
printf("ҵˣ±ǣ%d\n", ret);
}
system("pause");
return 0;
}
|
C
|
#include<stdio.h>
int cost[20][20],parent[20]={0};
void main()
{
int n,i,j,ne=1,min,mincost=0,u,v,a,b;
printf("enter the number of nodes\n");
scanf("%d",&n);
printf("enter the cost matrix\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
{
min=cost[i][j];
u=a=i;
v=b=j;
}
if(parent[u])
u=parent[u];
if(parent[v])
v=parent[v];
if(u!=v)
{
printf("cost from %d to %d is %d\n",a,b,min);
mincost+=min;
ne++;
parent[v]=u;
}
cost[a][b]=cost[b][a]=999;
}
printf("min cost is %d\n",mincost);
}
|
C
|
/*
* Author: Joshua Curtis
* randomtestadventurer.c
* random test for adventure card
*/
#include "dominion.h"
#include "dominion_helpers.h"
#include "rngs.h"
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <time.h>
int main() {
struct gameState G;
struct gameState testG;
int k[10] = {adventurer, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy, council_room};
int i; // Loop iterator
int numPlayers = 2;
int seed = 1000;
int curPlayer = 0;
int otherPlayer = 1;
int handpos = 0, choice1 = 0, choice2 = 0, choice3 = 0, bonus = 0;
int newCards = 2;
int testNum = 0;
int handPassed = 0; //counter for correct currentPlayer handCount
int deckPassed = 0; //counter for correct currentPlayer deckCount
int otherHandPassed = 0; //counter for correct otherPlayer handCount
int otherDeckPassed = 0; //counter for correct otherPlayer handCount
int randHand, randDeck; //variable to store random number of currentPlayer handCount and deckCount
int negRandHand = 0; // Counter for handCount > 500
int negDeckHand = 0; // counter for deckCount > 500
int overRandHand = 0; // counter for handCount < 0
int overDeckHand = 0; // counter for deckCount < 0
int zeroHand = 0; // counter for handCount == 0
int zeroDeck = 0; // counter for deckCount == 0
time_t t;
// Initialize random number generator for testing
srand((unsigned) time(&t));
// initialize the game state and player cards
initializeGame(numPlayers, k, seed, &G);
printf("---------- Testing adventurer card ----------\n");
for (i = 0; i <100000; i++) {
//printf("Test Number: %d\n", testNum);
// copy the game state to a test case
memcpy(&testG, &G, sizeof(struct gameState));
// Generate random number of cards for testG hand
randHand = rand() % MAX_HAND - 1;
randDeck = rand() % MAX_DECK - 1;
//printf("randHand: %d\n", randHand);
//printf("randDeck: %d\n", randDeck);
if (randHand < 0)
negRandHand++;
if (randDeck < 0)
negDeckHand++;
if (randHand == 0)
zeroHand++;
if (randDeck == 0)
zeroDeck++;
testG.handCount[curPlayer] = randHand;
testG.deckCount[curPlayer] = randDeck;
//play adventurer card on testG check handCount
cardEffect(adventurer, choice1, choice2, choice3, &testG, handpos, &bonus);
if ( testG.handCount[curPlayer] == G.handCount[curPlayer] + newCards){
//printf("handCount: Passed\n");
handPassed++;
}
else
//printf("handCount: Failed\n");
//check adventure card on testG check deckCount
if ( testG.deckCount[curPlayer] <= G.deckCount[curPlayer]) {
//printf("deckCount: Passed\n");
deckPassed++;
}
else
//printf("deckCount: Failed\n");
//check that other players state is not changed
if ( testG.handCount[otherPlayer] == G.handCount[otherPlayer]) {
//printf("otherPlayer handCount: Passed\n");
otherHandPassed++;
}
else
//printf("otherPlayer handCount: Failed\n");
//check adventure card on testG check deckCount
if ( testG.deckCount[otherPlayer] == G.deckCount[otherPlayer]) {
//printf("otherPlayer deckCount: Passed\n");
otherDeckPassed++;
}
else
//printf("otherPlayer deckCount: Failed\n");
testNum++;
}
printf("Total Tests: %d\n", testNum);
printf("handCount Passed: %d\n", handPassed);
printf("deckCount Passed: %d\n", deckPassed);
printf("otherPlayer handCount Passed: %d\n", otherHandPassed);
printf("otherPlayer deckCount Passed: %d\n", otherDeckPassed);
printf("negRandHand: %d\n", negRandHand);
printf("negDeckHand: %d\n", negDeckHand);
printf("zeroHand: %d\n", zeroHand);
printf("zeroHand: %d\n", zeroDeck);
return 0;
}
|
C
|
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
float x[20], y[20], f, s, h, d, p;
int j, i, n;
printf("enter the number of elements: ");
scanf("%d", &n);
printf("enter the elements of x:\n");
for (i = 1; i <= n; i++)
{
scanf("%f", &x[i]);
}
printf("enter the elements of y:\n");
for (i = 1; i <= n; i++)
{
scanf("%f", &y[i]);
}
h = x[2] - x[1];
printf("Enter the value of f: ");
scanf("%f", &f);
s = (f - x[1]) / h;
p = 1;
d = y[1];
for (i = 1; i <= (n - 1); i++)
{
for (j = 1; j <= (n - i); j++)
{
y[j] = y[j + 1] - y[j];
}
p = p * (s - i + 1) / i;
d = d + p * y[1];
}
printf("For the value of x=%6.5f THe value is %6.5f\n", f, d);
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include "derivedStack.h"
#ifndef NULL
#define NULL ((void *)0)
#endif
const void *OBJ_bsearch_ex_(const void *key, const void *base_, int num,
int size,
int (*cmp) (const void *, const void *),
int flags);
/**
* a general derived type stack.
* refs from openssl source
*/
struct stackSt {
int capacity;
int topOfStack;
int sorted;
const void **data;
stackEleCmpFunc cmp;
};
stackEleCmpFunc stSetCmpFunc(derivedStack *st, stackEleCmpFunc func)
{
stackEleCmpFunc old;
old = st->cmp;
if (st->cmp != func)
st->sorted = 0;
st->cmp = func;
return old;
}
derivedStack *stDup(const derivedStack *st)
{
derivedStack *ret;
if ((ret = malloc(sizeof(*ret))) == NULL) {
err_msg("malloc error");
return NULL;
}
/* direct structure assignment */
*ret = *st;
if (st->topOfStack == EmptyTOS) {
/* postpone |ret->data| allocation */
ret->data = NULL;
ret->capacity = 0;
return ret;
}
/* duplicate |sk->data| content */
if ((ret->data = malloc(sizeof(*ret->data) * st->capacity)) == NULL)
goto err;
memcpy(ret->data, st->data, sizeof(void *) * st->topOfStack);
return ret;
err:
free(ret);
return NULL;
}
derivedStack *stDeepCopy(const derivedStack *st,
stackEleCopyFunc copy_func,
stackEleFreeFunc free_func)
{
derivedStack *ret;
int i;
if ((ret = malloc(sizeof(*ret))) == NULL) {
err_msg("malloc error");
return NULL;
}
/* direct structure assignment */
*ret = *st;
if (st->topOfStack == 0) {
/* postpone |ret| data allocation */
ret->data = NULL;
ret->capacity = 0;
return ret;
}
ret->capacity = st->topOfStack > min_nodes ? st->topOfStack : min_nodes;
ret->data = calloc(1, sizeof(*ret->data) * ret->capacity);
if (ret->data == NULL) {
free(ret);
return NULL;
}
for (i = 0; i < ret->topOfStack; ++i) {
if (st->data[i] == NULL)
continue;
if ((ret->data[i] = copy_func(st->data[i])) == NULL) {
while (--i >= 0)
if (ret->data[i] != NULL)
free_func((void *)ret->data[i]);
free(ret);
return NULL;
}
}
return ret;
}
derivedStack *stNewNULL(void)
{
return stNewReserve(NULL, 0);
}
derivedStack *stNewNULLC(stackEleCmpFunc c)
{
return stNewReserve(c, 0);
}
/**
* Allocate or rellocate the memory of stack to st->topOfStack + n
* n is the expected new capacity, exact is a flag to apply compute_growth
* if exact euals 0 won't reduce mem size, otherwise may reduce mem size
* input: st, n, exact
* output: none
* return: Errorcodes
*/
static int reserve(derivedStack *st, int n, int exact)
{
const void **tmpdata;
int newCap;
/* Check to see the reservation isn't exceeding the hard limit */
if (n > max_nodes - st->topOfStack)
return 0;
/* Figure out the new size */
newCap = st->topOfStack + n;
if (newCap < min_nodes)
newCap = min_nodes;
/* If |st->data| allocation was postponed */
if (st->data == NULL) {
/*
* At this point, |st->num_alloc| and |st->num| are 0;
* so |num_alloc| value is |n| or |min_nodes| if greater than |n|.
*/
if ((st->data = malloc(sizeof(*st->data) * newCap)) == NULL) {
err_msg("maloc error");
return 0;
}
st->capacity = newCap;
return 1;
}
if (!exact) {
if (newCap <= st->capacity)
return 1; /* won't reduce mem size */
newCap = compute_growth(newCap, st->capacity);
if (newCap == 0)
return 0;
} else if (newCap == st->capacity) {
return 1; /* may reduce mem size */
}
tmpdata = realloc((void *)st->data, sizeof(*st->data) * newCap);
if (tmpdata == NULL)
return 0;
st->data = tmpdata;
st->capacity = newCap;
return 1;
}
/* change stack size to st->topOfStack + n */
int stReserve(derivedStack *st, int n)
{
if (st == NULL)
return 0;
if (n < 0)
return 1;
return reserve(st, n, 1);
}
void stFree(derivedStack *st)
{
if (st == NULL)
return;
free(st->data);
free(st);
}
void stPopFree(derivedStack *st, stackEleFreeFunc func)
{
if (st == NULL)
return;
for (int i = 0; i < st->topOfStack; i++)
if (st->data[i] != NULL)
func((char *)st->data[i]); /* try cast to char* to handle compiler warning */
}
void stZero(derivedStack *st)
{
if (st == NULL || st->capacity == 0)
return;
memset(st->data, 0, sizeof(*st->data) * st->capacity);
st->capacity = 0;
}
int stTopOfStack(derivedStack *st)
{
return st == NULL ? -1 : st->topOfStack;
}
void *stGetAt(derivedStack *st, int idx)
{
if (st == NULL || idx < 0 || idx >= st->topOfStack)
return NULL;
return (void *)st->data[idx];
}
void *stSetAt(derivedStack *st, int idx, const void *data)
{
if (st == NULL || idx < 0 || idx >= st->topOfStack)
return NULL;
st->data[idx] = data;
st->sorted = 0;
return (void *)st->data[idx];
}
void stSort(derivedStack *st)
{
if (st != NULL && !st->sorted && st->cmp != NULL) {
if (st->capacity > 1)
qsort(st->data, st->capacity, sizeof(void *), st->cmp);
st->sorted = 1;
}
}
int stIsSorted(derivedStack *st)
{
return st == NULL ? 1 : st->sorted;
}
derivedStack *stNewReserve(stackEleCmpFunc func, int cap)
{
derivedStack *st;
if ((st = calloc(1, sizeof(derivedStack))) == NULL)
return NULL;
st->topOfStack = EmptyTOS;
st->cmp = func;
if (cap <= 0)
return st;
if (!stReserve(st, cap)) {
free(st);
return NULL;
}
return st;
}
/* random loc insert is not a regular stack op, but this is the undlying func for push op */
int stInsert(derivedStack *st,const void *data, int loc)
{
if (st == NULL || st->capacity == max_nodes)
return 0;
if (!reserve(st, 1, 0)) /* may increase the stack size dynamictly */
return 0;
if ((loc >= st->topOfStack) || (loc < 0)) {
st->data[st->topOfStack] = data;
} else {
memmove(&st->data[loc + 1], &st->data[loc], sizeof(st->data[0]) * (st->topOfStack - loc));
st->data[loc] = data;
}
st->topOfStack++;
st->sorted = 0;
return st->topOfStack;
}
/* be ware, random loc delete is not a regular stack op */
static inline void *internalDelete(derivedStack *st, int loc)
{
const void *ret;
ret = st->data[loc];
if (loc != st->topOfStack - 1)
memmove(&st->data[loc], &st->data[loc + 1], sizeof(st->data[0]) * (st->topOfStack - loc - 1));
st->topOfStack--;
return (void *)ret;
}
void *stDeletePtr(derivedStack *st, const void *p)
{
for (int i = 0; i < st->topOfStack; i++)
if (st->data[i] == p)
return internalDelete(st, i);
return NULL;
}
void *stDelete(derivedStack *st, int loc)
{
if (st == NULL || loc < 0 || loc >= st->topOfStack)
return NULL;
return internalDelete(st, loc);
}
/* find is not a regular stack op */
static int internalFind(derivedStack *st, const void *data, int retOptions)
{
const void *r;
int i;
if (st == NULL || st->topOfStack == 0)
return -1;
if (st->cmp == NULL) {
for (i = 0; i < st->topOfStack; i++)
if (st->data[i] == data)
return i;
return -1;
}
if (!st->sorted) {
if (st->topOfStack > 1)
qsort(st->data, st->topOfStack, sizeof(void *), st->cmp);
st->sorted = 1;
}
if (data == NULL)
return -1;
r = OBJ_bsearch_ex_(&data, st->data, st->topOfStack, sizeof(void *), st->cmp,
retOptions);
return r == NULL ? -1 : (int)((const void **)r - st->data);
}
int stFind(derivedStack *st, const void *data)
{
return internalFind(st, data, 0x02);
}
int stFindex(derivedStack *st, const void *data)
{
return internalFind(st, data, 0x01);
}
int stPush(derivedStack *st, const void *data)
{
if (st == NULL)
return -1;
return stInsert(st, data, st->topOfStack);
}
/* pop return the top element value and move top loc */
void *stPop(derivedStack *st)
{
if (st == NULL || st->topOfStack == 0)
return NULL;
return internalDelete(st, st->topOfStack - 1);
}
/* top return the top element value, but won't move top loc */
void *stTop(derivedStack *st)
{
if (st == NULL || st->topOfStack == 0)
return NULL;
return (void *)st->data[st->topOfStack - 1];
}
|
C
|
#include<stdio.h>
void main()
{
int i;
float a,b,c;
while (i>0)
{
printf("please enter the value of first side a\n");
scanf("%f",&a);
printf("please enter the value of second side b\n");
scanf("%f",&b);
printf("please enter the value of third side c\n");
scanf("%f",&c);
if(a<0 || b<0 || c<0)
{
break;
}
if(a+b<=c || b+c<=a || a+c<=b )
printf("Invalid input\n");
if(a==b==c)
printf("Equilateral\n");
else if(a==b || b==c || a==c )
printf("Isoceles\n");
else
{
printf("the given triangle is not equilateral or isoceles\n");
}
}
}
|
C
|
/*******************************************************************************
*
* lib-util : A Utility Library
*
* Copyright (c) 2016-2018 Ammon Dodson
* You should have received a copy of the license terms with this software. If
* not, please visit the project homepage at:
* https://github.com/ammon0/lib-util
*
******************************************************************************/
#include <util/input.h>
#include <util/types.h>
#include <stdlib.h>
#include <ctype.h>
#define IN 1 /* inside a word */
#define OUT 2 /* outside a word */
#define ARRAY_SIZE 50 // this is just a starting size
#define SP_NW_FIELD 3 // number of spaces for a new field in grabfield()
/******************************************************************************/
// PRIVATE FUNCTIONS
/******************************************************************************/
static inline bool line(char c){
return (c == '\n' || c == '\f' || c == '\r' || c == EOF );
}
static inline bool word(char c){
return ( !isgraph(c) || c == EOF );
}
static inline char* finishup(char* store, unsigned int i){
if (*store == '\0' || *store == EOF) { // if nothing was read
free(store);
return NULL;
}
// get rid of any trailing spaces or tabs we might have captured
while(store[i-1] == ' ' || store[i-1] == '\t'){
store[i-1]='\0';
i--;
}
// create a correctly sized array to output the result
if ( (store=(char*)realloc(store, i+1)) == NULL ) {
puts("ERROR: realloc() failed.");
free(store);
return NULL;
}
return store;
}
// since grabword and grabline were nearly identical I combined their code
static inline char* grab (bool (test) (char c), FILE* source){
unsigned int i = 1; // position in the array
unsigned int size = ARRAY_SIZE; // current size of the array
char * store; // an array to temporarily hold the word
char c; // temporary character
if (source == NULL)
return NULL;
// allocate
if ( (store=(char*)malloc(ARRAY_SIZE)) == NULL ) {
puts("ERROR: calloc() failed.");
return NULL;
}
store[0] = '\0';
// get the first character excluding all whitespace
while(!isgraph( c = (char) fgetc(source) ) && !feof(source));
store[0]=c;
while (!feof(source)){
c = (char) fgetc(source);
if (test (c)) break;
// if store isn't big enough we double it.
if (i == size-1)
if ( (store=(char*)realloc(store, size *=2)) == NULL ) {
puts("ERROR: realloc() failed.");
free(store);
return NULL;
}
// store c in the array and increment i
store[i]=c;
i++;
store[i]='\0'; // don't know if realloc space is initialized
}
return finishup(store, i);
}
/******************************************************************************/
// PUBLIC FUNCTIONS
/******************************************************************************/
char* grabword(FILE* source){
return grab(&word, source);
}
char* grabline(FILE* source){
return grab(&line, source);
}
char* grabfield(FILE* source){
unsigned int i = 0; // position in the array
unsigned int size = ARRAY_SIZE; // current size of the array
int state= OUT; // assume that the pointer is not in a field
char* store; // an array to temporarily hold the field
char c; // temporary character
int space_count=0; // track number of contiguous spaces
if (source == NULL)
return NULL;
// allocate
if ( (store=(char*)malloc(ARRAY_SIZE)) == NULL ) {
puts("ERROR: calloc() failed.");
return NULL;
}
store[0] = '\0';
// while c is not EOF read it into store
do {
if (state == IN && space_count >=SP_NW_FIELD) break;
c = (char) fgetc(source);
if (c == ' ' && state == OUT); // do nothing
else if( (c>='\t' && c<='\r') || c == EOF ){
if (state == IN) break;
} else {
state = IN;
if (i == size-1) { // if store isn't big enough we double it.
if ( (store=(char*)realloc(store, size *=2)) == NULL ) {
puts("ERROR: realloc() failed.");
free(store);
return NULL;
}
}
// store c in the array and increment i
store[i]=c;
i++;
store[i]='\0'; // don't know if realloc space is initialized
if (c == ' ') space_count++;
else space_count=0;
}
} while (!feof(source));
return finishup(store, i);
}
|
C
|
/* HASH HASH OPERATOR */
#include<stdio.h>
#include<stdlib.h>
#define CAT1(x, y) (x##y)
#define CAT2(x, y) (x##_##y)
int main()
{
system("clear");
int int_val = 4;
float float_val = 2.54;
int bird_count = 20;
printf("int val : %d\n", CAT1(int, _val));
printf("flaot val : %f\n", CAT2(float, val));
printf("bird count : %d\n", CAT2(bird, count));
return 0;
}
|
C
|
#include "platform.h"
struct KeyState {
unsigned char m_IsPressed;
unsigned char m_IsTriggered;
unsigned char m_WasPressed;
unsigned char m_Reserved;
};
static struct KeyState m_Keys[3];
int isMouseLeftButtonPressed(void)
{
return m_Keys[0].m_IsPressed;
}
int isMouseLeftButtonTriggered(void)
{
return m_Keys[0].m_IsTriggered;
}
int isMouseMiddleButtonPressed(void)
{
return m_Keys[1].m_IsPressed;
}
int isMouseMiddleButtonTriggered(void)
{
return m_Keys[1].m_IsTriggered;
}
int isMouseRightButtonPressed(void)
{
return m_Keys[2].m_IsPressed;
}
int isMouseRightButtonTriggered(void)
{
return m_Keys[2].m_IsTriggered;
}
void mouseUpdate(void)
{
int i;
int pressed[3] = { isLeftMouseButtonDown(), isMiddleMouseButtonDown(), isRightMouseButtonDown() };
for (i = 0; i < 3; ++i) {
m_Keys[i].m_IsPressed = pressed[i];
if (m_Keys[i].m_IsPressed) {
if (m_Keys[i].m_WasPressed)
m_Keys[i].m_IsTriggered = 0;
else {
m_Keys[i].m_WasPressed = 1;
m_Keys[i].m_IsTriggered = 1;
}
} else {
m_Keys[i].m_IsTriggered = 0;
m_Keys[i].m_WasPressed = 0;
}
}
}
static struct KeyState m_KeyboardKeys[256];
int isKeyPressed(int vKey)
{
return m_KeyboardKeys[vKey].m_IsPressed;
}
int isKeyTriggered(int vKey)
{
return m_KeyboardKeys[vKey].m_IsTriggered;
}
void keyboardUpdate(void)
{
int i;
unsigned char ks[256] = {0};
getKeyboardState(ks);
for (i = 0; i < 256; ++i) {
m_KeyboardKeys[i].m_IsPressed = ks[i] & (1 << 7) ? 1 : 0;
if (m_KeyboardKeys[i].m_IsPressed) {
if (m_KeyboardKeys[i].m_WasPressed)
m_KeyboardKeys[i].m_IsTriggered = 0;
else {
m_KeyboardKeys[i].m_WasPressed = 1;
m_KeyboardKeys[i].m_IsTriggered = 1;
}
} else {
m_KeyboardKeys[i].m_IsTriggered = 0;
m_KeyboardKeys[i].m_WasPressed = 0;
}
}
}
|
C
|
#include "stack.h"
#include<stdio.h>
void CreateStack(StackType *s) {
s->top = -1;
}
int StackEmpty(StackType s) {
return(s.top==-1);
}
int StackFull(StackType s) {
return(s.top==MAX-1);
}
void Push(EntryType item , StackType *s) {
if(s->top == MAX-1)
printf("Error: Stack Overflow");
else
s->entry[++s->top] = item;
}
void Pop(EntryType *item , StackType *s) {
if(s->top == -1)
printf("Error: Stack Underflow");
else
*item = s->entry[s->top--];
}
|
C
|
#include "binary_trees.h"
/**
* deepTree - Binary tree node
*
* @tree: tree to measure
* Return: deep of the tree
*/
int deepTree(const binary_tree_t *tree)
{
int deep = 0;
while (tree != NULL)
{
deep++;
tree = tree->left;
}
return (deep);
}
/**
* _binary_tree_is_perfect - function that checks if a binary tree is perfect
*
* @tree: tree to check
* @deep: deep of the tree
* @level: current level
* Return: 1 if the tree is perfect, 0 otherwise
*/
int _binary_tree_is_perfect(const binary_tree_t *tree, int deep, int level)
{
int left_measure = 0;
int right_measure = 0;
if (!tree)
return (1);
if (tree->left == NULL && tree->right == NULL)
return (deep == level + 1);
if (tree->right == NULL || tree->left == NULL)
return (0);
left_measure = _binary_tree_is_perfect(tree->left, deep, level + 1);
right_measure = _binary_tree_is_perfect(tree->right, deep, level + 1);
return (left_measure && right_measure);
}
/**
* binary_tree_is_perfect - function that checks if a binary tree is perfect
*
* @tree: tree to check
* Return: 1 if the tree is perfect, 0 otherwise
*/
int binary_tree_is_perfect(const binary_tree_t *tree)
{
int deep = 0;
if (!tree)
return (0);
deep = deepTree(tree);
if (_binary_tree_is_perfect(tree, deep, 0) == 1)
return (1);
else
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define TRUE 1
#define FALSE 0
#define TAM 1000
#include "empleados.h"
int initEmployees(eEmpleado listaEmpleados[],int tamanioArray)
{
int retorno;
retorno=-1;
for(int i=0;i <tamanioArray; i++)
{
listaEmpleados[i].isEmpty =TRUE;
retorno=0;
}
return retorno;
}
int PedirEntero(char texto[],char textoError[])
{
char auxiliar[10];
int numeroIngresado;
printf("%s", texto);
fflush(stdin);
scanf("%[^\n]",auxiliar);
while(ValidarNumero(auxiliar)==0)
{
printf("%s", textoError);
fflush(stdin);
scanf("%[^\n]",auxiliar);
}
numeroIngresado=atoi(auxiliar);
return numeroIngresado;
}
float PedirFlotante(char texto[],char textoError[])
{
char auxiliar[10];
float numeroIngresado;
printf("%s", texto);
fflush(stdin);
scanf("%[^\n]",auxiliar);
while(ValidarFlotante(auxiliar)==0)
{
printf("%s", textoError);
fflush(stdin);
scanf("%[^\n]",auxiliar);
}
numeroIngresado=atof(auxiliar);
return numeroIngresado;
}
int ValidarFlotante(char numero[])
{
int valido=1;
for(int i=0;i<strlen(numero);i++)
{
if( (numero[i] < '0' || numero[i] > '9') && numero[i] !='.')
{
valido=0;
}
}
return valido;
}
void PedirString(char texto[],char textoError[],int max, char input[])
{
char auxiliar[500];
printf("%s", texto);
fflush(stdin);
scanf("%[^\n]",auxiliar);
while(ValidarLetras(auxiliar)==0|| strlen(auxiliar)>max-1)
{
printf("%s", textoError);
fflush(stdin);
scanf("%[^\n]",auxiliar);
}
strcpy(input,auxiliar);
}
eEmpleado addEmployees(eEmpleado listaEmpleados[],int tamanioArray, int indiceLibre)
{
eEmpleado unEmpleado;
PedirString("\nIngrese nombre: ","Error. Reingrese nombre: ",51,unEmpleado.nombre);
PedirString("Ingrese apellido: ","Error. Reingrese apellido: ",51,unEmpleado.apellido);
unEmpleado.sector = PedirEntero("Ingrese sector: ","Error, reingrese sector valido: ");
unEmpleado.sueldo= PedirFlotante("Ingrese sueldo: ","Error, reingrese sueldo valido:");
unEmpleado.isEmpty=FALSE;
unEmpleado.id=indiceLibre;
listaEmpleados[indiceLibre]=unEmpleado;
return unEmpleado;
}
int BuscarLibre(eEmpleado listaEmpleados[],int tamanioArray)
{
int index=-1;
for(int i=0;i<tamanioArray;i++)
{
if(listaEmpleados[i].isEmpty==TRUE)
{
index=i;
break;
}
}
return index;
}
void printEmployees(eEmpleado listaEmpleados[],int cant)
{
printf("\n*********************************************************************************");
printf("\n\t \tListado de empleados: \n\n");
printf("ID \tNOMBRE\t\tAPELLIDO\t SECTOR\t \tSUELDO\n");
for(int i=0;i<cant;i++)
{
if(listaEmpleados[i].isEmpty==FALSE)
{
listaEmpleados[i].id=i;
printf("%2d %10s %15s %15d %20f \n", listaEmpleados[i].id,
listaEmpleados[i].nombre,
listaEmpleados[i].apellido,
listaEmpleados[i].sector,
listaEmpleados[i].sueldo );
}
}
printf("\n*********************************************************************************");
}
int findEmployeeById(int idIngresado, int tam, eEmpleado listaEmpleados[])
{
int idValido=-1;
for(int i=0;i<tam;i++)
{
if(listaEmpleados[i].id==idIngresado)
{
idValido=idIngresado;
}
}
return idValido;
}
void ModificarUnEmpleado(eEmpleado listaEmpleados[],int idAModificar,int opcionModificar)
{
char nombreModificado[51];
char apellidoModificado[51];
switch(opcionModificar)
{
case 1:
PedirString("Ingrese el nuevo nombre:","Error. Reingrese nombre: ",51,nombreModificado);
strcpy(listaEmpleados[idAModificar].nombre,nombreModificado);
break;
case 2:
PedirString("Ingrese el nuevo apellido:","Error. Reingrese apellido: ",51,apellidoModificado);
strcpy(listaEmpleados[idAModificar].apellido,apellidoModificado);
break;
case 3:
listaEmpleados[idAModificar].sector=PedirEntero("Ingrese nuevo sector: ","Error, reingrese sector valido: ");
break;
case 4:
listaEmpleados[idAModificar].sueldo=PedirFlotante("Ingrese sueldo: ","Error, reingrese sueldo valido:");
break;
default:
printf("\nOpcion no valida. Intente nuevamente\n");
}
}
int removeEmployee(eEmpleado listaEmpleados[],int contadorEmpleadosCargados, int idEliminar)
{
int retorno=-1;
if(findEmployeeById(idEliminar,contadorEmpleadosCargados,listaEmpleados)!=-1)
{
retorno=0;
listaEmpleados[idEliminar].isEmpty=TRUE;
}
return retorno;
}
int ValidarLetras(char string[])
{
int valido;
valido=1;
for(int i=0;i<strlen(string);i++)
{
if((string[i] != ' ') && (string[i] < 'a' || string[i] > 'z') && (string[i] < 'A' || string[i] > 'Z'))
{
valido=0;
}
}
return valido;
}
int ValidarNumero(char numero[])
{
int valido=1;
for(int i=0;i<strlen(numero);i++)
{
if(numero[i] < '0' || numero[i] > '9')
{
valido=0;
}
}
return valido;
}
void sortEmployees(eEmpleado unEmpleado[],int tamanioarray)
{
eEmpleado auxiliar;
for(int i=0;i<tamanioarray-1;i++)
{
for(int j=i+1;j<tamanioarray;j++)
{
if( strcmp(unEmpleado[i].apellido,unEmpleado[j].apellido)>0 || (strcmp(unEmpleado[i].apellido,unEmpleado[j].apellido)==0) && (unEmpleado[i].sector< unEmpleado[j].sector))
{
auxiliar= unEmpleado[i]; //empleado i vale juan
unEmpleado[i]=unEmpleado[j]; //empleado subj vale maria
unEmpleado[j]=auxiliar;
}
}
}
}
float CalcularTotalSalarios(eEmpleado unEmpleado[],int cantEmpleados)
{
float acumuladorSalarios;
acumuladorSalarios=0;
for(int i=0;i<cantEmpleados;i++)
{
acumuladorSalarios=acumuladorSalarios+unEmpleado[i].sueldo;
}
return acumuladorSalarios;
}
float CalcularPromedioSalarios(eEmpleado unEmpleado[],int cantEmpleados,float salarioTotal)
{
float promedioSalarios;
promedioSalarios=salarioTotal/cantEmpleados;
return promedioSalarios;
}
float ContarEmpleadosSueldoMayorAlPromedio(eEmpleado unEmpleado[],int cantEmpleados,float salarioPromedio)
{
int contadorEmpleadosSueldoMayorAlPromedio=0;
for(int i=0;i<cantEmpleados;i++)
{
if(unEmpleado[i].sueldo>salarioPromedio)
{
contadorEmpleadosSueldoMayorAlPromedio++;
}
}
return contadorEmpleadosSueldoMayorAlPromedio;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
float c, f;
puts("Introduza a temperatura em graus Fahrenheit: ");
scanf("%f", &f);
c = (f - 32) * 5/9;
printf("A temperatura em graus Centigrados e: %f\n", c);
return 0;
}
|
C
|
#include "header.h"
static void execute(t_queue *work, t_builtin_command *my_command) {
t_queue *p = work;
int status;
for (; p; p = (*p).next) {
(*p).command = mx_tokenCut((*p).command, 0, mx_strlen((*p).command));
(*p).command = mx_substitute((*p).command, my_command);
status = mx_redirection((*p).command, my_command);
if (((*p).op == '&' && status == 1)
|| ((*p).op == '|' && status == 0))
{
p = (*p).next;
}
}
}
int mx_subExec(t_builtin_command *my_command, char *line) {
int fd[2];
t_queue **work = NULL;
pid_t pid;
pipe(fd);
pid = fork();
if (pid == 0) {
close(1);
dup(fd[1]);
close(fd[1]);
work = mx_works_queue(line);
for (int i = 0; work[i]; i++) {
execute(work[i], my_command);
}
exit(0);
}
else
close(fd[1]);
if (malloc_size(line))
mx_strdel(&line);
return fd[0];
}
|
C
|
#ifndef LIST_H
#define LIST_H
#include <stdbool.h>
typedef struct _doubly_node DoublyNode, Node;
typedef struct _doubly_linked_list DoublyLinkedList, List;
Node *Node_create(int val);
List *List_create();
void List_destroy(List **L_ref);
bool List_is_empty(const List *L);
void List_add_first(List *L, int val);
void List_add_last(List *L, int val);
void List_print(const List *L);
void List_inverted_print(const List *L);
void List_remove(List *L, int val);
void List_sorted_add(List *L, int val);
#endif
|
C
|
/*
* Programa servidor:
* Recebe uma string do cliente e envia o tamanho dessa string.
*
* Como compilar:
* gcc -Wall -g server.c -o server
*
* Como executar:
* server <porto_servidor>
*/
#include "inet.h"
int main(int argc, char **argv)
{
int sockfd, connsockfd;
struct sockaddr_in server, client;
char str[MAX_MSG+1];
int nbytes, count, size_client;
// Verifica se foi passado algum argumento
if (argc != 2){
printf("Uso: ./server <porto_servidor>\n");
printf("Exemplo de uso: ./server 12345\n");
return -1;
}
// Cria socket TCP
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
perror("Erro ao criar socket");
return -1;
}
// Preenche estrutura server para bind
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[1]));
server.sin_addr.s_addr = htonl(INADDR_ANY);
// Faz bind
if (bind(sockfd, (struct sockaddr *) &server, sizeof(server)) < 0){
perror("Erro ao fazer bind");
close(sockfd);
return -1;
};
// Faz listen
if (listen(sockfd, 0) < 0){
perror("Erro ao executar listen");
close(sockfd);
return -1;
};
printf("Servidor 'a espera de dados\n");
// Bloqueia a espera de pedidos de conexo
while ((connsockfd = accept(sockfd,(struct sockaddr *) &client, &size_client)) != -1) {
// L string enviada pelo cliente do socket referente a conexo
if((nbytes = read(connsockfd,str,MAX_MSG)) < 0){
perror("Erro ao receber dados do cliente");
close(connsockfd);
continue;
}
// Coloca terminador de string
str[nbytes] = '\0';
// Conta numero de caracteres
count = strlen(str);
// Converte count para formato de rede
count = htonl(count);
// Envia tamanho da string ao cliente atravs do socket referente a conexo
if((nbytes = write(connsockfd,&count,sizeof(count))) != sizeof(count)){
perror("Erro ao enviar resposta ao cliente");
close(connsockfd);
continue;
}
// Fecha socket referente a esta conexo
close(connsockfd);
}
// Fecha socket (s executado em caso de erro...)
close(sockfd);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include "struct.h"
#include <omp.h>
//function which initiates the qs struct
TAD_istruct init2(TAD_istruct qs){
int i;
//runs through all the cube's and author's block inside the hash table andpercorre os arrays cube e author e inicializa-os.
for(i=0; i < qs->hashsize; i++){
qs->articles[i].id = -1;//-1 is the deafult id of an article
qs->articles[i].isOccupied = 0;
qs->articles[i].nrevisions = 0;
qs->authors[i].id = -1;//-1 is the default id of an author
qs->authors[i].isOccupied = 0;
qs->authors[i].ncontributions = 0;
}
return qs;
}
//function which counts how many articles exist in the document
int parseCount (xmlDocPtr doc){
xmlNodePtr cur, aux;
int p=0;
if (doc == NULL ) {
fprintf(stderr,"Document not parsed successfully. \n");
return 0;
}
cur = xmlDocGetRootElement(doc);
if (cur == NULL) {
fprintf(stderr,"empty document\n");
return 0;
}
aux = cur->xmlChildrenNode;
while (aux != NULL ){
if(!(xmlStrcmp(aux->name, (const xmlChar *) "page"))) p++;//everytime there is a page node we increment the p variable
aux = aux->next;
}
return p;
}
//function which parse all the document and insert the information on the struct
void parseDocID (xmlNodePtr cur, TAD_istruct qs, xmlDocPtr doc){
xmlNodePtr aux, cont,user, texto;
char username[256];
char *text, *con, *t, *u;
int textflag = 0;
int id, revisionid, usernameid=-1;
while (cur != NULL){
if(!(xmlStrcmp(cur->name, (const xmlChar *) "page"))){
aux= cur->xmlChildrenNode;//everytime the function finds a page node, it equals the aux to the children node
while(aux!=NULL){
if(!(xmlStrcmp(aux->name, (const xmlChar *) "title"))){
con = (char*) xmlNodeGetContent(aux);
//strcpy(title, con);
//xmlFree(con);
}
if(!(xmlStrcmp(aux->name, (const xmlChar *) "id"))){
char* i = (char*) xmlNodeGetContent(aux);
id = atoi(i);
xmlFree(i);
}
if(!(xmlStrcmp(aux->name, (const xmlChar *) "revision"))){
cont=aux->xmlChildrenNode;
while(cont!=NULL){
if(!(xmlStrcmp(cont->name, (const xmlChar *) "id"))){
char *ri = (char*) xmlNodeGetContent(cont);
revisionid = atoi(ri);
xmlFree(ri);
}
if(!(xmlStrcmp(cont->name, (const xmlChar *) "timestamp"))){
t = (char*) xmlNodeGetContent(cont);
//strcpy(timestamp, t);
//xmlFree(t);
}
if(!(xmlStrcmp(cont->name, (const xmlChar *) "contributor"))){
user= cont->xmlChildrenNode;
while(user!=NULL){
if(!(xmlStrcmp(user->name, (const xmlChar *) "username"))){
u = (char*) xmlNodeGetContent(user);
strcpy(username, u);
xmlFree(u);
}
if(!(xmlStrcmp(user->name, (const xmlChar *) "id"))){
char* uid = (char*) xmlNodeGetContent(user);
usernameid = atoi(uid);
xmlFree(uid);
}
user=user->next;
}
}
if(!(xmlStrcmp(cont->name, (const xmlChar *) "text")) && !textflag){
texto = cont->xmlChildrenNode;
if (texto != NULL){
textflag = 1;
text = (char*) xmlNodeGetContent(texto);
}
}
cont=cont->next;
}
}
aux=aux->next;
}
insertID(id, revisionid, usernameid, con, username, t, text, qs);
xmlFree(text);
}
usernameid=-1;
textflag = 0;
cur = cur->next;
}
}
/*
parseDoc - parse all doc info
*/
void parseDoc(xmlDocPtr doc, TAD_istruct qs) {
xmlNodePtr cur, aux;
if (doc == NULL ) {
fprintf(stderr,"Document not parsed successfully. \n");
return;
}
cur = xmlDocGetRootElement(doc);
if (cur == NULL) {
fprintf(stderr,"empty document\n");
return;
}
aux = cur->xmlChildrenNode;
parseDocID(aux, qs, doc);
}
void parse(int nsnaps, char **snaps_paths, TAD_istruct qs) {
int i, size = 0;
if (nsnaps <= 0) {
printf("Usage: ./program docname\n");
return;
}
xmlDocPtr doc[nsnaps];
#pragma omp parallel for num_threads(8) ordered schedule(dynamic)
for(i=0; i<nsnaps; i++){
doc[i] = xmlParseFile(snaps_paths[i]);
size+=parseCount(doc[i]);
}
size = (size *2);
qs->hashsize = size;
qs->articles = malloc(size*sizeof(Article));
qs->authors = malloc(size*sizeof(Contributor));
qs = init2(qs);
for(i=0; i<nsnaps; i++){
parseDoc(doc[i], qs);
xmlFreeDoc(doc[i]);
}
xmlCleanupParser();
}
|
C
|
/*
ID: saitorl1
LANG: C
TASK: dualpal
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
void swap(char* a, char* b)
{
char temp = *a;
*a = *b;
*b = temp;
}
void reverse(char str[], int length)
{
int start = 0;
int end = length - 1;
while(start < end) {
swap(&str[start], &str[end]);
start++;
end--;
}
}
// Implementation of itoa()
char* itoa(int num, char* str, int base)
{
int i = 0;
int isNegative = 0;
// Handle 0 explicitely
if(num==0) {
str[i++] = '0';
str[i] = '\0';
return str;
}
// Native numbers only handled with base 10
if(num<0 && base==10) {
isNegative = 1;
num = -num;
}
// Process individual digits
while(num!=0) {
int rem = num % base;
str[i++] = (rem > 9)? (rem-10) + 'A' : rem + '0';
num /= base;
}
// If number is negative, append '-'
if(isNegative)
str[i++] = '-';
// Append string terminator
str[i] = '\0';
// Reverse the string
reverse(str, i);
return str;
}
int isPalin(char* str)
{
int len = strlen(str);
char* start= str;
char* end = str+len-1;
for( ; start<end; start++, end--)
if(*start != *end) return 0;
return 1;
}
int main()
{
FILE* fin = fopen("dualpal.in", "r");
FILE* fout = fopen("dualpal.out", "w");
int i, n, s, num;
assert(fin!=NULL && fout!=NULL);
while(fscanf(fin, "%d%d", &n, &s)!=EOF) {
for(i=0, num=s+1; i<n; num++) {
int j, count;
for(j=2, count=0; j<=10; j++) { // Check for each base
char numBuf[101];
itoa(num, numBuf, j);
if(isPalin(numBuf))
count++;
}
if(count>=2) {
fprintf(fout, "%d\n", num);
i++;
}
}
}
fclose(fin);
fclose(fout);
return 0;
}
|
C
|
#include "holberton.h"
#include <stdlib.h>
/**
* array_range - creates an array of integers
*
* @min: start range
* @max: end range
*
* Return: the pointer to the newly created array
*/
int *array_range(int min, int max)
{
int i;
int *intArrayAddress = NULL;
if (min > max)
return (NULL);
intArrayAddress = malloc(sizeof(int) * (max - min + 1));
if (intArrayAddress == NULL)
return (NULL);
for (i = 0; min <= max; i++)
{
intArrayAddress[i] = min;
min++;
}
return (intArrayAddress);
}
|
C
|
// conio.c written by Magi.bbs@tsunami.ml.org
//
// for porting my five chess from borland c to unix
//
// Date: 98/3/18
#include <termios.h>
static int bgcolor=30;
static int high=0;
void cputs(char *buf)
{
printf("%s",buf);
}
void textcolor(int color)
{
printf("\x1b[1;%d;%dm",bgcolor,color);
}
void textbackground(int color)
{
bgcolor=color;
printf("\x1b[%dm",color+10);
}
void gotoxy(int x,int y)
{
printf("\x1b[%d;%dH",y,x);
}
void clrscr()
{
printf("\x1b[2J");
}
char readkey()
{
char ch;
/* read(0,&ch,1); */
ch=getchar();
return ch;
}
struct termios termsave;
void initconio()
{
struct termios term;
tcgetattr(0,&termsave);
term=termsave;
term.c_lflag &=~(ECHO | ICANON);
term.c_cc[VMIN]=1;
term.c_cc[VTIME]=0;
tcsetattr(0,TCSAFLUSH,&term);
}
void endconio()
{
tcsetattr(0,TCSAFLUSH,&termsave);
}
void highv()
{
high=1;
}
void lowv()
{
high=0;
}
|
C
|
#include <stdint.h>
#include "lib.h"
#include "testlib.h"
#define SIZE_OF_TEST 100
uint64_t* __var(test_ctx_t* ctx, run_idx_t r, const char* varname) {
var_idx_t idx = idx_from_varname(ctx, varname);
return ctx->heap_vars[idx].values[r];
}
#define VAR(ctx, r, var) __var(ctx, r, var)
UNIT_TEST(test_concretization_linear_default_diff_pages)
UNIT_TEST(test_concretization_random_default_diff_pages)
void __test_concretization_default_diff_pages(concretize_type_t conc_type) {
litmus_test_t test = {
"test",
0,NULL,
3,(const char*[]){"x","y","z","a"},
3,(const char*[]){"r", "s", "t"},
};
test_ctx_t ctx;
init_test_ctx(&ctx, &test, SIZE_OF_TEST, 1);
initialize_regions(&ctx.heap_memory);
void* st = concretize_init(conc_type, &ctx, ctx.cfg, ctx.no_runs);
concretize(conc_type, &ctx, ctx.cfg, st, ctx.no_runs);
/* each var must be in its own page */
for (int r = 0; r < ctx.no_runs; r++) {
for (int v = 0; v < ctx.cfg->no_heap_vars; v++) {
for (int v2 = v+1; v2 < ctx.cfg->no_heap_vars; v2++) {
ASSERT(PAGE(ctx.heap_vars[v].values[r]) != PAGE(ctx.heap_vars[v2].values[r]), "page == page");
}
}
}
}
void test_concretization_linear_default_diff_pages(void) {
__test_concretization_default_diff_pages(CONCRETE_LINEAR);
}
void test_concretization_random_default_diff_pages(void) {
__test_concretization_default_diff_pages(CONCRETE_RANDOM);
}
UNIT_TEST(test_concretization_linear_own_pmd)
UNIT_TEST(test_concretization_random_own_pmd)
void __test_concretization_own_pmd(concretize_type_t conc_type) {
litmus_test_t test = {
"test",
0,NULL,
2,(const char*[]){"x","y"},
0,(const char*[]){},
INIT_STATE(
2,
INIT_REGION_OWN(x, REGION_OWN_PMD),
INIT_REGION_OWN(y, REGION_OWN_PMD),
)
};
test_ctx_t ctx;
init_test_ctx(&ctx, &test, SIZE_OF_TEST, 1);
initialize_regions(&ctx.heap_memory);
void* st = concretize_init(conc_type, &ctx, ctx.cfg, ctx.no_runs);
concretize(conc_type, &ctx, ctx.cfg, st, ctx.no_runs);
for (run_idx_t r = 0; r < ctx.no_runs; r++) {
uint64_t* x = VAR(&ctx, r, "x");
uint64_t* y = VAR(&ctx, r, "y");
uint64_t xpmd = PMD(x);
uint64_t ypmd = PMD(y);
ASSERT(xpmd != ypmd, "x (%p) and y (%p) were placed in the same pmd", x, y);
}
}
void test_concretization_linear_own_pmd(void) {
__test_concretization_own_pmd(CONCRETE_LINEAR);
}
void test_concretization_random_own_pmd(void) {
__test_concretization_own_pmd(CONCRETE_RANDOM);
}
UNIT_TEST(test_concretization_linear_same_page)
UNIT_TEST(test_concretization_random_same_page)
void __test_concretization_same_page(concretize_type_t conc_type) {
litmus_test_t test = {
"test",
0,NULL,
2,(const char*[]){"x","y"},
0,NULL,
INIT_STATE(
2,
INIT_REGION_OWN(x, REGION_OWN_PAGE),
INIT_REGION_PIN(y, x, REGION_SAME_PAGE),
)
};
test_ctx_t ctx;
init_test_ctx(&ctx, &test, SIZE_OF_TEST, 1);
initialize_regions(&ctx.heap_memory);
void* st = concretize_init(conc_type, &ctx, ctx.cfg, ctx.no_runs);
concretize(conc_type, &ctx, ctx.cfg, st, ctx.no_runs);
/* x and y must be in the same page */
for (run_idx_t r = 0; r < ctx.no_runs; r++) {
ASSERT(PAGE(ctx.heap_vars[0].values[r]) == PAGE(ctx.heap_vars[1].values[r]));
}
}
void test_concretization_linear_same_page(void) {
__test_concretization_same_page(CONCRETE_LINEAR);
}
void test_concretization_random_same_page(void) {
__test_concretization_same_page(CONCRETE_RANDOM);
}
UNIT_TEST(test_concretization_linear_separate_roots)
UNIT_TEST(test_concretization_random_separate_roots)
void __test_concretization_separate_roots(concretize_type_t conc_type) {
litmus_test_t test = {
"test",
0,NULL,
4,(const char*[]){"x","y","a","b"},
0,NULL,
INIT_STATE(
4,
INIT_REGION_OWN(x, REGION_OWN_PAGE),
INIT_REGION_PIN(a, x, REGION_SAME_PAGE_OFFSET),
INIT_REGION_OWN(y, REGION_OWN_PAGE),
INIT_REGION_PIN(b, y, REGION_SAME_PAGE_OFFSET),
)
};
test_ctx_t ctx;
init_test_ctx(&ctx, &test, SIZE_OF_TEST, 1);
initialize_regions(&ctx.heap_memory);
void* st = concretize_init(conc_type, &ctx, ctx.cfg, ctx.no_runs);
concretize(conc_type, &ctx, ctx.cfg, st, ctx.no_runs);
for (run_idx_t r = 0; r < ctx.no_runs; r++) {
ASSERT(PAGE(VAR(&ctx, r, "x")) == PAGE(VAR(&ctx, r, "a")), "x not same page as a");
ASSERT(PAGE(VAR(&ctx, r, "y")) == PAGE(VAR(&ctx, r, "b")), "y not same page as b");
ASSERT(PAGE(VAR(&ctx, r, "x")) != PAGE(VAR(&ctx, r, "y")), "x and y were same page");
}
}
void test_concretization_linear_separate_roots(void) {
__test_concretization_separate_roots(CONCRETE_LINEAR);
}
void test_concretization_random_separate_roots(void) {
__test_concretization_separate_roots(CONCRETE_RANDOM);
}
UNIT_TEST(test_concretization_linear_aliased)
UNIT_TEST(test_concretization_random_aliased)
void __test_concretization_aliased(concretize_type_t conc_type) {
litmus_test_t test = {
"test",
0,NULL,
2,(const char*[]){"x","y"},
0,NULL,
INIT_STATE(
2,
INIT_REGION_OWN(x, REGION_OWN_PAGE),
INIT_ALIAS(y, x),
)
};
test_ctx_t ctx;
init_test_ctx(&ctx, &test, SIZE_OF_TEST, 1);
initialize_regions(&ctx.heap_memory);
void* st = concretize_init(conc_type, &ctx, ctx.cfg, ctx.no_runs);
concretize(conc_type, &ctx, ctx.cfg, st, ctx.no_runs);
for (run_idx_t r = 0; r < ctx.no_runs; r++) {
/* aliased things cannot be in the same page */
ASSERT(PAGE(VAR(&ctx, r, "x")) != PAGE(VAR(&ctx, r, "y")), "x in same page as y");
ASSERT(PAGEOFF(VAR(&ctx, r, "x")) == PAGEOFF(VAR(&ctx, r, "y")), "x and y not same offset in pages");
}
}
void test_concretization_linear_aliased(void) {
__test_concretization_aliased(CONCRETE_LINEAR);
}
void test_concretization_random_aliased(void) {
__test_concretization_aliased(CONCRETE_RANDOM);
}
UNIT_TEST(test_concretization_linear_unrelated_aliased)
UNIT_TEST(test_concretization_random_unrelated_aliased)
void __test_concretization_unrelated_aliased(concretize_type_t conc_type) {
litmus_test_t test = {
"test",
0,NULL,
3,(const char*[]){"x","y","z"},
0,NULL,
INIT_STATE(
3,
INIT_VAR(x, 0),
INIT_VAR(y, 0),
INIT_ALIAS(z, x),
)
};
test_ctx_t ctx;
init_test_ctx(&ctx, &test, SIZE_OF_TEST, 1);
initialize_regions(&ctx.heap_memory);
void* st = concretize_init(conc_type, &ctx, ctx.cfg, ctx.no_runs);
concretize(conc_type, &ctx, ctx.cfg, st, ctx.no_runs);
for (run_idx_t r = 0; r < ctx.no_runs; r++) {
ASSERT(PAGE(VAR(&ctx, r, "x")) != PAGE(VAR(&ctx, r, "y")), "x in same page as y");
ASSERT(PAGE(VAR(&ctx, r, "x")) != PAGE(VAR(&ctx, r, "z")), "x in same page as z");
ASSERT(PAGE(VAR(&ctx, r, "y")) != PAGE(VAR(&ctx, r, "z")), "y in same page as z");
ASSERT(PAGEOFF(VAR(&ctx, r, "x")) == PAGEOFF(VAR(&ctx, r, "z")), "x and y not same offset in pages");
}
}
void test_concretization_linear_unrelated_aliased(void) {
__test_concretization_unrelated_aliased(CONCRETE_LINEAR);
}
void test_concretization_random_unrelated_aliased(void) {
__test_concretization_unrelated_aliased(CONCRETE_RANDOM);
}
UNIT_TEST(test_concretization_linear_unmapped)
UNIT_TEST(test_concretization_random_unmapped)
void __test_concretization_unmapped(concretize_type_t conc_type) {
litmus_test_t test = {
"test",
0,NULL,
3,(const char*[]){"x","y","z"},
0,NULL,
INIT_STATE(
3,
INIT_UNMAPPED(x),
INIT_VAR(y, 0),
INIT_VAR(z, 1)
),
};
test_ctx_t ctx;
init_test_ctx(&ctx, &test, SIZE_OF_TEST, 1);
initialize_regions(&ctx.heap_memory);
void* st = concretize_init(conc_type, &ctx, ctx.cfg, ctx.no_runs);
concretize(conc_type, &ctx, ctx.cfg, st, ctx.no_runs);
for (run_idx_t r = 0; r < ctx.no_runs; r++) {
/* no other var on any other run got given the same page as x on this run */
uint64_t* x = VAR(&ctx, r, "x");
uint64_t xpage = PAGE(x);
for (var_idx_t varidx = 0; varidx < ctx.cfg->no_heap_vars; varidx++) {
if (varidx != idx_from_varname(&ctx, "x")) {
for (run_idx_t r2 = 0; r2 < ctx.no_runs; r2++) {
uint64_t* v2 = ctx.heap_vars[varidx].values[r2];
uint64_t v2page = PAGE(v2);
ASSERT(v2page != xpage, "x (%p) and %s (%p) had same page", x, ctx.heap_vars[varidx].name, v2);
}
}
}
}
}
void test_concretization_linear_unmapped(void) {
__test_concretization_unmapped(CONCRETE_LINEAR);
}
void test_concretization_random_unmapped(void) {
__test_concretization_unmapped(CONCRETE_RANDOM);
}
UNIT_TEST(test_concretization_linear_twopage)
UNIT_TEST(test_concretization_random_twopage)
void __test_concretization_twopage(concretize_type_t conc_type) {
litmus_test_t test = {
"test",
0,NULL,
4,(const char*[]){"a1", "a2", "b1", "b2"},
0,NULL,
INIT_STATE(
4,
INIT_REGION_OWN(a1, REGION_OWN_PAGE),
INIT_REGION_OWN(b1, REGION_OWN_PAGE),
INIT_REGION_PIN(a2, a1, REGION_SAME_PAGE),
INIT_REGION_PIN(b2, b1, REGION_SAME_PAGE),
),
};
test_ctx_t ctx;
init_test_ctx(&ctx, &test, SIZE_OF_TEST, 1);
initialize_regions(&ctx.heap_memory);
void* st = concretize_init(conc_type, &ctx, ctx.cfg, ctx.no_runs);
concretize(conc_type, &ctx, ctx.cfg, st, ctx.no_runs);
for (run_idx_t r = 0; r < ctx.no_runs; r++) {
/* no other var on any other run got given the same page as x on this run */
uint64_t a1page = PAGE(VAR(&ctx, r, "a1"));
uint64_t a2page = PAGE(VAR(&ctx, r, "a2"));
uint64_t b1page = PAGE(VAR(&ctx, r, "b1"));
uint64_t b2page = PAGE(VAR(&ctx, r, "b2"));
ASSERT(a1page==a2page, "a1 and a2 weren't same page");
ASSERT(b1page==b2page, "b1 and b2 weren't same page");
ASSERT(a1page!=b1page, "b1 and a1 were same page");
}
}
void test_concretization_linear_twopage(void) {
__test_concretization_twopage(CONCRETE_LINEAR);
}
void test_concretization_random_twopage(void) {
__test_concretization_twopage(CONCRETE_RANDOM);
}
UNIT_TEST(test_concretization_linear_relpmdoverlap)
UNIT_TEST(test_concretization_random_relpmdoverlap)
void __test_concretization_relpmdoverlap(concretize_type_t conc_type) {
litmus_test_t test = {
"test",
0,NULL,
2,(const char*[]){"x", "y"},
0,NULL,
INIT_STATE(
2,
INIT_REGION_OWN(x, REGION_OWN_PMD),
INIT_REGION_OFFSET(y, x, REGION_SAME_PMD_OFFSET),
),
};
test_ctx_t ctx;
init_test_ctx(&ctx, &test, SIZE_OF_TEST, 1);
initialize_regions(&ctx.heap_memory);
void* st = concretize_init(conc_type, &ctx, ctx.cfg, ctx.no_runs);
concretize(conc_type, &ctx, ctx.cfg, st, ctx.no_runs);
for (run_idx_t r = 0; r < ctx.no_runs; r++) {
/* no other var on any other run got given the same page as x on this run */
uint64_t xpmd = PMD(VAR(&ctx, r, "x"));
uint64_t ypmd = PMD(VAR(&ctx, r, "y"));
uint64_t xpmdoff = PMDOFF(VAR(&ctx, r, "x"));
uint64_t ypmdoff = PMDOFF(VAR(&ctx, r, "y"));
ASSERT(xpmd != ypmd, "x and y were same pmd");
ASSERT(xpmdoff == ypmdoff, "x and y had different offsets");
}
}
void test_concretization_linear_relpmdoverlap(void) {
__test_concretization_relpmdoverlap(CONCRETE_LINEAR);
}
void test_concretization_random_relpmdoverlap(void) {
__test_concretization_relpmdoverlap(CONCRETE_RANDOM);
}
UNIT_TEST(test_concretization_linear_multi_pmd_pin)
UNIT_TEST(test_concretization_random_multi_pmd_pin)
void __test_concretization_multi_pmd_pin(concretize_type_t conc_type) {
litmus_test_t test = {
"test",
0,NULL,
3,(const char*[]){"x", "y", "z"},
0,NULL,
INIT_STATE(
8,
INIT_VAR(x, 0),
INIT_VAR(y, 1),
INIT_VAR(z, 2),
INIT_REGION_OWN(x, REGION_OWN_PMD),
INIT_REGION_PIN(y, x, REGION_SAME_PMD),
INIT_REGION_OFFSET(y, x, REGION_SAME_PAGE_OFFSET),
INIT_REGION_OWN(z, REGION_OWN_PMD),
INIT_REGION_OFFSET(z, x, REGION_SAME_PMD_OFFSET),
),
};
test_ctx_t ctx;
init_test_ctx(&ctx, &test, SIZE_OF_TEST, 1);
initialize_regions(&ctx.heap_memory);
void* st = concretize_init(conc_type, &ctx, ctx.cfg, ctx.no_runs);
concretize(conc_type, &ctx, ctx.cfg, st, ctx.no_runs);
for (run_idx_t r = 0; r < ctx.no_runs; r++) {
/* no other var on any other run got given the same page as x on this run */
uint64_t* x = VAR(&ctx, r, "x");
uint64_t* y = VAR(&ctx, r, "y");
uint64_t* z = VAR(&ctx, r, "z");
uint64_t xpmd = PMD(x);
uint64_t ypmd = PMD(y);
uint64_t zpmd = PMD(z);
uint64_t xpmdoff = PMDOFF(x);
uint64_t zpmdoff = PMDOFF(z);
uint64_t xpageoffs = PAGEOFF(x);
uint64_t ypageoffs = PAGEOFF(y);
uint64_t zpageoffs = PAGEOFF(z);
ASSERT(xpmd != zpmd, "x (%p) and z (%p) were placed in same pmd", x, z);
ASSERT(xpmd == ypmd, "x and y were not pinned to the same pmd");
ASSERT(xpmdoff == zpmdoff, "x and z did not have same pmd offset");
ASSERT(xpageoffs == ypageoffs, "x and y did not have same page offset");
ASSERT(xpageoffs == zpageoffs, "x and z did not have same page offset");
}
}
void test_concretization_linear_multi_pmd_pin(void) {
__test_concretization_multi_pmd_pin(CONCRETE_LINEAR);
}
void test_concretization_random_multi_pmd_pin(void) {
__test_concretization_multi_pmd_pin(CONCRETE_RANDOM);
}
|
C
|
#include<stdio.h>
int main()
{
char name[30];
float sa;
double se,TOTAL;
gets(name);
scanf("%f %lf",&sa,&se);
TOTAL = sa + (se * 15)/100;
printf("TOTAL = R$ %0.2lf\n",TOTAL);
return 0;
}
|
C
|
#include "input.h"
#include "future.h"
#include <stdio.h>
#include <string.h>
deck_t * hand_from_string(const char * str, future_cards_t * fc) {
deck_t * hand = malloc(sizeof(*hand));
hand->cards = NULL;
hand->n_cards = 0;
while(str != NULL && *str != '\0') {
if (*str == ' ') {
str++;
continue;
} else {
char value = *str;
str++;
if(value == '?') {
int index = atoi(str);
str = strchr(str, ' ');
add_future_card(fc, index, add_empty_card(hand));
} else {
char suit = *str;
str++;
add_card_to(hand, card_from_letters(value, suit));
}
}
//str++;
}
if (hand->n_cards < 5) {
fprintf(stderr, "Each hand should have at least 5 cards.\n");
exit(EXIT_FAILURE);
}
return hand;
}
/*
This function reads the input from input file f (has one
hand per line represented with a deck_t) It allocates a
deck_t for each hand and place it into an array of
pointers to deck_ts. This function needs to tell its
caller how many hands it read. We could return a struct,
but we are going to do this a different way: it will fill
in *n_hands with the number of hands.
*/
deck_t ** read_input(FILE * f, size_t * n_hands, future_cards_t * fc) {
deck_t ** arr = NULL;
*n_hands = 0;
ssize_t nread = 0;
char *line = NULL;
size_t len = 0;
while((nread = getline(&line, &len, f)) != -1 ) {
line[nread - 1] = '\0';
(*n_hands)++;
arr = realloc(arr, sizeof(*arr) * (*n_hands));
arr[*n_hands - 1] = hand_from_string(line, fc);
}
free(line);
return arr;
}
|
C
|
#include "simply.h"
#include <stdio.h>
#include <sys/times.h>
#include <unistd.h>
#define N 1000000000
main(int argc, char *argv[]){
double w, result = 0.0, temp;
int i,myid,nproc;
struct SIMPLY_status myStatus;
struct tms a;
int t1,t2,t3,t4;
t1 = times(&a);
simply_init(&argc,&argv);
simply_comm_rank(&myid);
simply_comm_size(&nproc);
t2 = times(&a);
w = 1.0/((double)N);
for(i=myid; i<N; i+=nproc)
result += 4*w/(1+(i+0.5)*(i+0.5)*w*w);
t2 = times(&a);
simply_reduce(&result,&result,1,SIMPLY_DOUBLE, SIMPLY_SUM,0);
if(myid == 0)
printf("pi = %.45lf\n", result);
t3 = times(&a);
simply_barrier();
simply_finalize();
t4 = times(&a);
if(myid == 0)
{
printf("Total time: %lf\n", (double)(t4-t1)/sysconf(_SC_CLK_TCK) );
printf("Time for communications: %lf\n", (double)(t3-t2)/sysconf(_SC_CLK_TCK) );
printf("Time for init: %lf\n", (double)(t2-t1)/sysconf(_SC_CLK_TCK) );
}
}
|
C
|
#include "circularLinkedList.h"
#include <stdio.h>
#include <stdlib.h>
struct Node
{
ET Element;
Pos Prev;
Pos Next;
};
/**---- BASIC LIST OPERATION ----**/
List
makeEmpty()
{
List L = malloc(sizeof(struct Node));
L->Next = NULL;
L->Prev = NULL;
return L;
}
void
insert(ET elem, List L, Pos position)
{
Pos tmpNode;
tmpNode = malloc(sizeof(struct Node));
tmpNode->Element = elem;
tmpNode->Next = position->Next;
if (position->Next != NULL)
{
position->Next->Prev = tmpNode;
}
tmpNode->Prev = position;
position->Next = tmpNode;
}
void
deleteNode(Pos position)
{
Pos tmp = position;
tmp->Prev->Next = tmp->Next;
tmp->Next->Prev = tmp->Prev;
free(tmp);
}
/**---- VARIOUS LIST PROBLEMS ----**/
List
initializeList(ET A[], int arrayLen)
{
List L = makeEmpty();
Pos dummyL = L;
int i;
for(i = 0; i < arrayLen; i++)
{
insert(A[i], L, dummyL);
dummyL = dummyL->Next;
}
dummyL->Next = L;
L->Prev = dummyL;
return L;
}
void
printList(List L)
{
Pos dummyL;
dummyL = L->Next;
while(dummyL != NULL && dummyL != L)
{
printf("%s %d <->", (dummyL->Prev == L) ? ("<->") : (""), dummyL->Element);
dummyL = dummyL->Next;
}
}
/* Runtime analysis: O(MN)
*/
ET
circularDoubleLinkedListJosephus(ET N, ET M)
{
/* int i; */
/* ET people[N] = {0}; */
/* for (i = 0; i < N; i++) */
/* { */
/* people[i] = i + 1; */
/* } */
int counter = N; // count how many elements left
int j = 1; // count how many element we have traversed for each round
// initialize the arr
int i;
int* people;
people = calloc(N, sizeof(int));
//people = malloc(N*sizeof(int)); // can use either 'malloc' or 'calloc' in this case
for ( i = 0; i < N; i++)
{
*(people + i) = i + 1;
}
// construct the list
List L = initializeList(people, N);
Pos dummyL = L->Next;
// start to work on the problem
ET M_prime = M % N;
while (counter > 1)
{
while (j < M_prime)
{
dummyL = dummyL->Next;
// handle the case when a data node is followed by a header.
// in that case, we don't want to remove the header node and we
// want to move on to the actual data node.
if (dummyL != L)
{
j++;
}
}
Pos tmp = dummyL->Next;
deleteNode(dummyL);
dummyL = tmp;
counter--;
j = 1;
// we should start to count M when we on a data node, not a header node.
if (dummyL == L)
{
dummyL = dummyL->Next;
}
}
return dummyL->Element;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: wfung <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/05 17:10:10 by wfung #+# #+# */
/* Updated: 2017/02/14 20:10:43 by wfung ### ########.fr */
/* */
/* ************************************************************************** */
/*
#include "fillit.h"
#include <stdio.h> //to test print output
int main(void) //example practice to create square exterior
{
char k;
char grid[10][10];
int x = 0;
int y = 0;
k = 65;
while (x < 10)
{
while (y < 10)
{
if (y == 0 || y == 9)
k = '*';
else if (x == 0 || x == 9)
k = '$';
else if (x == y)
k = '#';
else
k = ' ';
grid[x][y] = k;
printf("%c", grid[x][y]);
y++;
}
printf("\n");
y = 0;
x++;
}
*/ //testing creating 2d grid/array
/*
printf("42 *, 43 +, 44 , 45 -\n");
grid[i][j] = '*';
grid[i][j + 1] = '!';
grid[j + 1][i] = '@';
grid[j + 1][i + 1] = '#';
while (i < 2 )
{
while (j < 2)
{
printf("%c ", grid[i][j]);
j++;
}
j = 0;
printf("\n");
i++;
}
*/ //testing matching of grid values
//build shape == ft_strdup
// TO DO LIST
//
// make variations of shape EQUAL
//read up on 2d array
//linked list with 2 datas; 1 for letter count (4 per shape) & 1 for map (piece touching)
//
//choose between linked list or 2darray or use both?
//
//>>>>>>>>>>>>>>> LOGIC of program <<<<<<<<<<<<<<
//
// >>>open file??maybe should be 1) use open for fd
// 1) check input if valid in chk_input
// a)chk input size + # of shapes
// b)chk shape(s)
// 2) pass return values to build_shape?
// a) if error, print error message + free whatever?<<<<<<
// b) if valid, shape letter; might not need to malloc, just replace chars
// 3)match shape
// a)set variations as same
// 4)create map
// a) create all possible solutions
// b) select smallest possible upper left square
// 5)print map
// 6)close files? fd? exit?
// 7) free stuff?
//
//
//
// >>>>> CURRENTLY MADE STUFF <<<<<
//
// 1) ft_chk_input
// a) ft_chk_char checks input chars
// b) ft_chk_count checks count of input chars
// i)ft_chk_block checks each block if shape_count > 1; every 21
// 2) ft_matchx
// a) ft_shape_chk checks each shape of inputs
// 1)ft_shape1 checks shape 1 - 11
// 2)ft_shape2 checks shape 2 - 19
// 3) ft_shape_count counts # of shapes in input
// ------------------------
// 4) ft_convert_shape converts return of ft_matchx to that specific shape
// 4a)ft_shape_letter
// 5) ft_build_map builds a map based off of how many pieces input
// maybe like a 4x4 per piece? or smaller
// a) grows square by +1 x +1 til it can fit it
// i) if can fit, ft_packing - returns size of square
// ii) if can't fit, increase square by +1 x +1
// 6) ft_sort_map if fits from (5), sorts maps by area of perfect square
// returns smallest sorted square
// 7) ft_display prints/displays result
|
C
|
#include <stdio.h>
#define MaxTree 10
#define Null -1
#define ElementType char
#define Tree int
struct TreeNode
{
ElementType Element;
Tree left;
Tree right;
} T1[MaxTree], T2[MaxTree];
Tree BuildTree(struct TreeNode T[])
{
int N, j;
scanf("%d\n", &N);
int ROOT = Null;
if (N)
{
int i;
char cl, cr;
int check[N];
for (i = 0; i < N; i++)
check[i] = 0;
for (i = 0; i < N; i++)
{
scanf("%c %c %c\n", &T[i].Element, &cl, &cr);
if (cl != '-')
{
T[i].left = cl - '0';
check[T[i].left] = 1;
}
else
cl = Null;
if (cr != '-')
{
T[i].right = cr - '0';
check[T[i].right] = 1;
}
else
cr = Null;
}
for (j = 0; j < N; j++)
{
if (check[j] == 0)
{
ROOT = j;
break;
}
}
return ROOT;
}
}
Tree Isomerphic(Tree R1, Tree R2)
{
if (R1 == Null && R2 == Null)
return 1;
if ((R1 == Null && R2 != Null) || (R1 != Null && R2 == Null))
return 0;
if (T1[R1].Element != T2[R2].Element)
return 0;
if ((T1[R1].Element == T2[R2].Element) &&
(T1[T1[R1].left].Element == T2[T2[R2].left].Element))
return Isomerphic(T1[R1].left, T2[R2].right);
if ((T1[R1].Element == T2[R2].Element) &&
(T1[T1[R1].left].Element == T2[T2[R2].right].Element))
return Isomerphic(T1[R1].left, T2[R2].right);
if ((T1[R1].Element == T2[R2].Element) &&
(T1[T1[R1].right].Element == T2[T2[R2].left].Element))
return Isomerphic(T1[R1].right, T2[R2].left);
if ((T1[R1].Element == T2[R2].Element) &&
(T1[T1[R1].right].Element == T2[T2[R2].right].Element))
return Isomerphic(T1[R1].right, T2[R2].right);
}
int main()
{
int R1 = BuildTree(T1);
int R2 = BuildTree(T2);
if (Isomerphic(R1, R2))
printf("YES");
else
printf("No");
return 0;
}
|
C
|
/* 1) Elaborar um programa para ler valores inteiros (incluindo valores positivos e negativos) até
que o valor zero seja informado. O valor zero não deverá ser considerado. Informar o maior e
o menor entre os valores positivos lidos e apresentar a média dos valores negativos
informados.
Obs.: verificar que não sejam realizadas divisões por zero. */
#include <stdio.h>
int main(void)
{
char repetir;
int numero = 1;
int maior, menor;
float media;
int qtdenegativo;
char entrada;
int soma;
do
{
system("cls");
entrada = 's';
qtdenegativo = 0;
soma = 0;
do
{
printf("Insira um numero (saida = 0): ");
scanf("%d", &numero);
if (numero > 0)
{
if (entrada == 's')
{
maior = numero;
menor = numero;
entrada = 'r';
}
else
{
if (numero > maior)
{
maior = numero;
}
else if (numero < menor)
{
menor = numero;
}
}
}
else if (numero < 0)
{
numero = numero * (-1);
soma = soma + numero;
qtdenegativo++;
}
} while (numero != 0);
printf("Maior => %d\nMenor => %d\n", maior, menor);
if (qtdenegativo != 0)
{
media = (float)soma / qtdenegativo;
printf("Media dos numero negativos é de: %.2f\n", media);
}
else
{
printf("Impossivel calcular media !!!\n");
}
printf("Deseja repetir o programa(S/s para sim): ");
fflush(stdin);
scanf("%c", &repetir);
} while (repetir == 'S' || repetir == 's');
return 0;
}
|
C
|
/* ************************************************************************** */
/* LE - / */
/* / */
/* option.c .:: .:/ . .:: */
/* +:+:+ +: +: +:+:+ */
/* By: beduroul <marvin@le-101.fr> +:+ +: +: +:+ */
/* #+# #+ #+ #+# */
/* Created: 2019/05/06 19:00:30 by beduroul #+# ## ## #+# */
/* Updated: 2019/05/09 20:52:42 by beduroul ### #+. /#+ ###.fr */
/* / */
/* / */
/* ************************************************************************** */
#include "ft_ls.h"
char *option_i(char *itoatmp, t_recu *tmp, t_max max, char *str)
{
itoatmp = ft_itoa(tmp->neod);
ft_strcpy(str, itoatmp);
rspace(max.i_max - ft_intsize(tmp->neod) + 1, str);
ft_strcat(str, tmp->perm);
return (str);
}
void p_cat(t_recu *list, char *str, t_option op)
{
(void)op;
if (list->perm[0] == 'd')
ft_strcat(str, "/");
if (!op.p && list->perm[0] == 'l')
ft_strcat(str, "@");
if (!op.p && list->perm[0] == 'p')
ft_strcat(str, "|");
if (list->perm[0] == '-' && list->perm[3] == 'x' && list->perm[6] == 'x'
&& list->perm[9] == 'x' && !op.p)
ft_strcat(str, "*");
}
void put_m(t_recu *list, t_max max, t_option op)
{
int c;
c = 0;
while (list)
{
if (op.i)
{
ft_putnbr(list->neod);
ft_putspace(1);
}
c += ft_strlen(list->name) + 2;
if (list->next && (int)ft_strlen(list->next->name) + 3 + c >=
max.te_max)
{
write(1, "\n", 1);
c = 0;
}
ft_putstr(list->name);
if (list->next)
ft_putstr(", ");
else
putchar('\n');
list = (op.r ? list->prev : list->next);
}
}
void put_one(t_recu *list, t_max max, t_option op)
{
while (list)
{
if (op.i)
{
ft_putnbr(list->neod);
ft_putspace(max.i_max - ft_intsize(list->neod) + 1);
}
op.g_color ? put_name(list, op) : ft_putendl(list->name);
list = (op.r ? list->prev : list->next);
}
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
/* Variables and functions */
scalar_t__ malloc (size_t) ;
int /*<<< orphan*/ memcpy (char*,char const*,size_t) ;
int /*<<< orphan*/ strcpy (char*,char const*) ;
char* strdup (char const*) ;
size_t strlen (char const*) ;
char* strstr (char const*,char const*) ;
char *string_replace_substring(const char *in,
const char *pattern, const char *replacement)
{
size_t numhits, pattern_len, replacement_len, outlen;
const char *inat = NULL;
const char *inprev = NULL;
char *out = NULL;
char *outat = NULL;
/* if either pattern or replacement is NULL,
* duplicate in and let caller handle it. */
if (!pattern || !replacement)
return strdup(in);
pattern_len = strlen(pattern);
replacement_len = strlen(replacement);
numhits = 0;
inat = in;
while ((inat = strstr(inat, pattern)))
{
inat += pattern_len;
numhits++;
}
outlen = strlen(in) - pattern_len*numhits + replacement_len*numhits;
out = (char *)malloc(outlen+1);
if (!out)
return NULL;
outat = out;
inat = in;
inprev = in;
while ((inat = strstr(inat, pattern)))
{
memcpy(outat, inprev, inat-inprev);
outat += inat-inprev;
memcpy(outat, replacement, replacement_len);
outat += replacement_len;
inat += pattern_len;
inprev = inat;
}
strcpy(outat, inprev);
return out;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "lista.h"
lista cria_lista(){
lista l;
l = (lista)malloc(sizeof(TLista));
if(l){ //(lista!=NULL)
l->first = NULL;
l->last = NULL;
l->sizeLista=0;
}
return l;
}//cria_lista;
void termina_lista(lista l){
TNodoLista *p;
while(l->first != NULL){
p = l->first;
l->first = l->first->next;
free(p);
}
free(l);
}//termina_lista
int insere_final(lista l, TElemento e){
TNodoLista *p;
p = (TNodoLista*)malloc(sizeof(TNodoLista));
if(p==NULL)
return 0;
p->info=e;
p->next = NULL;
if(l->first==NULL)
l->first = p;
else
l->last->next = p;
l->last = p;
l->sizeLista++;
return 1;
}
int remove_elemento(lista l, int indice){
TNodoLista *p, *ant;
int i;
if(indice>=1 && indice<=l->sizeLista){
p=l->first;
for(i=1; i<indice; i++){
ant = p;
p=p->next;
}
if(l->first==p)
l->first = l->first->next; /*l->first = p->next*/
else if(l->last==p){
l->last = ant;
l->last->next = NULL;
}
else
ant->next = p->next;
free(p);
l->sizeLista--;
return 1;
}
return 0;
}
|
C
|
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
int main()
{
/* Exercise 1-11:
Test the word count program on ' ', new lines, and tabs, including multiple spaces, new lines, and/or tabs in a row. This assumes that other symbols do not denote separation of words, such as punctuation (.,!) or symbols such as '&' when there is no space between the words (salt&pepper will be one word)*/
/* Exercise 1-12 */
int c, state;
state = OUT;
c = 0;
while ((c = getchar()) != EOF) {
if (c == '\n' || c == ' ' || c == '\t') {
if (state != OUT) {
putchar('\n');
state = OUT;
}
}
else {
state = IN;
putchar(c);
}
}
}
|
C
|
#define _BSD_SOURCE // usleep()
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dlfcn.h>
#include "game.h"
const char *GAME_LIBRARY = "./libgame.so";
struct game {
void *handle;
ino_t id;
struct game_api api;
struct game_state *state;
};
static void game_load(struct game *game)
{
struct stat attr;
if ((stat(GAME_LIBRARY, &attr) == 0) && (game->id != attr.st_ino)) {
if (game->handle) {
game->api.unload(game->state);
dlclose(game->handle);
}
void *handle = dlopen(GAME_LIBRARY, RTLD_NOW);
if (handle) {
game->handle = handle;
game->id = attr.st_ino;
const struct game_api *api = dlsym(game->handle, "GAME_API");
if (api != NULL) {
game->api = *api;
if (game->state == NULL)
game->state = game->api.init();
game->api.reload(game->state);
} else {
dlclose(game->handle);
game->handle = NULL;
game->id = 0;
}
} else {
game->handle = NULL;
game->id = 0;
}
}
}
void game_unload(struct game *game)
{
if (game->handle) {
game->api.finalize(game->state);
game->state = NULL;
dlclose(game->handle);
game->handle = NULL;
game->id = 0;
}
}
int main(void)
{
struct game game = {0};
for (;;) {
game_load(&game);
if (game.handle)
if (!game.api.step(game.state))
break;
usleep(100000);
}
game_unload(&game);
return 0;
}
|
C
|
//mpicc questao3.c -o questao3
//mpirun -np 4 ./questao3
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
int calculaPrimos(int n){
int k, j, i=3, soma=2;
for(k = 2; k < n; k++ ){
for(j = 2; j < i; j++){
if(i%j==0)
break;
}
if(j==i){
soma+=i;
}
i++;
}
return soma;
}
int main(int argc, char const *argv[])
{
int num_proc, id_rank, n, soma=2, primos;
MPI_Init(NULL,NULL);
MPI_Comm_size(MPI_COMM_WORLD,&num_proc);
MPI_Comm_rank(MPI_COMM_WORLD,&id_rank);
if(id_rank!=0){
MPI_Reduce(&primos,&soma,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD); //Reduces values on all processes to a single value
// MPI_Recv(&soma, 1, MPI_INT, (num_proc-1), 0, MPI_COMM_WORLD,MPI_STATUS_IGNORE);
}
if(id_rank==0){
printf("Digite o numero:\n");
scanf("%d",&n);
MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD);
soma = calculaPrimos(n);
//MPI_Reduce(&soma,&primos,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD);
MPI_Send(&soma, 1, MPI_INT, (id_rank+1)%num_proc, 0, MPI_COMM_WORLD);
printf("%d\n", soma);
}
MPI_Finalize();
return 0;
}
|
C
|
#include "img2.h"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **tmp_strsplit(char *s, char c)
{
char **res;
int i;
i = -1;
if (!s || !strlen(s))
return (0);
res = malloc((strlen(s) / 2 + 1) * sizeof(char*));
s = _strdup(s);
while (*s)
{
while (*s == c)
{
*s = '\0';
++s;
}
res[++i] = s;
while (*s && *s != c)
++s;
}
res[++i] = 0;
return (res);
}
t_kernel* load_kernel(char *src)
{
FILE* file;
char* line;
char** tab;
int width;
int height;
t_kernel* k;
int i;
fopen_s(&file, src, "r");
if (!file)
{
printf("can't open file\n");
return (0);
}
height = 0;
width = 0;
k = malloc(sizeof(t_kernel));
k->ddata = malloc(sizeof(double) * MAX_KERNEL_SIZE);
while (!feof(file)) {
i = -1;
char c;
line = malloc(255);
while (fread_s(&c, 1, sizeof(char), 1, file) && c != '\n')
if (c != '\r')
line[++i] = c;
line[++i] = '\0';
if (!strlen(line))
break;
tab = tmp_strsplit(line, ' ');
i = -1;
while (tab[++i])
{
k->ddata[height * width + i] = atof(tab[i]);
}
if (tab[0])
{
free(tab[0]);
tab[0] = 0;
}
if (tab)
{
// free(tab); // TODO
tab = 0;
}
free(line);
if (i)
++height;
if (!width)
width = i;
}
k->width = width;
k->height = height;
fclose(file);
return (k);
}
void kernel_destroy(t_kernel* k)
{
free(k->ddata);
free(k);
}
|
C
|
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include "ordenacao.h"
#include "utils.h"
bool twosum_bruteforce(int *v, int n, int x)
{
}
int main(int argc, char** argv)
{
int v[] = {2, -1, 5, 8, 7, 4};
int n = 6;
twosum_bruteforce(v, n, 14);
return EXIT_SUCCESS;
}
|
C
|
#ifndef UTILS_TIME_H
#define UTILS_TIME_H
#include <time.h>
#include <sys/time.h>
#define RFC3339_SIZE 26 /* 2006-01-02T15:04:05+00:00 */
/* rfc3339 formats a cdtime_t time as UTC in RFC 3339 zulu format with second
* precision, e.g., "2006-01-02T15:04:05Z". */
int rfc3339(char *buffer, size_t buffer_size, time_t t);
/* rfc3339 formats a cdtime_t time as local in RFC 3339 format with second
* precision, e.g., "2006-01-02T15:04:05+00:00". */
int rfc3339_local(char *buffer, size_t buffer_size, time_t t);
int timeval_cmp(struct timeval tv0, struct timeval tv1, struct timeval *delta);
/* make sure tv_usec stores less than a second */
#define NORMALIZE_TIMEVAL(tv) \
do { \
(tv).tv_sec += (tv).tv_usec / 1000000; \
(tv).tv_usec = (tv).tv_usec % 1000000; \
} while (0)
/* make sure tv_sec stores less than a second */
#define NORMALIZE_TIMESPEC(tv) \
do { \
(tv).tv_sec += (tv).tv_nsec / 1000000000; \
(tv).tv_nsec = (tv).tv_nsec % 1000000000; \
} while (0)
#endif /* UTILS_TIME_H */
|
C
|
//
// xSemaphore.h - x-platform semaphore for iOS & Android (POSIX)
// AudioFetchSDK
//
// Copyright © 2019 Beach Cities Software, LLC. All rights reserved.
//
#ifndef xsemaphore_h
#define xsemaphore_h
#include <stdint.h>
#include <sys/time.h>
#include <sys/types.h>
#include <errno.h>
#if __APPLE__
#define __USE_DISPATCH__
#endif
#ifdef __USE_DISPATCH__
#include <dispatch/dispatch.h>
#else
#include <semaphore.h>
#endif
/**
Returns unix time in milliseconds
(millis. since the Unix Epoch, Jan. 1, 1970 00:00:00)
@return Returns the current unix time in milliseconds
*/
static inline uint64_t unix_time() {
struct timeval tv;
gettimeofday(&tv, NULL);
uint64_t unixts = ((uint64_t) (tv.tv_sec) * 1000) +
((uint64_t) (tv.tv_usec) / 1000);
return unixts;
}
/**
Unix timestamp in seconds
@return Returns the current unix time converted to seconds
*/
static inline uint64_t unix_timestamp() {
uint64_t unixTimeSeconds = unix_time() / 1000;
return unixTimeSeconds;
}
/**
x-platform (iOS/Android - POSIX) semaphore
*/
typedef struct xsemaphore {
#ifdef __USE_DISPATCH__
dispatch_semaphore_t sem;
#else
sem_t sem;
#endif
} xsemaphore;
/**
Init xsemaphore
@param s - The xsemaphore
@param value - The value for the semaphore
@return Returns the 0 on success, anything else on failure.
*/
static inline int xsem_init(struct xsemaphore *s, uint32_t value) {
#ifdef __USE_DISPATCH__
dispatch_semaphore_t *sem = &s->sem;
*sem = dispatch_semaphore_create(value);
return 0;
#else
return sem_init(&s->sem, 0, value);
#endif
}
/**
Wait for semaphore
@param s - The xsemaphore
@param timeoutMS - Timeout in milliseconds, or >= 0 for infinite wait.
@return Returns the result from the respective wait call.
*/
static inline long xsem_wait(struct xsemaphore *s, uint64_t timeoutMS = -1) {
#ifdef __USE_DISPATCH__
timeoutMS = (timeoutMS > 0) ? timeoutMS : DISPATCH_TIME_FOREVER;
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeoutMS / 1000) * (double)NSEC_PER_SEC);
return dispatch_semaphore_wait(s->sem, time);
#else
int r;
uint64_t now = unix_time();
uint64_t end = (timeoutMS <= 0) ? now : (now + timeoutMS);
do {
now = unix_time();
r = sem_wait(&s->sem);
if (timeoutMS > 0 && now > end) {
break;
}
} while (r == -1 && errno == EINTR);
return (long)r;
#endif
}
/**
Posts/Signals xsemaphore
@param s - The xsemaphore
@return Returns the result from the respective post/signal call (platform-specific).
*/
static inline long xsem_post(struct xsemaphore *s) {
#ifdef __USE_DISPATCH__
return dispatch_semaphore_signal(s->sem);
#else
return (long)sem_post(&s->sem);
#endif
}
/**
Destroys/Releases the xsemaphore
@param s - The xsemaphore
@return Returns the 0 on success, anything else on failure.
*/
static inline int xsem_destroy(struct xsemaphore *s) {
#ifdef __USE_DISPATCH__
dispatch_release(s->sem);
return 0;
#else
return sem_destroy(&s->sem);
#endif
}
#endif /* xsemaphore_h */
|
C
|
// File: c/pointers/function-pointer/compare.c
// Created by hengxin on 17-11-22.
// Illustration of "function pointer" using c "qsort"
#include <stdio.h>
#include "../../../c/array/array.h"
int compare(const void *a, const void *b) {
return (*((int *) a)) - (*((int *) b));
}
int compare_reverse(const void *a, const void *b) {
return (*((int *) b)) - (*((int *) a));
}
/*
* Decide the ordering randomly,
* ignoring the values of @param a and @param b.
*/
int compare_random(const void *a, const void *b) {
int random_integer = rand() % 101 - 50;
if (random_integer > 0) return 1;
if (random_integer < 0) return -1;
return 0;
}
int main(void) {
// natural ordering
int n = 100;
int *values = generate_values(n);
qsort(values, n, sizeof(int), compare);
puts("The natural order is:");
print(values, n);
// reverse ordering
values = generate_values(n);
qsort(values, n, sizeof(int), compare_reverse);
puts("\nThe reverse order is:");
print(values, n);
// random ordering
values = generate_values(n);
srand((unsigned) time(0));
qsort(values, n, sizeof(int), compare_random);
puts("\nThe random order is:");
print(values, n);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
double twoDecs(double n)
{
return (int)(n*100)/100.0;
}
double rand2dot2(bool printDetails)
{
int num = rand();
double doubleNum = (double) (num % 10000) / 100; //to put in form xx.yy e.g. 73.56%
if(printDetails)
{
printf("\nTime = %d", (unsigned int) time(NULL));
printf("\nRand Num: %d", num);
printf("\n%.2lf%%", doubleNum);
}
return doubleNum;
}
int gcd(int a, int b) //courtesy of Stack Overflow
{ //needed for Prob538
int temp;
while (b != 0)
{
temp = a % b;
a = b;
b = temp;
}
return a;
}
char* Prob538(double target)
{
int i, j, closesti = 1, closestj = 1, iter = 0;
double closest = 1;
target/=100; // to put in range 0 to 1
//Following 3 variables are all tweakable depending on personal preference
int limit = 10; //highest denominator for initial stage
double MOE = 0.004; //i.e. 0.4% only applies to chances over 90% or less than 10%
int HighestX5 = 25; //Highest multiple of 5 used as denominator (after 'limit' is reached) before switching to multiples of 10
for(i=1;i<=limit;i++)
{
for(j=1;j<i;j++)
{
printf("\n %d/%d", j, i);
if(i==1&&j==1)
printf("Print, Damn you!"); //why isn't this triggering/isn't 1/1 being printed above?
if(gcd(i,j)==1 && fabs(target - (double)j/i) < fabs(target - closest))
{ //first condition to avoid checking (and changing answer to)
printf("(New closest)"); //redundant fractions like 2/4, 3/9, 8/10
//i.e. any numerator and denominator that aren't relatively prime
closestj = j;
closesti = i;
closest = (double)j/i;
}
iter++;
}
}
for(i=10; fabs(target - closest)>MOE && (target>0.9||target<0.1) && i<=100 ; i+=(i<=HighestX5?5:10))
{
for(j=1;j<i;j++)
{
printf("\n %d/%d", j, i);
if(gcd(i,j)==1 && fabs(target - (double)j/i) < fabs(target - closest))
{ //first condition to avoid checking (and changing answer to)
printf("(New closest)"); //redundant fractions like 2/4, 3/9, 8/10
//i.e. any numerator and denominator that aren't relatively prime
closestj = j;
closesti = i;
closest = (double)j/i;
}
iter++;
}
}
printf("\n\nTarget = %.2lf%%\nCurrent = %d/%d a.k.a %.2lf%%\nDiff = %.2lf%%\n", target*100, closestj, closesti, (double)closestj/closesti*100, fabs(target - (double)closestj/closesti)*100);
printf("%.2lf%% < %.2lf%% MOE : %s\n", fabs(target - (double) closestj / closesti)*100, MOE*100 , fabs(target - (double) closestj / closesti) < MOE ? "True" : "False");
int origJ = closestj, origI = closesti;
printf("\nOriginal version took %d iterations (%d in %d odds) \n", iter, closestj, closesti);
closesti = 1, closestj = 1, iter=0, closest=1, j=1; //reset so that original algorithm's changes don't affect results
bool tooLow; //tooLow referring to the *current* value being lower than the target one
double diff;
for(i=1;i<=limit;i++)
{
printf("\nOuter loop: %d/%d", j, i);
diff = target - (double)j/i;
tooLow = diff > 0 ? true : false;
if (gcd(i,j)==1 && fabs(diff)<fabs(target-closest))
{
printf(" \t(New closest)");
closestj = j;
closesti = i;
closest = (double) j / i;
}
while(tooLow&&i<10) //&&i<10 to prevent cases where it gives the final fraction out of a higher number
//as a result, such as 73.66% giving 8 in 11 instead of 3 in 4
{
j++;
i++;
printf("\n Inner Loop: %d/%d", j, i);
diff = target - (double)j/i;
tooLow = diff > 0 ? true : false;
if(gcd(i,j)==1 && fabs(diff)<fabs(target-closest))
{
printf(" \t(New closest)");
closestj = j;
closesti = i;
closest = (double)j/i;
}
iter++;
}
iter++;
}
printf("\nAlternative version took %d iterations\n", iter);
if (origI!=closesti || origJ != closestj)
{
printf("\nERROR\nERROR\nERROR\nERROR\nERROR\nERROR\nERROR");
}
//TODO: Add final feature of expressing fractions that need more precision than a denominator of 10 can offer
//e.g. 6.58% , 97.51%, not by extending the denominator of 10 to 11, 12 so on, but by testing neater denominators
//of multiples of certain numbers, such as of 5s or 10s, which would give probabilities of 1 in 15, and 39 in 40
//for the two examples mentioned
unsigned int buffersize = 13 ;
char* buffer = malloc(buffersize);
snprintf(buffer, buffersize, "%d in %d odds", closestj, closesti);
//printf("\n%d in %d odds", closestj, closesti);
return buffer;
}
int main(void)
{
srand((unsigned int)time(NULL));
while(getchar()) //as opposed to running the whole program multiple times because then it wasn't random enough
{
printf("\n%s \n", Prob538(rand2dot2(1)));
}
return 0;
}
|
C
|
#include <stdio.h>
int main(void) {
printf("char:\t%d\n", 'a' != EOF);
printf("EOF:\t%d\n", EOF != EOF);
return 0;
}
|
C
|
/*====================================================*\
Vendredi 8 novembre 2013
Arash HABIBI
Image.c
\*====================================================*/
#include "Image.h"
//------------------------------------------------------------------------
Color C_new(unsigned char red, unsigned char green, unsigned char blue)
{
Color c;
c._red = red;
c._green = green;
c._blue = blue;
return c;
}
//------------------------------------------------------------------------
void C_check(Color c, char *message)
{
fprintf(stderr,"%s : %d %d %d\n",message,c._red,c._green,c._blue);
}
//------------------------------------------------------------------------
Color C_blend(Color c1, Color c2, double blend_coef)
{
Color c;
c._red = (1-blend_coef)*c1._red + blend_coef*c2._red;
c._green = (1-blend_coef)*c1._green + blend_coef*c2._green;
c._blue = (1-blend_coef)*c1._blue + blend_coef*c2._blue;
return c;
}
//------------------------------------------------------------------------
double C_intensity(Color c)
{
double intensity;
if(c._red > c._green)
{
if(c._blue > c._red) intensity = c._blue;
else intensity = c._red;
}
else
{
if(c._blue > c._green) intensity = c._blue;
else intensity = c._green;
}
return intensity;
}
//------------------------------------------------------------------------
//------------------------------------------------------------------------
//------------------------------------------------------------------------
Image* I_new(int width, int height)
{
Image *img_new = (Image*)malloc(sizeof(Image));
img_new->_width = width;
img_new->_height = height;
img_new->_xzoom = 0;
img_new->_yzoom = 0;
img_new->_zoom = 1.0;
img_new->_xoffset=0;
img_new->_yoffset=0;
img_new->_current_color = C_new(255,255,255);
img_new->_min = INFINITY;
img_new->_max = -INFINITY;
img_new->_buffer = (Color**)calloc(width,sizeof(Color*));
int x;
for(x=0;x<width;x++)
img_new->_buffer[x] = (Color*)calloc(height,sizeof(Color));
return img_new;
}
//------------------------------------------------------------------------
// From the zoom and offset data of image, this function returns
// windows coordinates to image coordinates.
static void _windowToImage(Image *img, int xwin, int ywin, int *ximg, int *yimg)
{
*ximg = img->_xzoom + img->_xoffset + (xwin-img->_xzoom) / img->_zoom;
*yimg = img->_yzoom + img->_yoffset + (ywin-img->_yzoom) / img->_zoom;
}
//-----
void I_check(Image *img, char *message)
{
fprintf(stderr,"------------- Check Image %s ------------------\n",message);
fprintf(stderr,"%d x %d pixels.\n",img->_width,img->_height);
fprintf(stderr,"Centre de zoom : (%d,%d)\n",img->_xzoom,img->_yzoom);
fprintf(stderr,"Facteur de zoom : %f\n",img->_zoom);
fprintf(stderr,"Décalage : (%d,%d),\n",img->_xoffset,img->_yoffset);
fprintf(stderr,"Les quatre coins de la fenêtre : \n");
int ximg, yimg;
_windowToImage(img,0,0,&ximg,&yimg);
fprintf(stderr,"0,0 -> ximg=%d yimg=%d\n",ximg,yimg);
_windowToImage(img,img->_width-1,0,&ximg,&yimg);
fprintf(stderr,"%d,0 -> ximg=%d yimg=%d\n",img->_width-1,ximg,yimg);
_windowToImage(img,0,img->_height-1,&ximg,&yimg);
fprintf(stderr,"0,%d -> ximg=%d yimg=%d\n",img->_height-1,ximg,yimg);
_windowToImage(img,img->_width-1,img->_height-1,&ximg,&yimg);
fprintf(stderr,"%d,%d -> ximg=%d yimg=%d\n",img->_width-1,img->_height-1,ximg,yimg);
}
//------------------------------------------------------------------------
static void _plot(Image *img, int x, int y, Color c)
{
img->_buffer[x][y] = c;
}
//-----
Image* I_read(char *ppmfilename)
{
Image *img;
Ppm ppm = PPM_nouv(ppmfilename, PPM_LECTURE);
fprintf(stderr,"%d x %d\n",PPM_largeur(ppm),PPM_hauteur(ppm));
if(ppm!=NULL)
{
img = I_new(PPM_largeur(ppm),PPM_hauteur(ppm));
img->_min = INFINITY;
img->_max = -INFINITY;
int nb_bytes=ppm->_nb_bytes;
int valmax = ppm->_valmax;
int nb_pixels = img->_width*img->_height;
if(nb_bytes<=1)
{
unsigned char *donnees = (unsigned char*)calloc(3*nb_pixels,sizeof(unsigned char));
PPM_lectureDonneesChar(ppm, donnees);
int x,y;
for(y=0;y<img->_height;y++)
for(x=0;x<img->_width;x++)
{
int indice = y*img->_width + x;
Color c = C_new(donnees[3*indice ],
donnees[3*indice+1],
donnees[3*indice+2]);
double intens = C_intensity(c);
if((intens<img->_min)&&(intens>0))
img->_min = intens;
if(intens>img->_max)
img->_max = intens;
_plot(img,x,y,c);
}
}
else
{
unsigned short *donnees = (unsigned short*)calloc(3*nb_pixels,sizeof(unsigned short));
PPM_lectureDonneesShort(ppm, donnees);
int x,y;
for(y=0;y<img->_height;y++)
for(x=0;x<img->_width;x++)
{
int indice = y*img->_width + x;
Color c = C_new((1.0*donnees[3*indice ])/valmax,
(1.0*donnees[3*indice+1])/valmax,
(1.0*donnees[3*indice+2])/valmax);
img->_buffer[x][y] = c;
}
}
PPM_fermeture(ppm);
return(img);
}
else
return(NULL);
}
//------------------------------------------------------------------------
void I_fill(Image *img, Color c)
{
int x,y;
for(x=0;x<img->_width;x++)
for(y=0;y<img->_height;y++)
img->_buffer[x][y]=c;
img->_min = C_intensity(c);
img->_max = C_intensity(c);
}
//------------------------------------------------------------------------
void I_checker(Image *img, Color c1, Color c2, int step)
{
int x,y;
for(x=0;x<img->_width;x++)
for(y=0;y<img->_height;y++)
{
int n_x = x/step;
int n_y = y/step;
if((n_x+n_y)%2==0) _plot(img,x,y,c1);
else _plot(img,x,y,c2);
}
if(C_intensity(c1)<C_intensity(c2))
{
img->_min = C_intensity(c1);
img->_max = C_intensity(c2);
}
else
{
img->_min = C_intensity(c2);
img->_max = C_intensity(c1);
}
}
//------------------------------------------------------------------------
void I_changeColor(Image *img, Color c)
{
img->_current_color = c;
}
//------------------------------------------------------------------------
void I_plot(Image *img, int x, int y)
{
if((x>=0)&&(x<img->_width)&&
(y>=0)&&(y<img->_height))
{
img->_buffer[x][y] = img->_current_color;
double intens = C_intensity(img->_current_color);
if((intens < img->_min)&&(intens>0))
img->_min = intens;
if(intens > img->_max)
img->_max = intens;
}
else
{
fprintf(stderr,"I_plot : ERROR !!!\n");
fprintf(stderr,"x (=%d) must be in the [%d,%d] range and\n", x, 0, img->_width);
fprintf(stderr,"y (=%d) must be in the [%d,%d] range\n", y, 0, img->_height);
}
}
//------------------------------------------------------------------------
void I_plotColor(Image *img, int x, int y, Color c)
{
if((x>=0)&&(x<img->_width)&&
(y>=0)&&(y<img->_height))
{
img->_buffer[x][y] = c;
double intens = C_intensity(c);
if(( intens < img->_min)&&(intens >0))
img->_min = intens;
if(intens > img->_max)
img->_max = intens;
}
else
{
fprintf(stderr,"I_plotColor : ERROR !!!\n");
fprintf(stderr,"x (=%d) must be in the [%d,%d] range and\n", x, 0, img->_width);
fprintf(stderr,"y (=%d) must be in the [%d,%d] range\n", y, 0, img->_height);
}
}
//------------------------------------------------------------------------
// Changement de repère
void I_focusPoint(Image *img, int xwin, int ywin)
{
int dx = xwin - img->_xzoom;
int dy = ywin - img->_yzoom;
img->_xoffset += dx*(1.0/img->_zoom-1);
img->_yoffset += dy*(1.0/img->_zoom-1);
img->_xzoom = xwin;
img->_yzoom = ywin;
}
//------------------------------------------------------------------------
void I_zoomInit(Image *img)
{
img->_xoffset = 0;
img->_yoffset = 0;
img->_zoom = 1.0;
}
//------------------------------------------------------------------------
void I_zoom(Image *img, double zoom_coef)
{
img->_zoom = img->_zoom * zoom_coef;
}
//------------------------------------------------------------------------
void I_move(Image *img, int x, int y)
{
img->_xoffset += x;
img->_yoffset += y;
}
//------------------------------------------------------------------------
void I_mandelbrot(Image *img, Mandelbrot *mb)
{
int xwin, ywin;
for(xwin=0;xwin<img->_width;xwin++)
for(ywin=0;ywin<img->_height;ywin++)
{
int value = MB_compute(mb, xwin, ywin);
Color c;
if(value>=255) c = C_new(0,0,0);
else c = C_new(value,value,value);
double intens = C_intensity(c);
if((intens < img->_min)&&(intens>0))
img->_min = intens;
if(intens > img->_max)
img->_max = intens;
_plot(img,xwin,ywin,c);
}
img->_xoffset = 0;
img->_yoffset = 0;
img->_xzoom = 0;
img->_yzoom = 0;
img->_zoom = 1;
I_check(img,"A la fin de I_mandelbrot");
}
//------------------------------------------------------------------------
void I_colorize(Image *img, Color c_min, Color c_max)
{
int xwin, ywin;
for(xwin=0;xwin<img->_width;xwin++)
for(ywin=0;ywin<img->_height;ywin++)
{
Color c = img->_buffer[xwin][ywin];
double value = C_intensity(c);
if(value!=0)
_plot(img,xwin,ywin,C_blend(c_min,c_max,pow(value/255,0.5)));
}
}
//------------------------------------------------------------------------
void I_draw(Image *img)
{
glBegin(GL_POINTS);
int xwin, ywin, ximg, yimg;
for(xwin=0;xwin<img->_width;xwin++)
for(ywin=0;ywin<img->_height;ywin++)
{
_windowToImage(img, xwin, ywin, &ximg, &yimg);
Color c;
if((ximg>=0)&&(ximg<img->_width)&&
(yimg>=0)&&(yimg<img->_height))
c = img->_buffer[ximg][yimg];
else
c = C_new(0,0,0);
glColor3ub(c._red,c._green,c._blue);
glVertex2i(xwin,ywin);
}
glEnd();
}
//------------------------------------------------------------------------
|
C
|
/*
* Acess2 C Library
* - By John Hodge (thePowersGang)
*
* perror.c
* - perror() and friends
*/
#include <errno.h>
#include <stdio.h>
void perror(const char *s)
{
fprintf(stderr, "%s: Error (%i)\n", s, errno);
}
|
C
|
#include "cachelab.h"
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#define MAXFILELEN 100
#define MAXCMDLEN 20
struct Line{
int valid;
int tag;
int lru; //we use lru algo
};
struct Set{
struct Line *lines;
};
struct Cache{
int setNum;
int lineNum;
struct Set *sets;
};
int misses=0;
int hits=0;
int evictions=0;
int Getopt(int argc,char** argv,int*s,int*E,int*b,char* trace,int*verbose); // read cmdline
void initCache(int s,int E,int b,struct Cache *cache); //malloc and set ptr
void updateCache(struct Cache* cache,int setNum,int tagNum,int verbose);//check miss or hit and set validbit, setbit
void updateLru(struct Cache* cache,int setNum,int index); // index is the index of updated block
int minLru(struct Cache* cache,int setNo); //the minLru block is the least recent used block and we can evict it
int main(int argc,char**argv)
{
int s,E,b,verbose=0;
char trace[MAXFILELEN];
char opt[MAXCMDLEN];
int addr;
int size;
struct Cache cache;
if(Getopt(argc,argv,&s,&E,&b,trace,&verbose)==-1){
printf("can't' get opt.\n");
exit(0);
}
//printf("opt got.\n");
//printf("trace:%s\n",trace);
initCache(s,E,b,&cache);
FILE *file=fopen(trace,"r");
if(file==NULL)
printf("failed to open file.\n");
while((fscanf(file,"%s %x,%d",opt,&addr,&size))!=EOF){
//printf("\nread a line.\n");
if(strcmp(opt,"I")==0) //if 'I' do nothing
continue;
if(verbose)
printf("%s %x,%d ",opt,addr,size);
int setNo=(addr>>b)&((1<<s)-1);
int tagNo=(addr>>(s+b));
if(strcmp(opt,"S")==0){
updateCache(&cache,setNo,tagNo,verbose);
if(verbose==1)
printf("\n");
continue;
}
if(strcmp(opt,"L")==0){ // "L" equals to "S" in this simulator
updateCache(&cache,setNo,tagNo,verbose);
if(verbose==1)
printf("\n");
continue;
}
if(strcmp(opt,"M")==0){ //"M" has the same consequence of two "S" or "L"
updateCache(&cache,setNo,tagNo,verbose);
updateCache(&cache,setNo,tagNo,verbose);
if(verbose==1)
printf("\n");
continue;
}
}
//printf("cache end.\n");
printSummary(hits, misses, evictions);
return 0;
}
int Getopt(int argc,char**argv,int*s,int*E,int*b,char*trace,int*verbose){
int ch;
while((ch=getopt(argc,argv,"hvs:E:b:t:"))!=-1){
switch(ch)
{
case 'h':
exit(0);
case 'v':
*verbose=1;
break;
case 's':
*s=atoi(optarg);
break;
case 'E':
*E=atoi(optarg);
break;
case 'b':
*b=atoi(optarg);
break;
case 't':
strcpy(trace,optarg);
break;
}
}return 1;
}
void initCache(int s,int E,int b,struct Cache* cache){
cache->setNum=1<<s;
cache->lineNum=E;
cache->sets=(struct Set*)malloc((1<<s)*sizeof(struct Set));
int i,j;
for(i=0;i<(1<<s);i++){
cache->sets[i].lines=(struct Line*)malloc(E*sizeof(struct Line));
for(j=0;j<E;j++){
cache->sets[i].lines[j].valid=0;
cache->sets[i].lines[j].lru=0;
}
}
}
void updateLru(struct Cache* cache,int setNo,int index){
int k;
cache->sets[setNo].lines[index].lru=9999; //recent used block's lru number is the biggest
for(k=0;k<cache->lineNum;k++){
if(k!=index)
cache->sets[setNo].lines[k].lru--; //update other line's lru
}
}
int minLru(struct Cache* cache,int setNo){
int i;
int minIdx=0;
int min=9999;
for(i=0;i<cache->lineNum;i++){
if(cache->sets[setNo].lines[i].lru<min){
minIdx=i;
min=cache->sets[setNo].lines[i].lru;
}
}
return minIdx;
}
void updateCache(struct Cache* cache,int setNo,int tagNo, int verbose){
int i;
for(i=0;i<cache->lineNum;i++){
if((cache->sets[setNo].lines[i].valid==1)
&&(cache->sets[setNo].lines[i].tag==tagNo)){ //cache hits
hits++;
updateLru(cache,setNo,i);
if(verbose==1)
printf("hit ");
return;
}
}
misses++; //cache misses
if(verbose==1)
printf("miss ");
for(i=0;i<cache->lineNum;i++){
if(cache->sets[setNo].lines[i].valid==0){ //find an empty block
cache->sets[setNo].lines[i].valid=1;
cache->sets[setNo].lines[i].tag=tagNo;
updateLru(cache,setNo,i);
return;
}
}
evictions++; //cache evictions
int evictionIdx=minLru(cache,setNo);
cache->sets[setNo].lines[evictionIdx].valid=1;
cache->sets[setNo].lines[evictionIdx].tag=tagNo;
updateLru(cache,setNo,evictionIdx);
if(verbose==1)
printf("eviction ");
}
|
C
|
/* $Id: topSchedule.C,v 1.4 2003-01-13 04:34:30 fateneja Exp $ */
/* File sections:
* Service: constructors, destructors
* Solution: functions directly related to the solution of a (sub)problem
* Utility: advanced member access such as searching and counting
* List: maintenance of lists or arrays of objects
*/
#include "topSchedule.h"
#include "topScheduleT.h"
#include "PulseHistory.h"
#include "Input/CoolingTime.h"
#include "Chains/Chain.h"
#include "Output/Result.h"
/****************************
********* Service **********
***************************/
/** This is used to convert a calcSchedule object, pointed to by
the first argument, to a topSchedule object. At the same time,
this function is initializes the number of after-shutdown
cooling times of interest. The second argument is the head of
the list of input coolingTimes which is parsed to set the local
member. After establishing the number of cooling times, space
is allocated and initialized for 'coolD'. */
topSchedule::topSchedule(calcSchedule *sched, CoolingTime *coolList) :
calcSchedule(*sched)
{
coolingTime = NULL;
coolD = NULL;
nCoolingTimes = coolList->makeCoolingTimes(coolingTime);
if (nCoolingTimes > 0)
{
coolD = new Matrix[nCoolingTimes];
memCheck(coolD,"topSchedule::topSchedule(...) constructor: coolD");
}
topScheduleT::setNumCoolingTimes(nCoolingTimes);
Result::setNResults(nCoolingTimes+1);
verbose(3,"Set number of cooling times to %d.",nCoolingTimes);
}
/** This constructor first invokes its base class copy constructor.
It then copies the number of cooling times, copying 'coolD' and
'coolingTime' on an element-by-element basis if it is greater
than 0. */
topSchedule::topSchedule(const topSchedule& t) :
calcSchedule(t)
{
coolingTime = NULL;
coolD = NULL;
nCoolingTimes = t.nCoolingTimes;
if (nCoolingTimes > 0)
{
coolD = new Matrix[nCoolingTimes];
memCheck(coolD,"topSchedule::topSchedule(...) copy constructor: coolD");
coolingTime = new double[nCoolingTimes];
memCheck(coolingTime,
"topSchedule::topSchedule(...) copy constructor: coolingTime");
for (int coolNum=0;coolNum<nCoolingTimes;coolNum++)
{
coolD[coolNum] = t.coolD[coolNum];
coolingTime[coolNum] = t.coolingTime[coolNum];
}
}
}
topSchedule::~topSchedule()
{
delete [] coolD;
delete coolingTime;
}
/** The correct implementation of this operator must ensure that
previously allocated space is returned to the free store before
allocating new space into which to copy the object. */
topSchedule& topSchedule::operator=(const topSchedule& t)
{
if (this == &t)
return *this;
/**** BEGIN copied directly from calcSchedule.C ***/
setCode = t.setCode;
delay = t.delay;
D = t.D;
history = t.history;
opTime = t.opTime;
fluxCode = t.fluxCode;
while (nItems-->0)
delete subSched[nItems];
delete subSched;
subSched=NULL;
nItems = t.nItems;
if (nItems>0)
{
subSched = new calcSchedule*[nItems];
memCheck(subSched,"calcSchedule::operator=(...): subSched");
for (int itemNum=0;itemNum<nItems;itemNum++)
subSched[itemNum] = t.subSched[itemNum];
}
/**** END copied directly from calcSchedule.C ***/
delete coolingTime;
delete [] coolD;
coolingTime = NULL;
coolD = NULL;
nCoolingTimes = t.nCoolingTimes;
if (nCoolingTimes > 0)
{
coolD = new Matrix[nCoolingTimes];
memCheck(coolD,"topSchedule::operator=(...): coolD");
coolingTime = new double[nCoolingTimes];
memCheck(coolingTime,
"topSchedule::operator=(...): coolingTime");
for (int coolNum=0;coolNum<nCoolingTimes;coolNum++)
{
coolD[coolNum] = t.coolD[coolNum];
coolingTime[coolNum] = t.coolingTime[coolNum];
}
}
return *this;
}
/****************************
******** Solution **********
***************************/
/** It does not set a decay matrix for the delay since no delay is
applied to a topSchedule. It checks for the existence of a
history before calling setDecay on it, since a topSchedule may
not have a pulsing history. It calls Chain::setDecay for each of
the 'coolD' matrices. */
void topSchedule::setDecay(Chain* chain)
{
int itemNum, coolNum;
/* NOTE: topSchedule's don't apply any final decay block */
if (nItems>0)
for (itemNum=0;itemNum<nItems;itemNum++)
subSched[itemNum]->setDecay(chain);
if (history != NULL)
history->setDecay(chain);
for (coolNum=0;coolNum<nCoolingTimes;coolNum++)
chain->setDecay(coolD[coolNum],coolingTime[coolNum]);
}
/** It does not apply any final decay operation. It checks for the
existence of the pulsing history before applying it. It applies
decays for each of the after-shutdown cooling times, storing them
in the special matrices of the topScheduleT object passed in the
second argument. */
void topSchedule::setT(Chain* chain, topScheduleT *schedT)
{
int coolNum;
if (nItems>0)
setSubTs(chain, schedT);
else
chain->fillTMat(schedT->opBlock(),opTime,fluxCode);
/* NOTE: Only a topSchedule can be without a pulsing history */
if (history != NULL)
schedT->total() = history->doHistory(schedT->opBlock());
else
schedT->total() = schedT->opBlock();
/* ALSO NOTE: topSchedule's don't apply any final decay block */
for (coolNum=0;coolNum<nCoolingTimes;coolNum++)
chain->mult(schedT->cool(coolNum),coolD[coolNum],schedT->total());
}
|
C
|
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include "inter-code.h"
Operand* newOperand(OperandKind kind) {
Operand *p = (Operand*)malloc(sizeof(Operand));
p->kind = kind;
p->name = p->text = NULL;
return p;
}
Operand* newVarOperand() {
static int cnt = 0;
Operand *p = newOperand(VARIABLE);
p->id = ++cnt;
return p;
}
Operand* newTempOperand() {
static int cnt = 0;
Operand *p = newOperand(TEMP);
p->id = ++cnt;
return p;
}
Operand* newLabelOperand() {
static int cnt = 0;
Operand *p = newOperand(LABEL);
p->id = ++cnt;
return p;
}
Operand* newFunctionOperand(char* s) {
Operand *p = newOperand(FUNCTION);
p->name = s;
return p;
}
Operand* constOperand(int val) {
Operand *p = newOperand(CONSTANT);
p->value = val;
return p;
}
Operand* varOperand(int id) {
Operand *p = newOperand(VARIABLE);
p->id = id;
return p;
}
Operand* addressOperand(int id) {
Operand *p = newOperand(ADDRESS);
p->id = id;
return p;
}
Operand* deRefOperand(int id) {
Operand *p = newOperand(DEREF);
p->id = id;
return p;
}
#define getStr(str, format, ...) do { \
static char buf[30]; \
sprintf(buf, format, __VA_ARGS__); \
str = malloc(strlen(buf)+1); \
strcpy(str, buf); \
return str; \
} while (0)
char* operandToStr(Operand* p) {
if (p == NULL) return NULL;
if (p->text != NULL) return p->text;
switch (p->kind) {
case TEMP: getStr(p->text, "t%d", p->id);
case VARIABLE: getStr(p->text, "v%d", p->id);
case CONSTANT: getStr(p->text, "#%d", p->value);
case ADDRESS: getStr(p->text, "&t%d", p->id);
case DEREF: getStr(p->text, "*t%d", p->id);
case LABEL: getStr(p->text, "label%d", p->id);
case FUNCTION: getStr(p->text, "%s", p->name);
}
return NULL;
}
void operandRelease(Operand* p) {
free(p->text);
free(p);
}
|
C
|
typedef struct string_class string_class_t;
typedef struct string string_t;
extern string_class_t String;
struct string_class {
string_t * (* new) (char *);
void (* init) (string_t * self, char *);
void (* delete) (string_t * self);
string_class_t * (* klass) (string_t * self);
char * (* class_name)(string_t * self);
int (* is_a) (string_t * self, string_class_t * class);
char * (* string)(string_t * self);
size_t (* len) (string_t * self);
size_t (* s2i) (string_t * self);
};
struct string {
union {
string_class_t * class;
string_class_t * _;
};
char * string;
};
void string_class_init(void);
typedef struct array_class array_class_t;
typedef struct array array_t;
extern array_class_t Array;
struct array_class {
array_t * (* new) (void);
void (* init) (array_t * self);
void (* delete) (array_t * self);
array_class_t * (* klass) (array_t * self);
char * (* class_name)(array_t * self);
int (* is_a) (array_t * self, array_class_t * class);
size_t (* len)(array_t * self);
};
struct array {
union {
array_class_t * class;
array_class_t * _;
};
size_t len;
};
void array_class_init(void);
typedef struct object_class object_class_t;
typedef struct object object_t;
extern object_class_t Object;
struct object_class {
object_t * (* new) (void);
void (* init) (object_t * self);
void (* delete) (object_t * self);
object_class_t * (* klass) (object_t * self);
char * (* class_name)(object_t * self);
int (* is_a) (object_t * self, object_class_t * class);
};
struct object {
union {
object_class_t * class;
object_class_t * _;
};
};
void object_class_init(void);
#include <stdio.h>
string_class_t String;
string_t *
string_method_new(char *) {
}
void
string_method_init(string_t * self, char * val) {
super.foo();
self->_.super->init(self, "abc");
self->_.super->init(self);
self->_.super->initialize(self, "abc");
self->_.super->initialize(self);
self->_.super->initialize(self);
self->_->initialize(self, "abc");
self->_->initialize(self);
self->_->initialize(self);
self->string = val;
string_t * str = String.new("abc");
str->_->concat(str, "def");
str->_->concat(str);
str->_->concat(str);
string_t str = String.new("abc");
str._->concat(str, "def");
str._->concat(str);
str._->concat(str);
}
char *
string_method_string(string_t * self) {
return self->string;
}
size_t
string_method_len(string_t * self) {
return strlen(self->string);
}
void
string_class_init(void) {
object_class_init();
o_init_class((Object *) &String, (Object *) &Object, "String",
sizeof(string_class_t), sizeof(string_t));
String.new = string_method_new;
String.init = string_method_init;
String.string = string_method_string;
String.len = string_method_len;
}
array_class_t Array;
size_t
array_method_len(array_t * self) {
return self->len;
}
void
array_class_init(void) {
object_class_init();
o_init_class((Object *) &Array, (Object *) &Object, "Array",
sizeof(array_class_t), sizeof(array_t));
Array.len = array_method_len;
}
|
C
|
/*main.c*/
#include <stdio.h>
#include "add.h"
#include "sub.h"
int main(void)
{
int a = 10, b = 12;
float x= 3.2f,y = 9.8f;
double m=3.2,n=6.4;
printf("x=%f,y=%f\n",x,y);
float sumf=add_float(x,y);
float subf=sub_float(x,y);
printf("float x+y IS:%f\n",sumf);
printf("float x-y IS:%f\n",subf);
return 0;
}
|
C
|
/***************************************************************************//**
*
* @file OLED.h
* @brief Header file for OLED Display (SSD1305)
* @author Embedded Artists AB
* @author Geoffrey Daniels, Dimitris Agrafiotis
* @version 1.0
* @date 14 March. 2012
* @warning Initialize I2C or SPI, and GPIO before calling any functions in
* this file.
*
* @edit Jeremy Dalton 12/2012
*
* Copyright(C) 2009, Embedded Artists AB
* All rights reserved.
*
*******************************************************************************/
#ifndef OLED_H
#define OLED_H
#define OLED_DISPLAY_WIDTH 96
#define OLED_DISPLAY_HEIGHT 64
typedef enum
{
OLED_COLOR_BLACK,
OLED_COLOR_WHITE
} OLED_Colour;
/// @brief Initialize the OLED display driver
/// @warning Initialize I2C or SPI, and GPIO before calling any functions in
/// this file.
void OLED_Init(void);
/// @brief Clear the entire screen
/// @param[in] Colour - Colour to fill the screen with
/// @warning Initialize the OLED driver before running this function
void OLED_ClearScreen(OLED_Colour Colour);
/// @brief Draw one pixel on the display
/// @param[in] X - X position
/// @param[in] Y - Y position
/// @param[in] Colour - Colour of the pixel
/// @warning Initialize the OLED driver before running this function
void OLED_Pixel(uint8_t X, uint8_t Y, OLED_Colour Colour);
/// @brief Draw a line starting at X0,Y0 and ending at X1,Y1
/// @param[in] X0 - Start x position
/// @param[in] Y0 - Start y position
/// @param[in] X1 - End x position
/// @param[in] Y1 - End y position
/// @param[in] Colour - Colour of the line
/// @warning Initialize the OLED driver before running this function
void OLED_Line(uint8_t X0, uint8_t Y0, uint8_t X1, uint8_t Y1, OLED_Colour Colour);
/// @brief Draw a circle centered at X0,Y0 with radius R
/// @param[in] X - Start x position
/// @param[in] Y - Start y position
/// @param[in] R - Radius
/// @param[in] Colour - Colour of the circle
/// @warning Initialize the OLED driver before running this function
void OLED_LineCircle(uint8_t X, uint8_t Y, uint8_t R, OLED_Colour Colour);
/// @brief Draw a filled circle centered at X0,Y0 with radius R
/// @param[in] X - Start x position
/// @param[in] Y - Start y position
/// @param[in] R - Radius
/// @param[in] Colour - Colour of the circle
/// @warning Initialize the OLED driver before running this function
void OLED_FillCircle(uint8_t X, uint8_t Y, uint8_t R, OLED_Colour Colour);
/// @brief Draw a rectangle starting at X0,Y0 and ending at X1,Y1
/// @param[in] X0 - Start x position
/// @param[in] Y0 - Start y position
/// @param[in] X1 - End x position
/// @param[in] Y1 - End y position
/// @param[in] Colour - Colour of the rectangle
/// @warning Initialize the OLED driver before running this function
void OLED_LineRect(uint8_t X0, uint8_t Y0, uint8_t X1, uint8_t Y1, OLED_Colour Colour);
/// @brief Draw a filled rectangle starting at X0,Y0 and ending at X1,Y1
/// @param[in] X0 - Start x position
/// @param[in] Y0 - Start y position
/// @param[in] X1 - End x position
/// @param[in] Y1 - End y position
/// @param[in] Colour - Colour of the rectangle
/// @warning Initialize the OLED driver before running this function
void OLED_FillRect(uint8_t X0, uint8_t Y0, uint8_t X1, uint8_t Y1, OLED_Colour Colour);
/// @brief Draw a character at location X,Y
/// @param[in] X - X location
/// @param[in] Y - Y location
/// @param[in] Character - Character
/// @param[in] Forground - Colour of the letter
/// @param[in] Background - Colour of the background
/// @return 1 on success, 0 if the location is outside of the display
/// @warning Initialize the OLED driver before running this function
uint8_t OLED_Char(uint8_t X, uint8_t Y, uint8_t Character, OLED_Colour Forground, OLED_Colour Background);
/// @brief Draw a string of characters starting at location X,Y
/// @param[in] X - X location
/// @param[in] Y - Y location
/// @param[in] S - String
/// @param[in] Forground - Colour of the letter
/// @param[in] Background - Colour of the background
/// @warning Initialize the OLED driver before running this function
void OLED_String(uint8_t X, uint8_t Y, uint8_t *String, OLED_Colour Forground, OLED_Colour Background);
void WriteOLEDString(uint8_t* String, uint8_t Line, uint8_t Position);
#endif // OLED_H
|
C
|
/* fs.c */
#include <stdio.h>
#include <conio.h>
#define FILE_NUM 10
#define FILE_SIZE (1024*10)
#define PUT_PROMPT printf("FS#")
const char file_system_name[] = "fs.dat";
FILE *fp;
struct inode{
char file_name[512];
int file_length;
};
struct inode *p;
struct inode inode_array[FILE_NUM];
void creat_file_system(){
long len;
int inode_num;
int i;
fp=fopen(file_system_name,"wb");
if(fp==NULL){
printf("Create file error!\n");
exit(1);
}
for(len=0;len< (sizeof(inode_array[0])+FILE_SIZE)*FILE_NUM;len++){
fputc(0,fp);
}
for(i=0;i<FILE_NUM;i++){
strcpy(inode_array[i].file_name,"");
inode_array[i].file_length =0;
p=&inode_array[i];
fwrite(p,sizeof(inode_array[0]),1,fp);
}
fflush(fp);
}
void open_file_system(){
int i;
fp=fopen(file_system_name,"r");
if(fp==NULL){
creat_file_system();
}
fp=fopen(file_system_name,"r+");
if(fp==NULL){
printf("Open file to read/write error!\n");
exit(1);
}
p = &inode_array[0];
fseek(fp,0,SEEK_SET);
fread(p,sizeof(inode_array[0])*FILE_NUM,1,fp);
}
int new_a_file(char *file_name){
int i;
for(i=0;i<FILE_NUM;i++){
if(strcmp(inode_array[i].file_name,"")==0){
strcpy(inode_array[i].file_name,file_name);
p = &inode_array[i];
fseek(fp,sizeof(inode_array[0])*i,SEEK_SET);
if(fwrite(p,sizeof(inode_array[0]),1,fp)!=1){
printf("new a file error!\n");
exit(1);
}
fflush(fp);
return i;
}
};
return -1;
}
int del_a_file(char *file_name){
int i;
for(i=0;i<FILE_NUM;i++){
if(strcmp(inode_array[i].file_name,file_name)==0){
strcpy(inode_array[i].file_name,"");
p = &inode_array[i];
fseek(fp,sizeof(inode_array[0])*i,SEEK_SET);
fwrite(p,sizeof(inode_array[0]),1,fp);
fflush(fp);
return i;
}
};
return -1;
}
void list(){
int i;
int count;
printf("\n");
count=0;
for(i=0;i<FILE_NUM;i++){
if(strcmp(inode_array[i].file_name,"")!=0){
printf("\tFile name: %s \t\t\t [%d]\n",inode_array[i].file_name,
inode_array[i].file_length);
count++;
}
};
printf("\tFiles count = %d\n",count);
}
int open_a_file(char *file_name){
int i;
for(i=0;i<FILE_NUM;i++){
if(strcmp(inode_array[i].file_name,file_name)==0){
return i;
}
};
}
int offset_by_i(int i){
return sizeof(inode_array[0])*FILE_NUM + FILE_SIZE*i;
}
int write(char *file_name,int offset,char *str,int count){
int handle;
handle = open_a_file(file_name);
fseek(fp,offset_by_i(handle)+offset,SEEK_SET);
fwrite(str,count,1,fp);
inode_array[handle].file_length = strlen(str)+offset;
p = &inode_array[handle];
fseek(fp,sizeof(inode_array[0])*handle,SEEK_SET);
fwrite(p,sizeof(inode_array[0]),1,fp);
fflush(fp);
}
int read(char *file_name,int offset,int count,char *str){
int handle;
char buf[FILE_SIZE];
handle = open_a_file(file_name);
fseek(fp,offset_by_i(handle)+offset,SEEK_SET);
fread(buf,count,1,fp);
strncpy(str,buf,count);
}
void print_help()
{
printf("Please select: 1. Creat a new file system\n");
printf(" 2. Make a new file\n");
printf(" 3. Del a file\n");
printf(" 4. List files\n");
printf(" 5. Write a string to a file\n");
printf(" 6. Read a string from a file\n");
printf(" 7. Exit\n");
printf(" \n");
printf(" h for help\n");
}
int main()
{
char buf1[FILE_SIZE];
char key;
char buf2[5120];
clrscr();
print_help();
key = '0';
open_file_system();
while(key!='7')
{
PUT_PROMPT;
key=getch();
putch(key);
strcpy(buf1,"");
strcpy(buf2,"");
switch(key)
{
case '1':
fclose(fp);
creat_file_system();
printf("\nCreate file system succeed!\n");
open_file_system();
break;
case '2':
puts("\nPlease input a file name:");
scanf("%s",buf1);
new_a_file(buf1);
printf("Add a file succeed!\n");
break;
case '3':
puts("\nPlease input a file name:");
scanf("%s",buf1);
del_a_file(buf1);
printf("Del file %s succeed!\n",buf1);
break;
case '4':
list();
break;
case '5':
puts("\nPlease input a file name:");
scanf("%s",buf1);
puts("\nPlease input a string:");
scanf("%s",buf2);
write(buf1,0,buf2,strlen(buf2)+1);
printf("\nWrite a file succeed!\n");
break;
case '6':
puts("\nPlease input a file name:");
scanf("%s",buf2);
read(buf2,0,FILE_SIZE,buf1);
puts(buf1);
break;
case 'h':
printf("\n\n");
print_help();
break;
case '7':
break;
default:
printf("\n");
}
}
return 0;
}
|
C
|
/**
* \file
* A very simple Contiki application showing how Contiki programs look
* \author
* mds
*/
#include "contiki.h"
#include <stdio.h> /* For printf() */
#include "dev/leds.h"
#include "ieee-addr.h"
#include <string.h>
#include "dev/serial-line.h"
#include "dev/cc26xx-uart.h"
#include "buzzer.h"
#include "sys/ctimer.h"
/*---------------------------------------------------------------------------
define the global symbols for easily change
---------------------------------------------------------------------------*/
#define BUTTON_ON 1
#define BUTTON_OFF 0
#define BUZZ_FREQUENCY 1000
#define BUZZ_COUNTER 0
/*---------------------------------------------------------------------------*/
PROCESS(lab1_process, "lab1 process");
AUTOSTART_PROCESSES(&lab1_process);
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
global variables for function access
---------------------------------------------------------------------------*/
char led_red_state = BUTTON_OFF; // init off
char led_green_state = BUTTON_OFF; // init off
char led_all_state = BUTTON_OFF; // init off
char buz_state = BUTTON_OFF; // init off
int buz_freq = BUZZ_FREQUENCY; // init 1000
char buzz_counter = BUZZ_COUNTER; // init 0
static struct ctimer timer_buzz_ctimer; //Callback Timer
static struct ctimer timer_red_ctimer; //Callback Timer
static struct ctimer timer_green_ctimer; //Callback Timer
static struct ctimer timer_all_ctimer; //Callback Timer
/*---------------------------------------------------------------------------
functions to realize the different demand of requirements
use call back to make the program running async without many processes
and multi-thread, the three different functions can run at the same time.
---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
1 functions to realize led red on and off
---------------------------------------------------------------------------*/
void show_toggle_led_red() {
ctimer_reset(&timer_red_ctimer);
leds_toggle(LEDS_RED); //Toggle RED LED
}
/*---------------------------------------------------------------------------
2 functions to realize led green on and off
---------------------------------------------------------------------------*/
void show_toggle_led_green() {
ctimer_reset(&timer_green_ctimer);
leds_toggle(LEDS_GREEN); //Toggle GREEN LED
}
/*---------------------------------------------------------------------------
3 functions to realize led all on and off
---------------------------------------------------------------------------*/
void show_toggle_led_all() {
ctimer_reset(&timer_all_ctimer);
leds_toggle(LEDS_ALL); //Toggle ALL LED
}
/*---------------------------------------------------------------------------
4 functions to realize the buzz on and off
---------------------------------------------------------------------------*/
void show_buzz_on_off() {
if (buz_state == BUTTON_ON) {
buzzer_stop();
buz_state = BUTTON_OFF;
} else {
buzzer_start(buz_freq);
buz_state = BUTTON_ON;
}
}
/*---------------------------------------------------------------------------
5 functions to realize the buzz freq increase 50Hz per second, press 'i': increase
50 Hz per seconds, after 5 seconds keep the beep until press b again
---------------------------------------------------------------------------*/
static void buzz_callback_inc_freq() {
if (buz_state == BUTTON_ON && buzz_counter < 5) {
buz_freq += 50;
buzzer_start(buz_freq);
ctimer_reset(&timer_buzz_ctimer);
buzz_counter++;
}
if (buz_state == BUTTON_ON && buzz_counter == 5) {
buz_freq = BUZZ_FREQUENCY;
}
}
/*---------------------------------------------------------------------------
6 functions to realize the buzz freq increase 50Hz per second, press 'd': decrease
50 Hz per seconds, after 5 seconds keep the beep until press b again
---------------------------------------------------------------------------*/
static void buzz_callback_dec_freq() {
if (buz_state == BUTTON_ON && buzz_counter < 5) {
buz_freq -= 50;
buzzer_start(buz_freq);
ctimer_reset(&timer_buzz_ctimer);
buzz_counter++;
}
if (buz_state == BUTTON_ON && buzz_counter == 5) {
buz_freq = BUZZ_FREQUENCY;
}
}
/*---------------------------------------------------------------------------
7 functions to realize the printing of ieee address
---------------------------------------------------------------------------*/
void print_ieee_address() {
uint8_t address[8]; // 64 bit to hex
ieee_addr_cpy_to(address, 8);
printf("IEEE 64 bit address: ");
for (int i = 0; i < 8; i++) {
if (i < 7) { // noral print for first 7 address
if ((int)(address[i]) >= 16) {
printf("%x:", address[i]);
} else {
printf("0%x:", address[i]);
}
} else { // specail print without : for the 8th address
if ((int)(address[i]) >= 16) {
printf("%x", address[i]);
} else {
printf("0%x", address[i]);
}
}
}
printf("\n\r");
}
//lab1 Thread
PROCESS_THREAD(lab1_process, ev, data) {
PROCESS_BEGIN(); //Start of thread
cc26xx_uart_set_input(serial_line_input_byte); //Initalise UART in serial driver
//Processing loop of thread
while (1) {
PROCESS_YIELD(); // run other threads
if (ev == serial_line_event_message) { // print first line
printf("reveived line: %s\n\r", (char *)data);
}
if (strcmp(data, "a") == 0) { // start conditional input
if (led_all_state == BUTTON_OFF) {
led_all_state = BUTTON_ON;
ctimer_set(&timer_all_ctimer, CLOCK_SECOND, show_toggle_led_all, NULL);
} else {
led_all_state = BUTTON_OFF;
ctimer_stop(&timer_all_ctimer);
}
} else if (strcmp(data, "g") == 0) {
if (led_green_state == BUTTON_OFF) {
led_green_state = BUTTON_ON;
ctimer_set(&timer_green_ctimer, CLOCK_SECOND, show_toggle_led_green, NULL);
} else {
led_green_state = BUTTON_OFF;
ctimer_stop(&timer_green_ctimer);
}
} else if (strcmp(data, "r") == 0) {
if (led_red_state == BUTTON_OFF) {
led_red_state = BUTTON_ON;
ctimer_set(&timer_red_ctimer, CLOCK_SECOND, show_toggle_led_red, NULL);
} else {
led_red_state = BUTTON_OFF;
ctimer_stop(&timer_red_ctimer);
}
} else if (strcmp(data, "b") == 0) {
show_buzz_on_off();
} else if (strcmp(data, "i") == 0) {
buzz_counter = 0;
ctimer_set(&timer_buzz_ctimer, CLOCK_SECOND, buzz_callback_inc_freq, NULL);
} else if (strcmp(data, "d") == 0) {
buzz_counter = 0;
ctimer_set(&timer_buzz_ctimer, CLOCK_SECOND, buzz_callback_dec_freq, NULL);
} else if (strcmp(data, "n") == 0) {
print_ieee_address();
}
}
PROCESS_END(); //End of thread
}
/*---------------------------------------------------------------------------*/
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
// Nom des différentes extensions
char fig[5]=".fig\0",
lfig[11]="_liste.fig\0",
res[5]=".res\0",
hach[13]="_hachage.res\0",
abr[9]="_abr.res\0";
// Change l'extension de chaine par ext
char *changeExtension(char *chaine, char *ext) {
char *string=strdup(chaine);
int i=0, j=0;
while(string[i]!='.' && string[i]!='\0')
i++;
while(ext[j]!='\0') {
string[i]=ext[j];
i++;
j++;
}
string[i]='\0';
return string;
}
// Suprimme le nom de l'instance pour laisser celui du dossier
char *supNom(char *chaine) {
char *string=strdup(chaine);
int i=0, j=0;
while(string[i]!='\0') {
if(string[i]=='/')
j=i;
i++;
}
string[j+1]='\0';
return string;
}
/* Ne pouvant faire d'affectation dans le switch, chaque case renvoie vers une fonction */
void case1(char *nf) {
char *pfig=changeExtension(nf, fig);
execlp("./bin/creerL", "creerL", nf, pfig, NULL);
printf("Fichier rendu : %s\n", pfig);
}
void case2(char *nf) {
char
*pres=changeExtension(nf, res),
*pfig=changeExtension(nf, fig);
execlp("./bin/creerR", "creerR", nf, pres, pfig, NULL);
}
void case3(char *nf) {
char
*pres=changeExtension(nf, hach),
*pfig=changeExtension(pres, fig);
execlp("./bin/creerH", "creerH", nf, pres, pfig, NULL);
}
void case4(char *nf) {
char
*pres=changeExtension(nf, abr),
*pfig=changeExtension(pres, fig);
execlp("./bin/creerA", "creerA", nf, pres, pfig, NULL);
}
void case5(char *nf) {
printf("Fichier rendu : courbes.txt,\t .fig, _liste.fig, .res, _hachage.res, _abr.res\n");
execlp("./bin/creation_courbes.sh", "creation_courbes", nf, "courbes.txt", NULL);
}
void case6(char *nf) {
char *dossier=supNom(nf);
printf("Fichier rendu : courbes.txt,\t .fig, _liste.fig, .res, _hachage.res, _abr.res\n");
execlp("./bin/creation_courbes.sh", "creation_courbes", dossier, "courbes.txt", NULL);
}
// Le menu
int main() {
int choix;
char *nf=(char*)malloc(sizeof(char)*128);
printf("Bienvenu\n");
printf("Veuillez saisir le nom du fichier .cha à lire\n");
scanf("%s",nf);
while(1) {
printf("1 : Pour créer une figure avec une liste\n");
printf("2 : Pour créer un réseau simple\n");
printf("3 : Pour créer un réseau avec table de hachage\n");
printf("4 : Pour créer un réseau avec ABRe\n");
printf("5 : Pour créer un fichier des temps cpu de l'instance\n");
printf("6 : Pour créer le fichier des temps cpu de l'ensemble\n");
printf("7 : Quitter\n");
scanf("%d",&choix);
switch(choix) {
case 1 :
case1(nf);
break;
case 2 :
case2(nf);
break;
case 3 :
case3(nf);
break;
case 4 :
case4(nf);
break;
case 5 :
case5(nf);
break;
case 6 :
case6(nf);
break;
default :
return 0;
}
}
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct page {int dummy; } ;
struct inode {int dummy; } ;
struct exofs_dir_entry {int dummy; } ;
/* Variables and functions */
int /*<<< orphan*/ IS_ERR (struct page*) ;
struct page* exofs_get_page (struct inode*,int /*<<< orphan*/ ) ;
struct exofs_dir_entry* exofs_next_entry (struct exofs_dir_entry*) ;
scalar_t__ page_address (struct page*) ;
struct exofs_dir_entry *exofs_dotdot(struct inode *dir, struct page **p)
{
struct page *page = exofs_get_page(dir, 0);
struct exofs_dir_entry *de = NULL;
if (!IS_ERR(page)) {
de = exofs_next_entry(
(struct exofs_dir_entry *)page_address(page));
*p = page;
}
return de;
}
|
C
|
#include <stdio.h>
int main(void) {
//khai bao bien R
double R;
R = 2.5 ;
//khai bao bien PI
const double PI = 3.14;
double CV, DT;
printf ("R=%1.f", R);
printf ("\n");
printf ("PI=%2.f", PI);
//chu vi
CV = (double) 2*R*PI;
//dien tich
DT = (double) R*R*PI;
printf ("\n\n");
printf("2*R*PI\tR*R*PI\n%.1f\t%.1f",CV,DT);
getchar();
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
void subset(int,int);
void display();
int x[10],count;
char str[10];
int main()
{
int n;
printf("enter string \n");
scanf("%s",str);
n=strlen(str);
subset(0,n-1);
printf("%d",count);
return 0;
}
void subset(int k,int n)
{
if(k==n)
{
x[k]=1;
display(n);
count++; //printf("%c",str[k]);
x[k]=0;
display(n);
count++;
//printf("\n%d\n",count++);
return;
}
// else
// {
x[k]=1;
subset(k+1,n);
x[k]=0;
subset(k+1,n);
// }
return;
}
void display(int n)
{
int i;
//count++;
for(i=0;i<=n;i++)
{
if(x[i]==1)
printf("%c",str[i]);
}
printf("\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct node* create_node(int);
struct node* search_node(struct node *, int);
struct node
{
int info;
struct node *next;
};
int isLoop(struct node *s)
{
struct node *p, *q;
p = q = s;
do
{
p = p->next;
q = q->next;
q = (q->next != NULL) ? q->next : NULL;
}while(p && q);
return (p == q) ? 1 : 0;
}
void reverse_node(struct node **s)
{
struct node *p, *q, *r;
p = *s;
q = r = NULL;
while(p)
{
r = q;
q = p;
p = p->next;
q->next = r;
}
*s = q;
}
void remove_duplicates(struct node *s)
{
struct node *i, *t;
if(!s)
{
printf("List is empty");
return;
}
while(s)
{
t = s;
i = s->next;
while(i)
{
if(s->info == i->info)
t->next = i->next;
else
t = i;
i = i->next;
}
s = s->next;
}
}
int largest_node(struct node *s)
{
return sort_node(s);
}
int smallest_node(struct node *s)
{
sort_node(s);
return s->info;
}
int sort_node(struct node *s)
{
int temp;
struct node *i, *j;
if(!s)
printf("List is empty");
else
{
while(s)
{
i = s->next;
while(i)
{
if(s->info > i->info)
{
temp = s->info;
s->info = i->info;
i->info = temp;
}
i = i->next;
}
j = s; //j will contain last node address
s = s->next;
}
}
return j->info;
}
int sum_node(struct node *s)
{
if(s)
return sum_node(s->next) + s->info;
}
void update_node(struct node *s, int item, int update_item)
{
struct node *r = s;
if(!s)
printf("List is empty");
else if(s->info == item)
s->info = update_item;
else
{
while(r != search_node(s, item))
r = r->next;
if(!search_node(s, item))//if item is not found
return;
r->info = update_item;
}
}
void add_node_after(struct node *s, int item, int insert_item)
{
struct node *t, *r, *n, *m;
n = create_node(insert_item);
r = s;
if(!s)
printf("List is empty");
else if(s->info == item)
{
m = s->next;
s->next = n;
n->next = m;
}
else
{
while(r != search_node(s, item))
{
r = r->next;
t = r;
}
m = t->next;
t->next = n;
n->next = m;
}
}
void add_node_last(struct node *s, int item)
{
struct node *r;
r = create_node(item);
while(s->next)
s = s->next;
s->next = r;
}
void add_node_begining(struct node **s, int item)
{
struct node *r;
r = create_node(item);
r->next = *s;
*s = r;
}
struct node* search_node(struct node *s, int item)
{
while(s)
{
if(s->info == item)
return s;
s = s->next;
}
return NULL;
}
void delete_node(struct node **s, int item)
{
struct node *t, *r;
r = t = *s;
if(!(*s))
printf("List is empty");
else if((*s)->info == item)
*s = r->next;
else
{
while(r != search_node(*s, item))
{
t = r;
r = r->next;
}
t->next = r->next;
}
}
void delete_last_node(struct node **s)
{
struct node *t, *r = NULL;
t = *s;
if(!(*s))
printf("List is empty");
else
{
while(t->next != NULL)
{
r = t;
t = t->next;
}
if(r)
r->next = NULL;
else
*s = NULL;
}
free(t);
}
void delete_first_node(struct node **s)
{
struct node *t;
if(!(*s))
printf("List is empty");
else
{
t = *s;
(*s) = t->next;
free(t);
}
}
void display(struct node *s)
{
while(s)
{
printf("%d ", s->info);
s = s->next;
}
}
int count_node(struct node *s)
{
if(s)
return count_node(s->next) + 1;
}
void insert_node(struct node **s, int item)
{
struct node *t;
if(!(*s))
(*s) = create_node(item);
else
{
t = *s;
while(t->next != NULL)
t = t->next;
t->next = create_node(item);
}
}
struct node* create_node(int item)
{
struct node *n;
n = (struct node*)malloc(sizeof(struct node));
n->info = item;
n->next = NULL;
return n;
}
|
C
|
#include<stdio.h>
void sum(int x,int y);
main()
{
int a,b;
a=10,b=20;
sum(a,b);
}
void sum(int x,int y)
{
int z;
z=x+y;
printf("result=%d",z);
}
|
C
|
/* Filter header
*
* 2017-02-17 Scott Lawrence
*
* Filter console input to provide a backchannel for data transfer
*/
#ifndef __FILTER_H__
#define __FILTER_H__
////////////////////////////////////////
/* pass-through */
#define kPS_IDLE (0)
/* Start command? */
#define kEscKey (0x1b)
#define kPS_ESC (1)
/* for REMOTE -> CONSOLE */
#define kStartMsgRC ('{') /* esc{ to start from the Remote */
#define kStartMsgCR ('}') /* esc} to start from the Remote */
#define kEndMsg (0x07) /* ^g (BELL) to end */
#define kPS_TCCMD (2)
/* for CONSOLE -> REMOTE */
#define kPS_TRCMD (3)
////////////////////////////////////////
// These are the handlers for the captured streams
void Filter_ProcessTC( byte * buf, size_t len ); // process REMOTE->CONSOLE command
void Filter_ProcessTR( byte * buf, size_t len ); // process CONSOLE->REMOTE command
/* Filters should use these to output text */
void Filter_ToConsolePutByte( byte data );
void Filter_ToConsolePutString( char * str );
void Filter_ToRemotePutByte( byte data );
void Filter_ToRemotePutString( char * str );
////////////////////////////////////////
// If this function pointer is set, then bytes
// will be passed through it as well.
// return the byte passed in for it to get further consumed
// or return -1 to not further pass on anything
typedef int (*consumeByteFcn)( byte );
consumeByteFcn consumeFcn;
#endif
|
C
|
#include <stdio.h>
//[]
void SwapValue(int iNum1, int iNum2);
void SwapRef(int * pNum1, int * pNum2);
void main()
{
/*
ϴ ?
1. Լ Լ ܺ
2. Ҵ
Լ Ű
1. Call by Value
- ȣ
-츮 Լ ȣߴ
- '' ´.
2.Call by Reference(address)
- ȣ(ּҿ ȣ)
-ͺ Ű Ͽ 'ּ ' ´.
> Լ ܺ ִ.
*/
int iNum1 = 100;
int iNum2 = 200;
SwapValue(iNum1, iNum2);
// SwapValue ȣ ''(100,200) !
printf("SwapValue ȣ , iNum1(%d), iNum2(%d)\n", iNum1, iNum2); //SwapValue Լ Լκ iNum1 iNum2 ǰ Լ Ҹȴ.
SwapRef(&iNum1, &iNum2);
printf("SwapRef ȣ , iNum1(%d), iNum2(%d)\n", iNum1, iNum2); //SwapRef Լ ܺԼ Լ iNum1 iNum2 Ͽ Ѵ.
}
//[]
void SwapValue(int iNum1, int iNum2)
{
int iTemp = iNum1; //ӽð iNum1
iNum1 = iNum2;
iNum2 = iTemp; //ӽð (iNum1 ) iNum2
printf("SwapValue , iNum1(%d), iNum2(%d)\n", iNum1, iNum2);
}
void SwapRef(int * pNum1, int * pNum2)
{
int iTemp = *pNum1;
*pNum1 = *pNum2;
*pNum2 = iTemp;
}
|
C
|
// main function for program
#include "main.h"
// main function
int main(int argc, char **argv) {
// check arguments
options args = {.valid = 0,.help=0,.promiscuous=0,.toTerminal=0,.toFile=0,.filter=0};
parseArguments(&args, argc, argv);
if (!args.valid) {
// argument parser determined arguments were invalid
fprintf(stderr,"Invalid arguments, run with \"-h\" for help\n");
return -1;
}else if (args.help) {
// display help
printf("basic packet sniffer\nArguments-\n");
printf("\t-h, display help\n");
printf("\t-p, run with promiscuous mode\n");
printf("\t-d, output results to screen\n");
printf("\t-o *, output results to given filename\n");
printf("\t-f *, filter these packets types\n");
printf("\tmultiple can be filtered at once by using seperate '-f *' arguments\n");
printf("\t\tIP, ip packets\n");
printf("\t\tARP, arp packets\n");
printf("\t\tTCP, tcp packets\n");
printf("\t\tUDP, udp packets\n");
printf("\t\tHTTP, http (tcp, port:80) packets\n");
printf("\t\tSMTP, smtp (tcp, port:25) packets\n");
printf("Must run with sudo, and in arguments choose '-d' to display to terminal or '-o *' with appropriate filename to write to, otherwise sniffer will not run.\nTo stop the program, type 'exit' and press enter.");
return 0;
}else if (!args.toTerminal && !args.toFile) {
// missing output option
fprintf(stderr,"Missing output type, run with \"-h\" for help\n");
return -1;
}
if (args.toFile) {
// attempt to open the file
if ((args.f = fopen(args.filename,"a")) == NULL) {
fprintf(stderr, "failed to open file \"%s\": %s", args.filename, strerror(errno));
return -1;
}
}
printf("sniffer starting...\n");
// create raw socket
// ETH_P_ALL
// ETH_P_IP | ETH_P_ARP either by themselves work, but using '|' causes it to not work
int sockfd = -1;
if ((sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0) {
perror("socket() error: ");
return -1;
}
if (args.promiscuous) {
// turn on promiscuous mode
if (!turnOnPromisc(sockfd)) {
// failed exit
fprintf(stderr,"Failed to turn on promiscuous mode\n");
return -1;
}
}
// get size of receive buffer of socket
int bufferPacketSize = -1;
int sockoptlen = sizeof(bufferPacketSize);
if (getsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &bufferPacketSize, &sockoptlen) < 0) {
perror("getsockopt() error: ");
return -1;
}
// for recvfrom
//struct sockaddr saddr;
//int saddr_size;
// for value read
int bufferRead;
// fd_set for select() polling
fd_set fdSet;
// timeout for select()
const struct timespec timeout = {.tv_sec = 0, .tv_nsec = 0};
// buffers
// general buffer
char buffer[SIZE_BUFFER];
// packet buffer
unsigned char *bufferPacket = (unsigned char *)calloc(bufferPacketSize,sizeof(unsigned char));
// summary statistics for session
// init all vals to zero
snifstats stats = {.packets_received=0,.bytes_received=0,.count_unknown_ethernet=0,.count_unknown_ip=0,.count_ip=0,.count_unknown_app=0,.count_tcp=0,.count_udp=0,.count_arp=0,.count_http=0,.count_smtp=0};
// list of packets
packetList *list = createPacketList();
// main loop
while(1) {
// set fds to stdin and sockfd
setFD(&fdSet,sockfd);
// select() polling
if (pselect(sockfd+1, &fdSet, NULL, NULL, &timeout, NULL) < 0) {
// error occured, break from loop
perror("select() error: ");
break;
}
// check if stdin set
if FD_ISSET(0,&fdSet) {
// process input
int inputResult = processInput(buffer,SIZE_BUFFER);
// check result
if (inputResult == INPUT_ERROR) {
// error processing the input
perror("processInput() error: ");
break;
}else if (inputResult == INPUT_EXIT) {
// if exit, exit loop
break;
}else{
// invalid command
printf("Invalid input, type 'EXIT' in order to exit the sniffer\n");
}
}
// check if socket set
if FD_ISSET(sockfd,&fdSet) {
// zero out buffer
clearStr(bufferPacket,bufferPacketSize);
// reset saddr size
//saddr_size = sizeof(saddr);
// read from socket
// recvfrom(sockfd, bufferPacket, bufferPacketSize, 0, &saddr, (socklen_t *) &saddr_size)
// recvfrom(sockfd, bufferPacket, bufferPacketSize, 0, NULL, NULL)
if ((bufferRead = recvfrom(sockfd, bufferPacket, bufferPacketSize, 0, NULL, NULL)) < 0) {
perror("recvfrom() error: ");
break;
}
// process the buffer
// recvfrom() appears to only popoff 1 datagram/packet
// so don't need to worry about seperating out packets
packetInfo *pi = processPacket(&args, &stats, bufferPacket, bufferRead);
if (pi != NULL) {
// output accordingly
displayInfo(&args, pi, buffer, SIZE_BUFFER);
// for this application, don't need to save to list, so just clean
cleanPacketInfo(&pi);
// add onto list
//addPacket(list,pi);
if (args.toFile) {
// flush the file
fflush(args.f);
}
}
}
} // while loop
// exit loop
// report statistics
reportStats(&args,&stats,buffer,SIZE_BUFFER);
// cleanup
// packet list
cleanPacketList(&list);
// packet buffer
free(bufferPacket);
// close socket
close(sockfd);
// close file if being used
if (args.toFile) {
fclose(args.f);
}
printf("sniffer ended\n");
return 0;
}
|
C
|
/*
* File: main.c
* Author: apurv
*
* Created on 6 August, 2010, 8:45 PM
*/
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
int main2(int argc, char** argv) {
//forkDemo1();
//forkDemo2();
//forkDemo3();
//waitDemo1();
//execDemo();
//sharedMemoryDemo();
//system("clear");
//howManyProcesses(); //didn't give thought to it yet.
int n=5;
int *p1=&n;
void **p21=&p1;
//int **p21=p1;
int i=*(int*)(*p21);
printf("%d",i);
return (EXIT_SUCCESS);
}
|
C
|
#include "stm32f4xx_i2c.h"
#include "adpd.h"
#include "i2c.h"
#define ADPD_SLAVE_ADDR 0x64
/******************************************************************************
* FIFO data ready interrupt
*/
void
EXTI0_IRQHandler( void )
{
}
/******************************************************************************
*/
int
adpd_init( void )
{
return 0;
}
/******************************************************************************
*/
int
adpd_start( void )
{
uint16_t status = adpd_read_1word( 0x4b );
adpd_write_reg( 0x4b, status | (1 << 7) ); // Enable 32kHz clock for FSM transitions
adpd_write_reg( 0x10, 0x1 ); // change device to program mode
// XXX Program configuration registers here
adpd_write_reg( 0x10, 0x2 ); // start in sampling mode
return 0;
}
/******************************************************************************
*/
int
adpd_write_reg( uint8_t reg_addr,
uint16_t data )
{
i2c_start( I2C1, ADPD_SLAVE_ADDR, I2C_Direction_Transmitter );
i2c_send( I2C1, reg_addr );
i2c_send( I2C1, (uint8_t) (data >> 8) );
i2c_send( I2C1, (uint8_t) (data & 0xff) );
i2c_stop( I2C1 );
return 0;
}
/******************************************************************************
*/
uint16_t
adpd_read_1word( uint8_t reg_addr )
{
uint16_t word;
i2c_start( I2C1, ADPD_SLAVE_ADDR, I2C_Direction_Transmitter );
i2c_send( I2C1, reg_addr );
i2c_start( I2C1, ADPD_SLAVE_ADDR, I2C_Direction_Receiver );
word = i2c_receive_ack( I2C1 ) << 8;
word |= i2c_receive_nack( I2C1 );
i2c_stop( I2C1 );
return word;
}
/******************************************************************************
* Length is number of 16-bit words being read
*/
int
adpd_read_words( uint8_t reg_addr,
uint16_t *buf,
int length )
{
int i = 0;
uint8_t temp;
i2c_start( I2C1, ADPD_SLAVE_ADDR, I2C_Direction_Transmitter );
i2c_send( I2C1, reg_addr );
i2c_start( I2C1, ADPD_SLAVE_ADDR, I2C_Direction_Receiver );
while ( i < length )
{
// XXX Do shit here
buf[i] = i2c_receive_ack( I2C1 ) << 8;
// if last half-word return nack otherwise return ack
if ( i == length - 1 )
buf[i] |= i2c_receive_nack( I2C1 );
else
buf[i] |= i2c_receive_ack( I2C1 );
i++;
}
return 0;
}
/******************************************************************************
*/
int
adpd_read_all_regs( uint16_t *buf )
{
adpd_read_words( 0x0, buf, 0x60 );
return 0;
}
|
C
|
#include"myheader18.h"
int main()
{
FILE *fptr1, *fptr2;
char filename[30], str[100];
int len, i, j=0, flag =0, len1, in; //in--to read the words of file
snode *top = NULL;
printf("Enter file name : ");
memset(filename,0,30*sizeof(char));
fgets(filename,29,stdin);
len = strlen(filename);
if('\n' == filename[len-1])
{
filename[len-1] = '\0';
}
if(NULL == (fptr1 = fopen(filename,"r")))
{
printf("Error in opening file\n");
exit(1);
}
if(NULL == (fptr2 = fopen("palindrome","w")))
{
printf("Error in opening file\n");
exit(1);
}
printf("Content of file : %s\n",filename);
while(EOF != (in = fgetc(fptr1)))
{
printf("%c",in);
}
fseek(fptr1,01,0);
while(fscanf(fptr1,"%s",str) > 0)
{
flag = 0;
len1 = strlen(str);
for(i=0; i<len1; i++)
{
push(&top, str[i]);
}
for(i=0; i<len1; i++)
{
if(str[i] != pop(&top))
{
flag = 1;
break;
}
}
if(0 == flag)
{
fprintf(fptr2,"%s\n",str);
j++;
}
free_stack(&top);
}
fclose(fptr1);
fclose(fptr2);
if(NULL == (fptr2 = fopen("palindrome","r")))
{
printf("Error in opening file\n");
exit(1);
}
if(0 == j)
{
printf("There are no palindrome words in the file \n");
exit(1);
}
printf("There are %d palindrome words in the file\n",j);
fseek(fptr2,00,0);
printf("Content of file(%s) which stores the palindrome words is: \n","palindrome");
while(EOF != (in = fgetc(fptr2)))
{
printf("%c",in);
}
fclose(fptr2);
return 0;
}
|
C
|
#pragma strict_types
#include "../def.h"
inherit MASTER_ROOM;
void create_object(void);
void reset(int arg);
void create_object(void)
{
set_short("A well on the farm (n)");
set_long("A small flat lawn in a corner of the farm, where a well " +
"has been built. The well is built of stone and stands in the " +
"centre of the lawn. The wooden crank mechanism rises above " +
"the well and there's a rope with a hook hanging down from it. " +
"East and south of here is the wooden fence that encircles the " +
"farm and to the west is a large hill. A huge oak tree grows " +
"on top of the hill, casting a shadow over the lawn. Thick " +
"bushes grow on the south side of the lawn.\n");
set_new_light(5);
add_item("lawn|flat lawn|small lawn|small flat lawn","A small lawn on " +
"the farm that seems to be off limits to animals since the " +
"grass here is not trampled at all");
add_item("ground","The ground looks a bit different here, it is not " +
"trampled at all");
add_item("grass|short grass","The grass here is trimmed short and " +
"not trampled at all. It seems like this lawn is being taken " +
"care of for some purpose other than having animals on");
add_item("corner|secluded corner","This is a secluded corner of the " +
"farm. Animals don't seem to come here");
add_item("farm","Most of it is north and west from here");
add_item("well|stone well|stone","A stone well with a wooden crank. " +
"It looks a bit small to you, but it would be of normal size " +
"if you were the size of a hobbit");
add_item("crank|mechanism|crank mechanism|wooden mechanism|" +
"wooden crank mechanism","It seems as if it is broken! The " +
"farmers probably have to go to the river to the east to get " +
"their water now");
add_item("rope","A rope that is supposed to be used to sink a bucket " +
"down into the water. It's not very useful now due to the " +
"condition of the crank");
add_item("hook","The bucket is supposed to hang there but it's not " +
"very useful now due to the condition of the crank");
add_item("fence","The fence is delicately carved and seems to go round " +
"the whole farm");
add_item("hill|large hill|grassy hill","There are windows in the " +
"side of the hill. It looks like a hobbit house");
add_item("house|hobbit house","It looks like one. There's no entrance " +
"to it from this direction");
add_item("top|top of the hill","A huge oak tree grows there");
add_item("tree|oak|oak tree|huge tree|huge oak|huge oak tree","It " +
"towers above you and looks huge even to someone who is not " +
"the size of a hobbit");
add_item("shadow","A shadow cast by the huge oak");
add_item("bush|bushes","Thick bushes with small flowers growing on " +
"them");
add_item("flower|flowers|small flower|small flowers","The flowers " +
"smell nice");
add_item("%flower|%flowers|%","The smell from the flowers fills your " +
"nostrils and you feel like all is right with the world");
add_exit(ROOM + "farm_gate","north");
reset(0);
}
void reset(int arg)
{
add_monster(MONSTER + "butterfly",5);
}
|
C
|
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 155
void eliminateZeros(char number[]);
int result(char numOne[] , char numTwo[]);
void eliminateZeros(char number[])
{
int pos = 0;
int zeroCount = 0;
for(int i=0; number[i] != '\0'; i++) // Get the Zero Count
{
if(number[i] != '0') {
break;
} else {
++zeroCount;
}
}
for(int i=0; i<zeroCount; i++) // Eliminate Zeros
{
for(int j=0; number[j] != '\0'; j++)
{
number[j] = number[j+1];
pos++;
} number[pos] = '\0';
pos = 0;
}
}
int result(char numOne[] , char numTwo[])
{
if(strlen(numOne) == strlen(numTwo)) {
int three = 1;
for(int i=0; numOne[i] != '\0'; i++)
{
if((numOne[i] != numTwo[i])) {
three = 0;
if(numOne[i] < numTwo[i]) {
return 1;
break;
} else {
return 2;
break;
}
} else {
three = 1;
}
}
if(three) {return 3;};
} else if(strlen(numOne) < strlen(numTwo)) {
return 1;
} else {
return 2;
}
}
int main()
{
int testCaseCount;
scanf("%d",&testCaseCount);
for(int count=0; count<testCaseCount; count++)
{
// Step 1 -> Get the Input
char numA[MAX_LENGTH];
scanf("%s",numA);
char numB[MAX_LENGTH];
scanf("%s",numB);
int resultFinal;
// Step 2 --> Get the results
if(numA[0] == '0' && numB[0] == '0') {
eliminateZeros(numA);
eliminateZeros(numB);
printf("%s\n",numA);
printf("%s\n",numB);
resultFinal = result(numA,numB);
} else if(numA[0] == '0') {
eliminateZeros(numA);
printf("%s\n",numA);
resultFinal = result(numA,numB);
} else if(numB[0] == '0') {
eliminateZeros(numB);
printf("%s\n",numB);
resultFinal = result(numA,numB);
} else {
resultFinal = result(numA,numB);
}
// Step 3 ---> Print the Result
printf("%d\n",resultFinal);
}
return 0;
}
/*
int main()
{
// Step 1 -> Get the Input
char numA[] = "1231";
char numB[] = "1230";
int resultFinal;
// Step 2 --> Get the results
if(numA[0] == '0' && numB[0] == '0') {
eliminateZeros(numA);
eliminateZeros(numB);
printf("%s\n",numA);
printf("%s\n",numB);
resultFinal = result(numA,numB);
} else if(numA[0] == '0') {
eliminateZeros(numA);
printf("%s\n",numA);
resultFinal = result(numA,numB);
} else if(numB[0] == '0') {
eliminateZeros(numB);
printf("%s\n",numB);
resultFinal = result(numA,numB);
} else {
resultFinal = result(numA,numB);
}
// Step 3 ---> Print the Result
printf("%d\n",resultFinal);
return 0 ;
}
*/
|
C
|
// Eric Johnson
// Lab1a - 2
// #8 from textbook. Write program to print a conversion table from feet to meters using
// the temperature conversion program as starting point.
// Header File
// REFERENCE: http://www.cs.colorado.edu/~main/chapter1/temperature.cxx
// File: temperature.cxx <== Old file heading
// This program prints a table to convert numbers from one unit to another.
// The program illustrates some implementation techniques.
#ifndef LAB1A_2_MAIN_H
#define LAB1A_2_MAIN_H
void setup_cout_fractions(int fraction_digits);
double feet_to_meters(double f);
#endif //LAB1A_2_MAIN_H
|
C
|
/*
Main source file for ezOS initializations
Author: Boris Kim
*/
#include "ezOS.h"
/**********************************************GLOBAL VARIABLES********************************************/
// scheduler
extern scheduler_t scheduler;
// TCB's
extern tcb_t tcb[NUM_TCB];
extern tcb_t main_tcb;
/**********************************************GLOBAL VARIABLES********************************************/
osError_t osInitialize(void) {
__disable_irq();
// Configure SysTick interrupt
SysTick_Config(SystemCoreClock/1000);
#ifdef __DEBUG
printf("\nosInitialize: Enter\n");
printGlobalLocations();
#endif
uint32_t *VECTOR_ZERO;
VECTOR_ZERO = 0x0;
const uint32_t KIBI = 0x100;
const uint32_t PSP_ENABLE = 1<<1;
main_tcb.stackPointer = (uint32_t*)*VECTOR_ZERO;
main_tcb.stackBaseAddress = main_tcb.stackPointer;
main_tcb.stackOverflowAddress = main_tcb.stackPointer - (2*KIBI);
main_tcb.priority = osPriorityNone;
main_tcb.state = T_INACTIVE;
main_tcb.tid = 99;
uint32_t* stackLocater = main_tcb.stackPointer - 2*KIBI;
#ifdef __DEBUG
printf("Main Stack is at %p and overflow at %p\n", main_tcb.stackBaseAddress, main_tcb.stackOverflowAddress);
#endif
for(int32_t stackCount = 0; stackCount < NUM_TCB; stackCount++) {
tcb[stackCount].stackPointer = (stackLocater - stackCount*KIBI);
tcb[stackCount].stackBaseAddress = (stackLocater - stackCount*KIBI);
tcb[stackCount].stackOverflowAddress = (stackLocater - (KIBI*(stackCount + 1)));
tcb[stackCount].priority = osPriorityNone;
tcb[stackCount].state = T_INACTIVE;
tcb[stackCount].nextTcb = NULL;
tcb[stackCount].tid = 0;
#ifdef __DEBUG
printf("Stack %d is at %p and overflow at %p, TCB location: %p\n", stackCount, tcb[stackCount].stackBaseAddress, tcb[stackCount].stackOverflowAddress, &tcb[stackCount]);
#endif
}
// Copy the Main Stack contents to the process stack of the new main() task, at tcb[0]
uint32_t topMainStack = __get_MSP();
uint32_t topNewMainStack = topMainStack - 2*4*KIBI;
#ifdef __DEBUG
printf("\nMSP was at: %p\n", (uint32_t*)__get_MSP());;
#endif
for(uint32_t *mainStackLoc = main_tcb.stackBaseAddress; (uint32_t)mainStackLoc >= topMainStack; mainStackLoc--) {
uint32_t *copyPointer = mainStackLoc - (2*KIBI);
*copyPointer = *mainStackLoc;
#ifdef __DEBUG
if(mainStackLoc == (uint32_t*)topMainStack) {
printf("\ncopyPointer is at: %p\n", copyPointer);
}
#endif
}
// Set MSP to base address of main stack
__set_MSP((uint32_t)main_tcb.stackBaseAddress);
#ifdef __DEBUG
printf("\nMSP is now at: %p\n", (uint32_t*)__get_MSP());;
#endif
// Set PSP to the top of main() task
__set_PSP(topNewMainStack);
#ifdef __DEBUG
printf("PSP is now at: %p\n", (uint32_t*)__get_PSP());
#endif
// Switch from using the MSP to the PSP
__set_CONTROL((uint32_t)__get_CONTROL() | PSP_ENABLE);
// Initialize the scheduler with Idle Task
initScheduler();
#ifdef __DEBUG
printf("\nosInitialize: Exit\n");
#endif
__enable_irq();
return osNoError;
}
osError_t osCreateTask(osThreadFunc_t functionPointer, void* functionArgument, priority_t priority) {
#ifdef __DEBUG
//printf("\nosCreateTask: Enter\n");
#endif
static uint32_t taskNumber = 1;
const uint32_t PSR_VAL = 0x01000000;
tcb[taskNumber].tid = taskNumber;
tcb[taskNumber].priority = priority;
changeState(&tcb[taskNumber], T_READY);
#ifdef __DEBUG
printTcbContents(&tcb[taskNumber]);
#endif
// Add register values to stack starting from PSR
tcb_push(&tcb[taskNumber], PSR_VAL);
// Set PC -> Function Pointer
tcb_push(&tcb[taskNumber], (uint32_t)functionPointer);
// Fill LR - R4 with placeholder bit
for(uint32_t count = 0; count < 14; count++) {
if(count == 5) {
// Set R0 -> Function Argument
tcb_push(&tcb[taskNumber], (uint32_t)(functionArgument));
}
else {
tcb_push(&tcb[taskNumber], 0x01);
}
}
#ifdef __DEBUG
printf("osCreateTask: Right before schedule task:\n");
printTcbContents(&tcb[taskNumber]);
#endif
tcb_t *newTask = &tcb[taskNumber];
tcbList_t *taskQueue = &scheduler.readyQueueList[priority];
tcbList_enqueue(taskQueue, newTask);
#ifdef __DEBUG
printSchedulerStatus();
printf("\nosCreateTask: Exit, created Tid: %d\n", tcb[taskNumber].tid);
#endif
// Increment Task Number
taskNumber++;
return osNoError;
}
void osPrintError(osError_t error) {
printf("Error Code: ");
switch(error) {
case osNoError :
printf("No Error\n");
break;
case osErrorOverflow :
printf("Stack Overflow\n");
break;
case osErrorInv :
printf("Invalid Call\n");
break;
case osErrorPerm :
printf("Permission Error\n");
break;
case osErrorEmp :
printf("Element Empty\n");
break;
default :
printf("Invalid Error Code\n");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.