language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include "inssort.h"
void inssort( void *base, size_t nelem, size_t size,
int (*compar) (const void *, const void *)){
for(size_t i = 1; i < nelem; ++i){
int slot = i;
void* element = malloc(size);
memcpy(element, (char*)(base + slot * size), size);
for(; slot > 0; --slot){
int compare = 0;
compare = (*compar) (element, base + ((slot-1) *size));
if(compare > 0) break;
else{
void *tmp = (char*) base + size * slot;
memcpy(tmp,(char*) base + (slot -1) * size, size);
}
}
memcpy((char*)(base + slot * size), element, size);
free(element);
}
}
|
C
|
/* Maciej Michalec */
#include <stdio.h>
#include <string.h>
#define MAX_TEXT 31
struct student {
char imie[MAX_TEXT];
char nazwisko[MAX_TEXT];
float oceny[30];
int liczba_ocen; /* trzeba jeszcze wyzerowac!!*/
};
typedef struct student student;
int porownywacz(const void* jeden, const void* drugi) /* porownywanie nazwisk i imion */
{
int tmp=strcmp((*(student*)jeden).nazwisko,(*(student*)drugi).nazwisko);
if (tmp) return tmp;
return strcmp((*(student*)jeden).imie,(*(student*)drugi).imie);
}
int normalize_name(char* tekst)
{
int i;
if(tekst[0]>='a'&&tekst[0]<='z')
{
tekst[0]=tekst[0]-32;
}
for(i=1;i<=MAX_TEXT;i++)
{
if(tekst[i]>=65&&tekst[i]<=90)
{
tekst[i]=tekst[i]+'a'-'A';
}
}
}
int main(int argc, char *argv[])
{
char tab[2000];
char test[MAX_TEXT];
FILE* plik;
student studenci[30], s;
int i, liczba_studentow=0, flaga=0; /* wyrzucic poza main?*/
float suma=0;
if(argc>1)
{
plik=fopen(argv[1], "r");
}
else
{
printf("Blad!\n");
return 1;
}
liczba_studentow=0;
while(!feof(plik)) /* dopoki nie napotkam EOF */
{
fscanf(plik,"%s %s %f",s.imie, s.nazwisko, &s.oceny[0]); /* wczytuje z pliku dane o studentach*/
normalize_name(s.imie);
normalize_name(s.nazwisko);
printf("otrzymalem imie %s, nazwisko %s i ocene %f\n",s.imie,s.nazwisko,s.oceny[0]);
for(i=0;i<liczba_studentow;i++); /* sprawdzam czy student juz istnieje */
{
printf("%d student ma imie %s i nazwisko %s\n",i,studenci[i].imie,studenci[i].nazwisko);
if((strcmp(s.imie, studenci[i].imie)==0 && strcmp(s.nazwisko,studenci[i].nazwisko)==0)) /*porownuje stringi*/
{
/* jezeli student o takim imieniu i nazwisku juz istnieje, dodaje tylko ocene */
studenci[i].oceny[studenci[i].liczba_ocen]=s.oceny[0];
studenci[i].liczba_ocen++;
flaga=0; /* ustawiam na zero by nie dopisywac studenta jako nowego */
break;
}
else
{
flaga=1;
}
} /* end of for */
if(flaga) /* jezeli takiego studenta jeszcze nie ma, kopiuje jego dane do tablicy studenci */
{
printf("\n\nKopiuje...\n\n");
strcpy(studenci[liczba_studentow].imie, s.imie);
strcpy(studenci[liczba_studentow].nazwisko, s.nazwisko);
studenci[liczba_studentow].oceny[0]=s.oceny[0];
studenci[liczba_studentow].liczba_ocen++;
liczba_studentow++; /* trzeba go jeszcze wczesniej wyzerowac! */
flaga=0;
}
printf("Skopiowalem %s do %s\n",s.imie,studenci[liczba_studentow-1].imie);
printf("\nliczba studentow to %d \n",liczba_studentow);
} /* end of while */
fclose(plik);
qsort(studenci, liczba_studentow, sizeof(s),porownywacz); /* sortowanie listy studentow */
/*program musi przyjmowac imie i nazwisko pisane zarowno malymi jak i duzymi literami,
w pliku ma byc zachowana forma poprawna (pierwsza lit. wielka) - postac kanoniczna*/
return 0;
}
|
C
|
#include "double_list.h"
int borrow_list(int op1, int op2, int borrow_in, Dlist *next, Dlist **result_head, Dlist **result_tail)
{
int borrow_out = 0, diff , temp = 100000000;
// printf("diff %d op1 %d op2 %d borrow_out %d borrow_in %d\n", diff, op1, op2, borrow_out, borrow_in);
if (next)
{
if (op1 < op2)
{
borrow_out = 1;
op1 = op1 + (borrow_out * 10 * temp);
}
}
diff = op1 - op2 - borrow_in;
insert_first(result_head, diff, result_tail);
return borrow_out;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ROW, COLUMN;
printf("Enter Row: ");
scanf("%d", &ROW);
printf("Enter Column: ");
scanf("%d", &COLUMN);
printf("Enter the elements of Matrix:\n");
int arr[ROW][COLUMN], minimum, i, j, temp, k, w, z = 0, q = 0 ;
/*
i = row iterator
j= column iterator
temp = temporary Variable to swap the values
k = iteration for row iterator i
w = for storing the previous value of column iterator j;
z = used as a temporary variable for storing k
q = used as temporary variable for storing column iterator j
*/
for(i = 0;i < ROW;i++)
for(j = 0;j < COLUMN;j++)
{
scanf("%d",&arr[i][j]);
}
for(i = 0;i < ROW;i++)
for(j = 0;j < COLUMN;j++)
{
temp = i;
q = j;
minimum = arr[i][j];
w = j;
for(k = i;k < ROW;k++)
{
for(;w < COLUMN;w++)
if(arr[k][w] < minimum)
{
minimum = arr[k][w];
z = k;
q = w;
}
w = 0;
}
if(arr[z][q] < arr[i][j])
{
temp = arr[i][j];
arr[i][j] = minimum;
arr[z][q] = temp;
}
}
printf("\nSorted Matrix: \n");
for(i = 0; i < ROW; i++)
{
for(j = 0;j < COLUMN;j++)
printf("%d ",arr[i][j]);
printf("\n");
}
return 0;
}
/*C implementation to sort the given matrix
Input :
Enter Row: 3
Enter Column: 3
Enter the elements of matrix :
7 8 9
5 6 4
3 1 2
Output :
Sorted Matrix :
1 2 3
4 5 6
7 8 9
Time Complexity: O(n2log2n)
Space Complexity : Auxiliary Space: O(n2)
*/
|
C
|
#include <config.h>
#include <cglib/cglib.h>
#include <stdarg.h>
#include "test-cg-fixtures.h"
/*
* This tests reading back an RGBA texture in all of the available
* pixel formats
*/
static const uint8_t tex_data[4] = { 0x12, 0x34, 0x56, 0x78 };
static void
test_read_byte (cg_texture_2d_t *tex_2d,
cg_pixel_format_t format,
uint8_t expected_byte)
{
uint8_t received_byte;
cg_texture_get_data (tex_2d,
format,
1, /* rowstride */
&received_byte);
c_assert_cmpint (expected_byte, ==, received_byte);
}
static void
test_read_short (cg_texture_2d_t *tex_2d,
cg_pixel_format_t format,
...)
{
va_list ap;
int bits;
uint16_t received_value;
uint16_t expected_value = 0;
char *received_value_str;
char *expected_value_str;
int bits_sum = 0;
cg_texture_get_data (tex_2d,
format,
2, /* rowstride */
(uint8_t *) &received_value);
va_start (ap, format);
/* Convert the va args into a single 16-bit expected value */
while ((bits = va_arg (ap, int)) != -1)
{
int value = (va_arg (ap, int) * ((1 << bits) - 1) + 128) / 255;
bits_sum += bits;
expected_value |= value << (16 - bits_sum);
}
va_end (ap);
received_value_str = c_strdup_printf ("0x%04x", received_value);
expected_value_str = c_strdup_printf ("0x%04x", expected_value);
c_assert_cmpstr (received_value_str, ==, expected_value_str);
c_free (received_value_str);
c_free (expected_value_str);
}
static void
test_read_888 (cg_texture_2d_t *tex_2d,
cg_pixel_format_t format,
uint32_t expected_pixel)
{
uint8_t pixel[4];
cg_texture_get_data (tex_2d,
format,
4, /* rowstride */
pixel);
test_cg_compare_pixel (pixel, expected_pixel);
}
static void
test_read_88 (cg_texture_2d_t *tex_2d,
cg_pixel_format_t format,
uint32_t expected_pixel)
{
uint8_t pixel[4];
pixel[2] = 0x00;
cg_texture_get_data (tex_2d,
format,
2, /* rowstride */
pixel);
test_cg_compare_pixel (pixel, expected_pixel);
}
static void
test_read_8888 (cg_texture_2d_t *tex_2d,
cg_pixel_format_t format,
uint32_t expected_pixel)
{
uint32_t received_pixel;
char *received_value_str;
char *expected_value_str;
cg_texture_get_data (tex_2d,
format,
4, /* rowstride */
(uint8_t *) &received_pixel);
received_pixel = C_UINT32_FROM_BE (received_pixel);
received_value_str = c_strdup_printf ("0x%08x", received_pixel);
expected_value_str = c_strdup_printf ("0x%08x", expected_pixel);
c_assert_cmpstr (received_value_str, ==, expected_value_str);
c_free (received_value_str);
c_free (expected_value_str);
}
static void
test_read_int (cg_texture_2d_t *tex_2d,
cg_pixel_format_t format,
...)
{
va_list ap;
int bits;
uint32_t received_value;
uint32_t expected_value = 0;
char *received_value_str;
char *expected_value_str;
int bits_sum = 0;
cg_texture_get_data (tex_2d,
format,
4, /* rowstride */
(uint8_t *) &received_value);
va_start (ap, format);
/* Convert the va args into a single 32-bit expected value */
while ((bits = va_arg (ap, int)) != -1)
{
uint32_t value = (va_arg (ap, int) * ((1 << bits) - 1) + 128) / 255;
bits_sum += bits;
expected_value |= value << (32 - bits_sum);
}
va_end (ap);
received_value_str = c_strdup_printf ("0x%08x", received_value);
expected_value_str = c_strdup_printf ("0x%08x", expected_value);
c_assert_cmpstr (received_value_str, ==, expected_value_str);
c_free (received_value_str);
c_free (expected_value_str);
}
void
test_read_texture_formats (void)
{
cg_texture_2d_t *tex_2d;
tex_2d = cg_texture_2d_new_from_data (test_dev,
1, 1, /* width / height */
CG_PIXEL_FORMAT_RGBA_8888_PRE,
4, /* rowstride */
tex_data,
NULL);
test_read_byte (tex_2d, CG_PIXEL_FORMAT_A_8, 0x78);
/* We should always be able to read into an RG buffer regardless of
* whether RG textures are supported because Cogl will do the
* conversion for us */
test_read_88 (tex_2d, CG_PIXEL_FORMAT_RG_88, 0x123400ff);
test_read_short (tex_2d, CG_PIXEL_FORMAT_RGB_565,
5, 0x12, 6, 0x34, 5, 0x56,
-1);
test_read_short (tex_2d, CG_PIXEL_FORMAT_RGBA_4444_PRE,
4, 0x12, 4, 0x34, 4, 0x56, 4, 0x78,
-1);
test_read_short (tex_2d, CG_PIXEL_FORMAT_RGBA_5551_PRE,
5, 0x12, 5, 0x34, 5, 0x56, 1, 0x78,
-1);
test_read_888 (tex_2d, CG_PIXEL_FORMAT_RGB_888, 0x123456ff);
test_read_888 (tex_2d, CG_PIXEL_FORMAT_BGR_888, 0x563412ff);
test_read_8888 (tex_2d, CG_PIXEL_FORMAT_RGBA_8888_PRE, 0x12345678);
test_read_8888 (tex_2d, CG_PIXEL_FORMAT_BGRA_8888_PRE, 0x56341278);
test_read_8888 (tex_2d, CG_PIXEL_FORMAT_ARGB_8888_PRE, 0x78123456);
test_read_8888 (tex_2d, CG_PIXEL_FORMAT_ABGR_8888_PRE, 0x78563412);
test_read_int (tex_2d, CG_PIXEL_FORMAT_RGBA_1010102_PRE,
10, 0x12, 10, 0x34, 10, 0x56, 2, 0x78,
-1);
test_read_int (tex_2d, CG_PIXEL_FORMAT_BGRA_1010102_PRE,
10, 0x56, 10, 0x34, 10, 0x12, 2, 0x78,
-1);
test_read_int (tex_2d, CG_PIXEL_FORMAT_ARGB_2101010_PRE,
2, 0x78, 10, 0x12, 10, 0x34, 10, 0x56,
-1);
test_read_int (tex_2d, CG_PIXEL_FORMAT_ABGR_2101010_PRE,
2, 0x78, 10, 0x56, 10, 0x34, 10, 0x12,
-1);
cg_object_unref (tex_2d);
if (test_verbose ())
c_print ("OK\n");
}
|
C
|
#include <pthread.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void* counter(void* x);
pthread_mutex_t mut;
typedef struct tParams{
int start;
int end;
pthread_t handle;
}tParams;
int main(int c, char *args[]){
long N = 100000000;
globalSum = 0;
int numThreads = 8;
pthread_t handle[numThreads];
tParams params[numThreads];
pthread_mutex_init(&mut, NULL);
for(int i = 0; i < numThreads; i++){
params[i].start = (N/numThreads)*i;
params[i].end = (N/numThreads) * (i+1)-1;
pthread_create(&(params[i].handle), NULL, &counter, (void*)(¶ms[i]));
}
double totalSum = 0;
for(int i = 0; i < numThreads; i++){
double *rv = 0;
pthread_join(params[i].handle, &rv);
}
printf("The global sum is %d\n", totalSum);
}
void* counter(void* x){
tParams* tp = (tParams*)x;
double sum = 0;
for(int i = tp->start; i <= tp->end; i++){
double s = sqrt(2+sin(cos(sin(i))));
sum += s;
}
void *pdouble = malloc(sizeof(double));
*((double*)pdouble) = sum;
return pdouble;
}
|
C
|
/*
Copyright (c) 2019 Olivier Meloche
L'autorisation est accordée, gracieusement, à toute personne acquérant une
copie de cette bibliothèque et des fichiers de documentation associés
(la "Bibliothèque"), de commercialiser la Bibliothèque sans restriction,
notamment les droits d'utiliser, de copier, de modifier, de fusionner, de
publier, de distribuer, de sous-licencier et / ou de vendre des copies de
la Bibliothèque, ainsi que d'autoriser les personnes auxquelles la
Bibliothèque est fournie à le faire, sous réserve des conditions suivantes:
La déclaration de copyright ci-dessus et la présente autorisation doivent
être incluses dans toutes copies ou parties substantielles de la
Bibliothèque.
LA BIBLIOTHÈQUE EST FOURNIE "TELLE QUELLE", SANS GARANTIE D'AUCUNE SORTE,
EXPLICITE OU IMPLICITE, NOTAMMENT SANS GARANTIE DE QUALITÉ MARCHANDE,
D’ADÉQUATION À UN USAGE PARTICULIER ET D'ABSENCE DE CONTREFAÇON. EN AUCUN
CAS, LES AUTEURS OU TITULAIRES DU DROIT D'AUTEUR NE SERONT RESPONSABLES DE
TOUT DOMMAGE, RÉCLAMATION OU AUTRE RESPONSABILITÉ, QUE CE SOIT DANS LE
CADRE D'UN CONTRAT, D'UN DÉLIT OU AUTRE, EN PROVENANCE DE, CONSÉCUTIF À OU
EN RELATION AVEC LA BIBLIOTHÈQUE OU SON UTILISATION, OU AVEC D'AUTRES
ÉLÉMENTS DE LA BIBLIOTHÈQUE.
*/
/**
* \file main.c
*
* Effectue les testes de l'arbre binaire.
*
*/
#include "arbre_binaire.h"
/**
* \brief Affiche tous les noeuds
*
* \param arbre L'arbre désiré
*/
void afficher_arbre_binaire(arbre_binaire* arbre) {
if (arbre != NULL){
printf("%d\n", element_arbre_binaire(arbre));
if (enfant_gauche_arbre_binaire(arbre) != NULL) {
afficher_arbre_binaire(enfant_gauche_arbre_binaire(arbre));
}
if (enfant_droit_arbre_binaire(arbre) != NULL){
afficher_arbre_binaire(enfant_droit_arbre_binaire(arbre));
}
}
}
/**
* \brief Teste de l'arbre binaire
*/
int main(void) {
int i = 0, j = 0, k = 0, l = 0, m = 0, nombre = 0;
bool n;
arbre_binaire* test1;
arbre_binaire* test2;
arbre_binaire* gauche;
arbre_binaire* droit;
printf("[DEBUT DU TEST]\n");
test1 = creer_arbre_binaire(69);
if (test1) {
printf("Arbre Binaire 'test1' cree.\n\n");
i = element_arbre_binaire(test1);
printf("ELEMENT: %d\n", i); /// <69
creer_enfant_gauche_arbre_binaire(test1, 70);
creer_enfant_droit_arbre_binaire(test1, 170);
creer_enfant_droit_arbre_binaire(test1, 170); /// <Erreur
if (a_erreur_arbre_binaire(test1)) {
printf("Erreur: %s\n", erreur_arbre_binaire(test1));
}
gauche = enfant_gauche_arbre_binaire(test1);
creer_enfant_gauche_arbre_binaire(gauche, 71);
gauche = enfant_gauche_arbre_binaire(gauche);
creer_enfant_gauche_arbre_binaire(gauche, 72);
creer_enfant_droit_arbre_binaire(gauche, 73);
droit = enfant_droit_arbre_binaire(test1);
creer_enfant_gauche_arbre_binaire(droit, 171);
creer_enfant_droit_arbre_binaire(droit, 172);
k = nombre_feuilles_arbre_binaire(test1);
printf("FEUILLE: %d\n", k);
l = nombre_elements_arbre_binaire(test1);
printf("NOEUD: %d\n", l);
m = hauteur_arbre_binaire(test1);
printf("HAUTEUR: %d\n", m);
nombre = 73;
n = contient_element_arbre_binaire(test1, nombre);
if (n) {
printf("L'element %d existe.\n", nombre);
} else {
printf("L'element %d n'existe pas.\n", nombre);
}
if (a_erreur_arbre_binaire(test1)) {
printf("Erreur: %s\n", erreur_arbre_binaire(test1));
}
retirer_enfant_gauche_arbre_binaire(test1);
retirer_enfant_gauche_arbre_binaire(droit);
retirer_enfant_droit_arbre_binaire(droit); /// <Reste seulement 69, 170
nombre = 171;
n = contient_element_arbre_binaire(test1, nombre);
if (n) {
printf("L'element %d existe.\n", nombre);
} else {
printf("L'element %d n'existe pas.\n", nombre);
}
if (a_erreur_arbre_binaire(test1)) {
printf("Erreur: %s\n", erreur_arbre_binaire(test1));
}
modifier_element_arbre_binaire(test1, 690);
j = element_arbre_binaire(test1);
printf("ELEMENT: %d\n", j); /// <69 devient 690
sauvegarder_arbre_binaire(test1, "test1.bin");
printf("Arbre Binaire 'test1' enregistre.\n");
detruire_arbre_binaire(test1);
printf("Arbre Binaire 'test1' detruit.\n\n");
test2 = charger_arbre_binaire("test1.bin");
if (test2) {
printf("Arbre Binaire 'test2' cree.\n\n");
afficher_arbre_binaire(test2); /// <690, 170
} else {
printf("'test2' Impossible de charger le fichier.\n");
}
} else {
printf("'test1' Une erreur est survenue.\n");
}
return 0;
}
|
C
|
#ifndef INIT_STRUCT
#define INIT_STRUCT(Struct_t, structure) Struct_t structure = {#structure}
#endif
#ifndef INIT_STRUCT
#define INIT_STRUCT(Struct_t, structure) Struct_t structure = {};
#endif
#ifndef NAME_OF_ARG_DEF
#define NAME_OF_ARG_DEF(ARG) #ARG
#endif
#include <assert.h>
const unsigned long CANARY_VAL = 0xfff'acf'afc'daf'fcf;
enum Values: unsigned long
{
POISON_VAL = 0xfcd'acf'fac'fff
};
typedef double Elem_t;
typedef unsigned long canary_t;
const int StartLenData = 255;
const int Up = 1,
Down = 0;
enum Stack_errors
{
STACK_UNDERFLOW,
STACK_OVERFLOW,
INVALID_DATA
};
struct Stack_t
{
const char* stack_name;
#ifdef STACK_ANALYSIS
canary_t canary1_struct = CANARY_VAL;
#endif
unsigned int size;
#ifdef STACK_ANALYSIS
canary_t* canary1_buf;
char* buf;
canary_t* canary2_buf;
#endif
Elem_t* data;
size_t max_size;
int err;
int Ok();
int Create(size_t max_size);
int Resize(); // (int updown)
int Push(Elem_t val);
Elem_t Top();
int Pop(Elem_t* val);
int Destruct();
#ifdef STACK_ANALYSIS
canary_t canary2_struct = CANARY_VAL;
#endif
};
int setPoisons(Elem_t* data, size_t num_elem);
const char* strErr(int err);
int setPoisons(Elem_t* data, size_t num_elem)
{
for (size_t el = 0; el < num_elem; el ++)
{
data[el] = POISON_VAL;
}
return 1;
}
// -- Stack ----------------------------------------------------------
int Stack_t::Ok()
{
if (!data)
return 0;
if (max_size < size)
return 0;
#ifdef STACK_ANALYSIS
assert(canary1_buf);
assert(canary2_buf);
assert(*(canary1_buf) == CANARY_VAL);
assert(*(canary2_buf) == CANARY_VAL);
#endif
return 1;
}
int Stack_t::Create(size_t max_size)
{
if (data)
{
free(data);
}
printf("%i:: Max_size = %ld" "\n", __LINE__, max_size);
if (!max_size)
max_size += !max_size * StartLenData;
this->max_size = max_size;
#ifdef STACK_ANALYSIS
if ( !(buf = (char*)(calloc(max_size * sizeof(*data) + sizeof(canary_t) * 2, sizeof(*buf)))) )
{
return -1;
}
canary1_buf = (canary_t*) buf;
*canary1_buf = CANARY_VAL;
canary2_buf = (canary_t*)(buf + sizeof(canary_t) + max_size * sizeof(*data));
*canary2_buf = CANARY_VAL;
data = (Elem_t*)(buf + sizeof(canary_t));
#else
if ( !(data = (Elem_t*)(calloc(max_size, sizeof(*data)))))
{
return -1;
}
#endif
setPoisons(data, max_size);
printf("%i:: Created stack[%u//%lu.<->.%zu]" "\n", __LINE__, size, max_size, (size_t)data);
return 1;
}
int Stack_t::Resize() // (int updown)
{
assert(Ok());
return 1;
/* if ( !(data = (Elem_t*)realloc(data, (updown ? (max_size *= 2) : (max_size /= 2)) * sizeof(*data)) ) )
{
return ERRCALLOC;
} */
assert(Ok());
}
int Stack_t::Push(Elem_t val)
{
assert(Ok());
if (size + 1 > max_size)
{
err = STACK_OVERFLOW;
return STACK_OVERFLOW;
// Resize(Up);
}
data[size++] = val;
return -1;
assert(Ok());
}
Elem_t Stack_t::Top()
{
assert(Ok());
return data[size - 1];
}
int Stack_t::Pop(Elem_t* val)
{
assert(Ok());
if (size < 1)
{
err = STACK_UNDERFLOW;
return 0;
}
if (size - 1 < max_size / 2)
{
// Resize(Down);
}
*val = data[--size];
assert(Ok());
return 1;
}
int Stack_t::Destruct()
{
#ifdef STACK_ANALYSIS
free(buf);
#else
free(data);
#endif
return 1;
}
const char* strErr(int err)
{
switch(err)
{
case STACK_UNDERFLOW:
return "STACK UNDERFLOW";
break;
case STACK_OVERFLOW:
return "STACK OVERFLOW";
break;
case INVALID_DATA:
return "INVALID DATA";
break;
default:
return "UNKNOWN ERROR";
break;
}
}
|
C
|
//
// main.c
// Lab2 Problem 1C
//
// Aiden Barrett
// Student ID; B00075033
#include <stdio.h>
#include <stdlib.h>
int main()
{
float base , height , area;
printf("Enter base , height: ");
scanf("%f %f", &base , &height );
area = (base * height) /2.0;
printf("Area = %.2f\n", area);
return 0;
}
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <errno.h>
#include "message_queue.h"
#include "mem.h"
#include "up_config.h"
#ifdef MB_TRACE
#define MB_MEM_STATIC_POOL_SIZE 100
struct mb_mem_static {
MessageBlock *mb;
int used;
};
static struct mb_mem_static mbms[MB_MEM_STATIC_POOL_SIZE];
static int mbcnt;
static void mbms_dump ()
{
int i;
printf("mb pool info, there %d mbs:\n", mbcnt);
for (i = 0; i < MB_MEM_STATIC_POOL_SIZE; i++) {
if (mbms[i].used) {
printf("#%d: mb %p\n", i, mbms[i].mb);
}
}
}
static void mbms_add (MessageBlock *mb)
{
int i;
printf("add mb %p, mbcnt %d\n", mb, mbcnt);
for (i = 0; i < MB_MEM_STATIC_POOL_SIZE; i++) {
if (!mbms[i].used) {
mbms[i].mb = mb;
mbms[i].used = 1;
mbcnt++;
break;
}
}
if (i == MB_MEM_STATIC_POOL_SIZE) {
printf("add mb %p, mbms fulllllllll\n", mb);
}
}
static void mbms_remove (MessageBlock *mb)
{
int i;
printf("remove mb %p, mbcnt %d\n", mb, mbcnt);
for (i = 0; i < MB_MEM_STATIC_POOL_SIZE; i++) {
if (mbms[i].used && mbms[i].mb == mb) {
mbms[i].used = 0;
mbcnt--;
break;
}
}
if (i == MB_MEM_STATIC_POOL_SIZE) {
printf("mb %p not found\n", mb);
}
}
#else
static void mbms_dump ()
{
}
static void mbms_add (MessageBlock *mb)
{
}
static void mbms_remove (MessageBlock *mb)
{
}
#endif
int up_usleep (int us)
{
struct timeval tv;
int rc;
tv.tv_sec = 0;
tv.tv_usec = us;
rc = select(1, NULL, NULL, NULL, &tv);
if (rc == 0) {
return 0;
}
return -1;
}
MessageBlock * message_block_new (void *data)
{
MessageBlock *mb = (MessageBlock *)mem_malloc(sizeof(MessageBlock));
if (!mb)
return NULL;
mb->data = data;
mbms_add(mb);
return mb;
}
void message_block_release (MessageBlock *mb)
{
mbms_remove(mb);
mem_free(mb);
}
void message_block_set_data (MessageBlock *mb, void *data)
{
mb->data = data;
}
void * message_block_get_data (MessageBlock *mb)
{
return mb->data;
}
MessageQueue * message_queue_create ()
{
MessageQueue *mq;
mq = (MessageQueue *)mem_malloc(sizeof(MessageQueue));
if (!mq) {
return NULL;
}
pthread_cond_init(&mq->cond, NULL);
pthread_mutex_init(&mq->mutex, NULL);
INIT_LIST_HEAD(&mq->mblist);
return mq;
}
void message_queue_destroy (MessageQueue *mq)
{
pthread_cond_destroy(&mq->cond);
pthread_mutex_destroy(&mq->mutex);
mem_free(mq);
}
/*
* dump the message queue's mbs
*/
static void message_queue_dump_mb (MessageQueue *mq)
{
struct list_head *l;
MessageBlock *mb;
printf("message queue %p had mbs:\n", mq);
list_for_each (l, &mq->mblist) {
mb = list_entry(l, MessageBlock, list);
printf("mb: %p\n", mb);
}
}
MessageBlock * message_queue_get_message_block (MessageQueue *mq, int timeout)
{
struct timeval now;
struct timespec to;
MessageBlock *mb = NULL;
int rc = 0;
unsigned long long nsec;
if (timeout == 0) {
pthread_mutex_lock(&mq->mutex);
if (!list_empty(&mq->mblist)) {
mb = list_entry(mq->mblist.next, MessageBlock, list);
list_del(mq->mblist.next);
}
pthread_mutex_unlock(&mq->mutex);
return mb;
} else if (timeout < 0) {
again:
pthread_mutex_lock(&mq->mutex);
if (!list_empty(&mq->mblist)) {
mb = list_entry(mq->mblist.next, MessageBlock, list);
list_del(mq->mblist.next);
pthread_mutex_unlock(&mq->mutex);
return mb;
} else {
rc = pthread_cond_wait(&mq->cond, &mq->mutex);
pthread_mutex_unlock(&mq->mutex);
goto again;
}
}
#if PTHREAD_COND_TIMEDWAIT_OK
gettimeofday(&now, NULL);
nsec = (now.tv_usec + (timeout % 1000) * 1000) * 1000;
to.tv_sec = now.tv_sec + (timeout / 1000) + nsec / 1000000000;
to.tv_nsec = nsec % 1000000000;
pthread_mutex_lock(&mq->mutex);
while (list_empty(&mq->mblist) && rc != ETIMEDOUT) {
rc = pthread_cond_timedwait(&mq->cond, &mq->mutex, &to);
}
if (!list_empty(&mq->mblist)) {
mb = list_entry(mq->mblist.next, MessageBlock, list);
list_del(mq->mblist.next);
}
pthread_mutex_unlock(&mq->mutex);
#else
/* sleep every 100 ms, then check the list, so emulate
the cond_timedwait function */
{
int cnt, i;
cnt = timeout / 100;
for (i = 0; i < cnt; i++) {
pthread_mutex_lock(&mq->mutex);
if (!list_empty(&mq->mblist)) {
mb = list_entry(mq->mblist.next, MessageBlock, list);
list_del(mq->mblist.next);
pthread_mutex_unlock(&mq->mutex);
return mb;
}
pthread_mutex_unlock(&mq->mutex);
usleep(100000);
}
}
#endif
return mb;
}
int message_queue_put_message_block (MessageQueue *mq, MessageBlock *mb)
{
pthread_mutex_lock(&mq->mutex);
list_add(&mb->list, &mq->mblist);
pthread_mutex_unlock(&mq->mutex);
pthread_cond_signal(&mq->cond);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct DOB /*structure for storing the date of birth in dd mm yyyy format*/
{
int dd;
int mm;
int yyyy;
};
struct student /*structure for storing the student data*/
{
char name[64];
struct DOB dob;
int height;
double weight;
} ;
struct node
{
struct student std;
struct node *next;
struct node *previous;
};
typedef struct node NODE;/*Define NODE as data type struct node*/
void print(NODE *temp)
{
if(temp==NULL)
return;
else
{
print(temp->next);
printf("%s %02d/%02d/%04d %d %lf\n",temp->std.name,temp->std.dob.dd,temp->std.dob.mm,temp->std.dob.yyyy,temp->std.height,temp->std.weight); /*printing data recursively in reverse */
}
}
int main()
{
int n;
scanf("%d",&n); /*no. of inputs to be taken*/
NODE *head, *first,*last, *temp = 0;/*declare pointers to NODE*/
first=0; /*the first node*/
for(n;n>0;n--)
{
head = (NODE *)malloc(sizeof(NODE)); /*leading head of our linkedlist*/
scanf("%s %2d %2d %4d %d %lf",head->std.name,&head->std.dob.dd,&head->std.dob.mm,&head->std.dob.yyyy,&head->std.height,&head->std.weight); /*scanning data*/
if (first != 0)
{
temp->next = head; /*elements of likedlist*/
head->previous=temp;
temp = head;
}
else
{
first = temp = head; /*taking the first element*/
}
}
print(first);
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
int main()
{
int i,num;
printf("Enter the number of elements:\n");
scanf("%d",&num);
int a[num];
printf("Enter %d elements in Array:\n",num);
for(i=0;i<num;i++)
{
scanf("%d",&a[i]);
}
printf("Eelments of array are:\n");
for(i=0;i<num;i++)
{
printf("a[%d] = %d\n",i,a[i]);
}
int smallest1,smallest2;
smallest1=smallest2=a[0];
for(i=0;i<num;i++)
{
if(a[i]<smallest1)
{
smallest2=smallest1;
smallest1=a[i];
}
else if( a[i] != smallest1 && a[i]<smallest2)
{
smallest2=a[i];
}
}
printf("The 1th smallest number %d and 2ad smallest is %d\n",smallest1,smallest2);
}
|
C
|
#include <stdio.h>
#include <wchar.h>
#include <assert.h>
int main()
{
printf("1..1 - wcslen_c\n");
wchar_t *s;
size_t len;
s = L"abcdefghijkl";
len = wcslen(s);
printf("len: %lu\n", (unsigned long)len);
assert(len == 12);
printf("ok 1 - wcslen_c\n");
return (0);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "config.h"
JVSConfig config;
void trimToken(char *str, int maxlen)
{
int length = strnlen(str, maxlen);
/* Look for unwated paterrns and terminate the token*/
for (int i = 0; i < length; i++)
{
char val = *(str + i);
if (('\n' == val) || ('\r' == val))
{
*(str + i) = '\0';
}
}
}
JVSConfig *getConfig()
{
return &config;
}
JVSStatus processConfig(char *filePath, char *custom_mapping)
{
// Setup default values
strcpy(config.devicePath, "/dev/ttyUSB0");
strcpy(config.defaultMapping, "driving-generic");
config.atomiswaveFix = 0;
config.debugMode = 0;
config.defaultIO = 1;
config.senseType = 1;
FILE *fp;
char buffer[1024];
if ((fp = fopen(filePath, "r")) != NULL)
{
fgets(buffer, 1024, fp);
while (!feof(fp))
{
if (buffer[0] != '#' && buffer[0] != 0 && strcmp(buffer, "") != 0)
{
char *saveptr;
char *token = strtok_r(buffer, " ", &saveptr);
trimToken(token, sizeof(buffer) - ((unsigned int)((token - buffer))));
/* Grab the Device Path */
if (strcmp(token, "DEVICE_PATH") == 0)
{
token = strtok_r(NULL, " ", &saveptr);
trimToken(token, sizeof(buffer) - ((unsigned int)((token - buffer))));
strcpy(config.devicePath, token);
}
/* Grab sense type */
if (strcmp(token, "SENSE_TYPE") == 0)
{
token = strtok_r(NULL, " ", &saveptr);
trimToken(token, sizeof(buffer) - ((unsigned int)((token - buffer))));
config.senseType = atoi(token);
}
/* Grab debug type */
if (strcmp(token, "DEBUG_MODE") == 0)
{
token = strtok_r(NULL, " ", &saveptr);
trimToken(token, sizeof(buffer) - ((unsigned int)((token - buffer))));
config.debugMode = atoi(token);
}
/* Grab default mapping */
if (strcmp(token, "DEFAULT_MAPPING") == 0)
{
token = strtok_r(NULL, " ", &saveptr);
trimToken(token, sizeof(buffer) - ((unsigned int)((token - buffer))));
strcpy(config.defaultMapping, token);
}
/* Get IO Choice */
if (strcmp(token, "DEFAULT_IO") == 0)
{
token = strtok_r(NULL, " ", &saveptr);
trimToken(token, sizeof(buffer) - ((unsigned int)((token - buffer))));
config.defaultIO = atoi(token);
}
/* Get IO Choice */
if (strcmp(token, "ATOMISWAVE_FIX") == 0)
{
token = strtok_r(NULL, " ", &saveptr);
trimToken(token, sizeof(buffer) - ((unsigned int)((token - buffer))));
config.atomiswaveFix = atoi(token);
if (config.atomiswaveFix)
{
printf("Warning: Running ATOMISWAVE analogue fix, make sure the IO is 8-bit.\n");
}
}
}
fgets(buffer, 1024, fp);
}
}
else
{
return OPEN_JVS_ERR_NULL;
}
fclose(fp);
/* Use custom OutMapping if provided */
if (custom_mapping != NULL)
{
strcpy(config.defaultMapping, custom_mapping);
}
return OPEN_JVS_ERR_OK;
}
void print_mapping_in(MappingIn *mappingIn)
{
if (NULL != mappingIn)
{
printf("Type:%u Mode:%u Key/Channel:%u Min:%d Max:%d \n",
mappingIn->type,
mappingIn->mode,
mappingIn->channel,
mappingIn->min,
mappingIn->max);
}
}
int processInMapFile(char *filePath, MappingIn *mappingIn)
{
int count = 0;
FILE *fp;
char buffer[1024];
char *str_ptr = NULL;
if ((fp = fopen(filePath, "r")) != NULL)
{
do
{
str_ptr = fgets(buffer, 1024, fp);
if ((str_ptr != NULL) && (buffer[0] != '#') && (buffer[0] != 0) && (buffer[0] != '\r') && (buffer[0] != '\n') && (strcmp(buffer, "") != 0))
{
char *saveptr;
char *token = strtok_r(buffer, " ", &saveptr);
trimToken(token, sizeof(buffer) - ((unsigned int)((token - buffer))));
InType type = KEY;
/* KEY <CHANNEL> <MODE> */
if (strcmp(token, "KEY") == 0 || strcmp(token, "ABS") == 0 || strcmp(token, "REV_ABS") == 0)
{
int reverse = 0;
if (strcmp(token, "KEY") == 0)
type = KEY;
if (strcmp(token, "ABS") == 0)
type = ABS;
if (strcmp(token, "REV_ABS") == 0)
{
type = ABS;
reverse = 1;
}
if (strcmp(token, "REV_ABS") == 0)
{
type = ABS;
reverse = 1;
}
token = strtok_r(NULL, " ", &saveptr);
trimToken(token, sizeof(buffer) - ((unsigned int)((token - buffer))));
int channel = atoi(token);
token = strtok_r(NULL, " ", &saveptr);
trimToken(token, sizeof(buffer) - ((unsigned int)((token - buffer))));
Mode mode = modeStringToEnum(token);
// Bobby: is setting min/max here still necessary? These values are set later in deviceThread() according to the InputDevice?
int min = 0;
int max = 0;
if (type == ABS)
{
min = 0;
max = 255;
}
MappingIn tempMapping = {
.channel = channel,
.type = type,
.mode = mode,
.min = min,
.max = max,
.reverse = reverse};
mappingIn[count] = tempMapping;
count++;
}
else
{
printf("config.c: processInMapFile: incorrect settings keyword (%s).\n", token);
}
}
} while (!feof(fp));
}
return count;
}
int processOutMapFile(char *filePath, MappingOut *mappingIn)
{
int count = 0;
FILE *fp;
char buffer[1024];
char *str_ptr = NULL;
if ((fp = fopen(filePath, "r")) != NULL)
{
do
{
str_ptr = fgets(buffer, 1024, fp);
if ((str_ptr != NULL) && (buffer[0] != '#') && (buffer[0] != 0) && (buffer[0] != '\r') && (buffer[0] != '\n') && (strcmp(buffer, "") != 0))
{
char *saveptr;
char *token = strtok_r(buffer, " ", &saveptr);
InType type = KEY;
/* KEY <CHANNEL> <MODE> */
if (strcmp(token, "ROTARY") == 0 || strcmp(token, "ANALOGUE") == 0 || strcmp(token, "BUTTON") == 0 || strcmp(token, "SYSTEM") == 0 || strcmp(token, "COIN") == 0)
{
if (strcmp(token, "ANALOGUE") == 0)
type = ANALOGUE;
if (strcmp(token, "BUTTON") == 0)
type = BUTTON;
if (strcmp(token, "SYSTEM") == 0)
type = SYSTEM;
if (strcmp(token, "ROTARY") == 0)
type = SYSTEM;
if (strcmp(token, "COIN") == 0)
type = COIN;
token = strtok_r(NULL, " ", &saveptr);
trimToken(token, sizeof(buffer) - ((unsigned int)((token - buffer))));
int channel = atoi(token);
token = strtok_r(NULL, " ", &saveptr);
trimToken(token, sizeof(buffer) - ((unsigned int)((token - buffer))));
Mode mode = modeStringToEnum(token);
/* Optional: Player Number*/
int player_number = 1;
token = strtok_r(NULL, " ", &saveptr);
if (token != NULL)
{
player_number = atoi(token);
}
MappingOut tempMapping = {
.channel = channel,
.type = type,
.mode = mode,
.player = player_number};
mappingIn[count] = tempMapping;
count++;
}
else
{
printf("config.c: processOutMapFile: incorrect settings keyword:%x \n", buffer[0]);
}
}
} while (!feof(fp));
}
return count;
}
|
C
|
# include <stdio.h>
# include <math.h>
# include <time.h>
# define LOWERLIMIT 2
# define UPPERLIMIT 1000
int is_prime(int i);
int main(void)
{
//测量时间
clock_t start, finish;
double duration;
start = clock();
//打印素数
printf("2-1000内所有的素数为:\n");
for(int i = LOWERLIMIT; i <= UPPERLIMIT; i++)
{
if(is_prime(i))
{
printf("%d\t", i);
}
}
//测量时间
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("\n该程序运行总时间为: %f seconds\n", duration);
return 0;
}
int is_prime(int i)
{
int sqrt_of_i = (int)sqrt(i);
int j, if_is_prime;
for(j = 2; j <= sqrt_of_i; j++)
{
if(i % j == 0) break;
}
if(j > sqrt_of_i)
{
if_is_prime = 1;
}
else
{
if_is_prime = 0;
}
return if_is_prime;
}
|
C
|
#include "bufio.h"
#include "helpers.h"
#include <stdlib.h>
struct buf_t *buf_new(size_t capacity) {
struct buf_t *res = (struct buf_t *)malloc(sizeof(struct buf_t));
if (res != NULL) {
res->data = (char*)malloc(capacity);
res->capacity = capacity;
res->size = 0;
}
return res;
}
void buf_free(struct buf_t *buf) {
#ifdef DEBUG
if (buf == NULL) {
abort();
}
#endif // DEBUG
if (buf->size != 0) {
free(buf->data);
}
free(buf);
}
size_t buf_capacity(struct buf_t *buf) {
#ifdef DEBUG
if (buf == NULL) {
abort();
}
#endif // DEBUG
return buf->capacity;
}
size_t buf_size(struct buf_t *buf) {
#ifdef DEBUG
if (buf == NULL) {
abort();
}
#endif // DEBUG
return buf->size;
}
ssize_t buf_fill(int fd, struct buf_t *buf, size_t required) {
#ifdef DEBUG
if (!buf || required > buf->capacity)
abort();
#endif
int now_read = 0;
while (1) {
if (buf->size < required) {
now_read = read(fd, buf->data + buf->size, buf->capacity - buf->size);
if (now_read <= 0) break;
else buf->size += now_read;
} else {
break;
}
}
return (now_read < 0 ? -1 : buf->size);
}
ssize_t buf_flush(int fd, struct buf_t *buf, size_t required) {
#ifdef DEBUG
if (!buf)
abort();
#endif
int total_written = 0, now_written = 0;
while (1) {
if (total_written < required && total_written < buf->size) {
now_written = write(fd, buf->data, buf->size - total_written);
if (now_written < 0) break;
else {
total_written += now_written;
}
} else {
break;
}
}
buf->size -= total_written;
int i;
for (i = 0; i < buf->size; i++)
buf->data[i] = buf->data[i + total_written];
return now_written < 0 ? -1 : total_written;
}
void erase_first_n(struct buf_t *buf, size_t n) {
if (n <= 0) {
return;
}
if (n > buf->size) {
n = buf->size;
}
char *tmp = (char *)malloc(buf->size - n);
size_t i;
for (i = n; i < buf->size; i++) {
tmp[i-n] = buf->data[i];
}
free(buf->data);
buf->size -= n;
buf->data = (char *)malloc(buf->size+1);
for (i = 0; i < buf->size; i++) {
buf->data[i] = tmp[i];
}
free(tmp);
}
ssize_t buf_getline(int fd, struct buf_t *buf, char *dest) {
size_t i = 0;
for (i = 0; i < buf->size; i++) {
char cur = buf->data[i];
if (cur == '\n') {
erase_first_n(buf, i+1);
dest[i] = '\0';
return i;
}
dest[i] = cur;
}
erase_first_n(buf, i);
while (1) {
buf_fill(fd, buf, 1);
if (buf->size == 0) return i;
int j = 0;
for (j = 0; j < buf->size; j++) {
char cur = buf->data[j];
dest[i++] = cur;
if (cur == '\n') {
erase_first_n(buf, j+1);
return i;
}
}
erase_first_n(buf, 1);
}
return i;
}
void buf_clear(struct buf_t *buf) {
free(buf->data);
buf->size = 0;
}
|
C
|
#include "create_hero.h"
void print_attr(int active, int changed, char* name, int val, int line, int coll, int free_points)
{
if(active)
{
attrset(COLOR_PAIR(1));
if(changed)
attrset(A_BLINK | COLOR_PAIR(1));
}
mvaddstr(line, coll, name);
attroff(A_BLINK | COLOR_PAIR(1));
mvaddstr(line, coll + 3, ":");
if (val != 1)
{
if (active && changed == 1)
attrset(COLOR_PAIR(1));
mvaddstr(line, coll + 5, "-");
attroff(COLOR_PAIR(1));
}
mvprintw(line, coll + 7, "%2d", val);
if (free_points)
{
if(active && changed == 2)
attrset(COLOR_PAIR(1));
mvaddstr(line, coll + 10, "+");
attroff(COLOR_PAIR(1));
}
if(active && changed)
{
if (changed == 3)
attrset(COLOR_PAIR(1));
mvaddstr(line, coll + 12, "OK");
attroff(COLOR_PAIR(1));
}
}
int create_hero(ggstate* ggs)
{
const int OPT_NUM = 7;
int change_param = 0;
int curr_param = 0;
int free_points = 0;
int attrs[ATTR_NUM] = {5,5,5,5};
char* attrs_name[ATTR_NUM];
attrs_name[STR_I] = "STR";
attrs_name[CON_I] = "CON";
attrs_name[DEX_I] = "DEX";
attrs_name[INT_I] = "INT";
char* name = malloc(15);
for (int i = 0; i < 15; i++)
name[i] = '\0';
do
{
clearscreen();
curs_set(0);
int line = LINES/2 - 1;
int coll = COLS/2 - 7;
if(curr_param == 0)
{
attrset(COLOR_PAIR(1));
if(change_param)
attrset(A_BLINK | COLOR_PAIR(1));
}
mvaddstr(line, coll, "Name");coll+=4;
attroff(A_BLINK | COLOR_PAIR(1));
mvaddstr(line, coll, ":");coll+=2;
mvaddstr(line++, coll, name);coll=COLS/2-7;line++;
mvprintw(line++, coll, "POINTS: %2d", free_points);coll=COLS/2-7;
for (int i = 0; i < ATTR_NUM; i++)
{
print_attr(curr_param == 1 + i,
change_param,
attrs_name[i],
attrs[i],
line++, coll+1,
free_points);
}
if(curr_param == 5)
{
attrset(COLOR_PAIR(1));
}
mvaddstr(++line, coll, "CREATE HERO");line++;
attroff(A_BLINK | COLOR_PAIR(1));
if(curr_param == 6)
{
attrset(COLOR_PAIR(1));
}
mvaddstr(line, coll, "BACK");coll+=4;
attroff(A_BLINK | COLOR_PAIR(1));
if(curr_param == 0 && change_param)
{
move(LINES/2 - 1, COLS/2 + strlen(name) - 1);
curs_set(1);
}
int ch = getch();
switch (ch)
{
case KEY_DOWN:
if(!change_param && curr_param+1 < OPT_NUM)
{
curr_param++;
}
else if (curr_param < 4 && curr_param > 0)
{
curr_param++;
}
break;
case KEY_UP:
if(!change_param && curr_param > 0)
{
curr_param--;
}
else if (curr_param > 1)
{
curr_param--;
}
break;
case KEY_RIGHT:
if(change_param && change_param < 3)
change_param++;
break;
case KEY_LEFT:
if(change_param && change_param > 1)
{
change_param--;
if(change_param == 2 && !free_points)
change_param--;
}
break;
case '\n':
if(curr_param == 6)
return MINE_MENU;
if(curr_param == 5)
{
ggs_set_hero(ggs, name,
attrs[STR_I], attrs[CON_I],
attrs[DEX_I], attrs[INT_I],
free_points);
return WORLD;
}
if(!change_param)
change_param = 1;
else
{
if(curr_param == 0)
change_param = 0;
else
{
switch (change_param)
{
case 1:
free_points++;
attrs[curr_param-1]--;
if(attrs[curr_param-1] == 1)
change_param = 3;
break;
case 2:
free_points--;
attrs[curr_param-1]++;
if(!free_points)
change_param = 3;
break;
case 3:
change_param = 0;
break;
default:
break;
}
}
}
break;
default:
if(curr_param == 0 && change_param) {
if(isalnum(ch)) {
if(name) {
if(strlen(name) < 15) {
strncat(name, (char*)&ch, 1);
}
}
}
if(ch == KEY_BACKSPACE) {
if(name) {
if(strlen(name) > 0) {
(name)[strlen(name)-1] = '\0';
}
}
}
}
break;
}
if(change_param && between(curr_param, 1, 4))
{
if(change_param == 1 && attrs[curr_param - 1] == 1)
change_param++;
if(change_param == 2 && !free_points)
change_param++;
}
} while (true);
}
|
C
|
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#define _GNU_SOURCE
#include <sched.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/mman.h>
static char *child_stack;
static char *child_stack_end;
static size_t child_tls[512];
static size_t child_tls1[512];
static size_t child_tls2[512];
static char child_stack1[8192];
static char *child_stack_end1 = child_stack1 + 8192;
static char child_stack2[8192];
static char *child_stack_end2 = child_stack2 + 8192;
volatile int thread_started;
__attribute__((weak)) int lkl_syscall(int, long*);
static void set_tls_self_ptrs() {
child_tls[0] = &child_tls;
child_tls1[0] = &child_tls1;
child_tls2[0] = &child_tls2;
}
static void assert(int cond, const char *msg, ...)
{
if (cond) return;
va_list ap;
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
fprintf(stderr, "\nTEST_FAILED\n");
exit(-1);
}
static int futex_wait(volatile int *addr, int val)
{
return syscall(SYS_futex, addr, 0 /* FUTEX_WAIT */, val, NULL, 0, 0);
}
static int futex_wake(volatile int *addr)
{
return syscall(SYS_futex, addr, 1 /* FUTEX_WAKE */, 100, NULL, 0, 0);
}
int newthr(void *arg)
{
// Sleep long enough to make sure that the caller goes to sleep on the
// futex.
sleep(2);
thread_started = 1;
assert(arg == (void*)0x42, "New thread got correct argument");
char x;
assert(&x > child_stack, "Local variable is not on the stack");
assert(&x < child_stack_end, "Local variable is not on the stack");
fprintf(stderr, "New thread created.\n");
fprintf(stderr, "Arg: %p.\n", arg);
fprintf(stderr, "Stack: %p.\n", &x);
// This would normally crash, but SGX_LKL defers unmapping the child stack
// until the thread exits.
munmap(child_stack, child_stack_end - child_stack);
return 0;
}
volatile int barrier = 0;
volatile int counter = 0;
int parallelthr(void* arg)
{
int odd = (int)(intptr_t)arg;
fprintf(stderr, "Thread %d started\n", odd);
futex_wait(&barrier, 0);
fprintf(stderr, "Thread %d woke up\n", odd);
// After this point, the thread will not yield until the function returns.
// This depends on the kernel waking up two clone'd threads and having them
// run in parallel. The purpose of this test is to ensure that nothing in
// the SGX-LKL host interface that backs the clone system call causes
// host tasks to become serialised.
// Note: This test will work only with 2+ ethreads.
while (1)
{
int v = __atomic_load_n(&counter, __ATOMIC_SEQ_CST);
if (v == 100)
break;
if (v % 2 == odd)
{
__atomic_compare_exchange_n(&counter, &v, v+1, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
}
}
fprintf(stderr, "Thread %d finished\n", odd);
return 0;
}
int main(int argc, char** argv)
{
set_tls_self_ptrs();
unsigned flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND
| CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS | CLONE_CHILD_SETTID
| CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED;
pid_t ptid;
pid_t ctid = 0;
child_stack = mmap(0, 8192, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
child_stack_end = child_stack + 8192;
assert(child_stack != MAP_FAILED, "Failed to map child stack");
fprintf(stderr, "Clone syscall number: %d\n", SYS_clone);
fprintf(stderr, "lkl_syscall: %p\n", lkl_syscall);
fprintf(stderr, "fn: %p \n", newthr);
fprintf(stderr, "ctid: %p \n", &ctid);
fprintf(stderr, "Stack: %p-%p \n", child_stack, child_stack_end);
int clone_ret = clone(newthr, child_stack_end, flags, (void*)0x42, &ptid, &child_tls, &ctid);
if (clone_ret == -1)
{
perror("Clone failed");
}
fprintf(stderr, "Clone returned %d, ctid: %d ptid: %d\n", clone_ret, ctid, ptid);
assert(ctid == clone_ret, "ctid is %d, should be %d\n", ctid, clone_ret);
int futex_ret = futex_wait(&ctid, clone_ret);
assert(futex_ret == 0, "futex syscall returned %d (%s)\n", futex_ret, strerror(errno));
fprintf(stderr, "After futex call, ctid is %d\n", ctid);
assert(ctid == 0, "ctid was not zeroed during futex wait\n");
fprintf(stderr, "Other thread should have terminated by now.\n");
assert(thread_started == 1, "Thread did not run");
fprintf(stderr, "Thread stacks: %p, %p, %p\n", child_stack, child_stack1, child_stack2);
pid_t ctid_futex1, ctid_futex2;
pid_t ctid1 = clone(parallelthr, child_stack_end1, flags, (void*)0, &ptid, &child_tls1, &ctid_futex1);
pid_t ctid2 = clone(parallelthr, child_stack_end2, flags, (void*)0x1, &ptid, &child_tls2, &ctid_futex2);
fprintf(stderr, "Created two threads: %d, %d, waking them now\n", ctid1, ctid2);
barrier = 1;
fprintf(stderr, "\nIf this test hangs after waking up one thread, check you have at least 2 ethreads\n");
fprintf(stderr, "This test is checking that LKL is able to wake up two cloned threads and leaving them running in parallel\n\n");
futex_wake(&barrier);
fprintf(stderr, "Waiting for for Thread 0 to finish\n");
futex_wait(&ctid_futex1, ctid1);
fprintf(stderr, "Waiting for for Thread 1 to finish\n");
futex_wait(&ctid_futex2, ctid2);
fprintf(stderr, "\nTEST_PASSED\n");
return 0;
}
|
C
|
/*
* Dylan Brown
*
* The purpose of this code is to accept a user's integer input, and output the
* prime numbers in the range and the number of twin prime sets there are.
*
*/
#include <stdio.h>
#include <math.h>
int checkForPrime(int val);
int promptUserForInteger();
int checkInputForCorrectValue(int input);
int findAllPrimes(int userValue);
int printOutIfItIsAPrime(int num);
int checkForTwinPrimes(int num, int lastPrime, int numberOfTwinPrimes);
int main(){
int x = promptUserForInteger();
checkInputForCorrectValue(x);
printf("Primes from 2 to %d:\n",x);
findAllPrimes(x);
return 0;
}
int promptUserForInteger(){
int input;
printf("Please enter a positive integer that is greater than 1 and less than 200.\n\n");
scanf("%d", &input); //Obtains the user's input for their number.
int correctValue = checkInputForCorrectValue(input); //Checks if the user's input is valid.
if (correctValue == 0){
input = promptUserForInteger(); //If the user's input is invalid, asks for their input again.
}
return input;
}
int checkInputForCorrectValue(int x){
if (x > 1 && x < 200){ //If the integer is anywehre from 2 to 199, it is a correct input.
return 1;
}
else if (x < 2){ //If the integer is less than 2, then it is not a prime number. Prompts the user to reenter an input.
printf("Please enter an integer greater than 1.\n");
}
else if (x > 200){ //If the integer is greater than 200, then it is outside of the scope for the project.
printf("Please enter an integer less than 200.\n");
}
return 0; //Return a 0 so the user has to reenter an input.
}
int findAllPrimes(int userValue){
int num = 2; //This is the first prime number we will check.
int numberOfTwinPrimes = 0; //Initially, there should be 0 twin primes. This counter will go up for each pair found.
int lastPrime = 0; //This is where the last prime number will be stored.
while (num <= userValue){
//While our incremented number is less than the user's input, or equal to.
if (printOutIfItIsAPrime(num) == 1){ // If it IS a prime number, then we will check for twin primes
numberOfTwinPrimes = checkForTwinPrimes(num, lastPrime, numberOfTwinPrimes);
//If there was a twin prime, the number of twin primes will be incremented.
lastPrime = num;
//The prime number will now be stored as the lastPrime.
}
num++;
//Increment num to iterate through all primes.
}
printf("\nAmongst these there are %d twin primes.\n", numberOfTwinPrimes);
//Print out the total number of twin primes that the code has found.
return 0;
}
int checkForTwinPrimes(int num, int lastPrime, int numberOfTwinPrimes){
if (lastPrime != 0 && (num - lastPrime) == 2){
//If the last prime number is 0, then that was our initial case and we shouldn't check for twin primes yet.
//If the current number minus the lastPrime number is equal to two, then we found a twin prime and should increment our counter.
numberOfTwinPrimes++;
}
//return our newly incremented value.
return numberOfTwinPrimes;
}
int printOutIfItIsAPrime(int num){
if (checkForPrime(num) == 1){
//If it is a prime number, then print out that prime number and return a 1.
printf("%d ", num);
return 1;
}
//If it is not a prime, return a 0.
return 0;
}
int checkForPrime(int val){
//Check to see if the number val is a prime number.
int i = 2;
//Start with the first prime, 2.
while(i < val){
if (i != val && val % i == 0){
//If for any i, i is the same as the number val
//Or if val modulus i is equal to 0, for any number less than i
//Then the number is not a prime, and return 0 immediately.
return 0;
}
//Increment i to check for more numbers less than the number val.
i++;
}
//If there was no case found where the number val isn't a prime, then it is a prime. Return 1.
return 1;
}
|
C
|
#include <stdio.h>
#include <math.h>
int n = 0; //存储棋盘大小
int res[16] = {-1}; //存储对应行的皇后列数
int count = 0; //记录总方法数
//在第n行找皇后的位置
void tosolve(int line)
{
//一列列搜索
for (int i = 1; i <=n; i++)
{
if (line != 1 && i == res[line - 1])
continue;
int flag = 1;
for (int j = 1; j <line; j++)
{
if (i == res[j] || (abs(line - j)) == (abs(i - res[j])))
{
flag = 0; //同一列、同一对角线拒绝
break;
}
}
if (flag)
{
res[line] = i; //记录下这行所对应的皇后的列数
if (line == n)
{
count++;
/*for (int j = 1; j < n; j++)
{
printf("%d ",res[j]);
}*/
//printf("\n");
return;
}
//若没放满则放下一行
tosolve(line + 1);
res[line] = -1;
}
}
return;
}
int main(int argc, char const *argv[])
{
//输入棋盘大小
scanf("%d", &n);
//从第1行开始
tosolve(1);
//输出
printf("%d", count);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <linux/limits.h>
#include "shell_usage/term_utils.h"
void pash_loop(void) {
char *line;
char **args;
int status;
char *shell;
shell = pash_check_dir(shell);
do {
printf("%s", shell);
line = pash_read_line();
args = pash_split_line(line);
status = pash_execute(args);
shell = pash_check_dir(shell);
} while (status);
}
int main() {
// Load config files
// Run command loop
pash_loop();
// Perform any shutdown/cleanup
return EXIT_SUCCESS;
}
|
C
|
/**
* \file io_graphique.h
* \brief Declaration des fonctions d'affichage graffique d'une grille
*/
#ifndef __IO_H
#define __IO_H
#include <stdio.h>
#include <cairo.h>
#include <cairo-xlib.h>
#include <X11/Xlib.h>
#include "grille.h"
#include "jeu.h"
/**
* \fn affiche_grille_gr(const grille *g, cairo_surface_t *surface)
* \brief Affiche dans une fenetre X11 une grille
*
* \param g grille a afficher
* \param surface surface cairo sur laquelle sera affichée la grille
* \return void mais la grille a été affichée dans une fenetre X11
*/
void affiche_grille_gr(const grille *g, cairo_surface_t *surface, unsigned int temps_evolution);
/**
* \fn efface_grille_gr(cairo_surface_t *surface)
* \brief Efface une surface cairo
*
* \param surface surface a effacer
* \return void
*/
void efface_grille_gr(cairo_surface_t *surface);
/**
* \fn debut_jeu_gr(grille *g, grille *gc)
* \brief Debute le jeu avec g comme grille de depart a t0
*
* \param g grille au moment t
* \param gc grille qui va servir a garder g en memoire
* \return void le jeu commence et est affiché dans une fenetre X11
*/
void debut_jeu_gr(grille *g, grille *gc);
void clean_surface(cairo_surface_t *surface);
/**
* \fn grilles_egales(grille *g, grille *gc)
* \brief Compare si deux grilles sont identiques
*
* \param g
* \param gc
* \return Un booleen representant g == gc
*/
bool grilles_egales(grille *g, grille *gc);
#endif
|
C
|
// Задача 2. Напишете функция area() без параметри. Поискайте от
// потребителя да въведе радиуса с помощта на функциите :
// printf("Enter a radius\n");
// scanf("%lf", &r);
// Използвайте горната функция 1.за изчисляване на площта на кръг,
// която написахме преди малко за да изчислите площта на кръга с този
// радиус и върнете резултата:
#include <stdio.h>
double aCircle(double r);
double area();
extern const double pi;
int main(){
area();
return 0;
}
const double pi = 3.14;
double aCircle(double r){
return r*r*pi;
}
double area(){
double r;
printf("Enter a radius\n");
scanf("%lf",&r);
printf("area = %lf",aCircle(r));
}
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
float P, c, d, n = 1.0, temp;
printf("\nEnter the original cost: ");
scanf("%f", &c);
printf("\nEnter the depriciation rate: ");
scanf("%f", &d);
printf("\nEnter the scrap value: ");
scanf("%f", &P);
while (temp >= P)
{
temp = c * pow((1.0 - d), n);
n += 1.0;
}
printf("\nUseful life (in years): %f", n);
}
|
C
|
#include <stdio.h>
void printando(char M, int i, int N);
int main() {
int N; // N=ordem da matriz
while(scanf("%d",&N)!=EOF){ // condição para não ser EOF
// N é a ordem da matriz, mas os elementos são N*N
int elementos = N*N;
char M[elementos];
int i=0;
int meio= (elementos-1)/2;
for(i=0;i<elementos;i++){
// preenchendo os valores da matriz
if(i%(N+1)==0 && i!=meio){ // diagonal principal
M[i]=1;
}else if(i!=0 && (((i%(N-1))==0))){
// diagonal secundária
M[i] =2;
}else{
M[i]=3;
}
printando(M[i],i, N);
}
}
return 0;
}
void printando(char M, int i, int N){
if(i!=0 && (((i+1)%N)==0)){ // ou seja é a última linha
printf("%d\n", M);
}else{
printf("%d", M);
}
}
|
C
|
#include<iostream>
#include<stdio.h>
#include<GL/glut.h>
#include<GL/gl.h>
float X1,X2,Y1,Y2;
void pixel(int x, int y) {
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
glFlush();
}
void bresenham(void){
glClear(GL_COLOR_BUFFER_BIT);
int dx, dy, i, p;
int incx, incy, inc1, inc2;
int x,y;
dx = X2-X1;
dy = Y2-Y1;
if (dx < 0) dx = -dx;
if (dy < 0) dy = -dy;
incx = 1;
if (X2 < X1) incx = -1;
incy = 1;
if (Y2 < Y1) incy = -1;
x = X1; y = Y1;
if (dx > dy) {
pixel(x, y);
p = 2 * dy-dx;
inc1 = 2*(dy-dx);
inc2 = 2*dy;
for (i=0; i<dx; i++) {
if (p >= 0) {
y += incy;
p += inc1;
}
else
p += inc2;
x += incx;
pixel(x, y);
}
} else {
pixel(x, y);
p = 2*dx-dy;
inc1 = 2*(dx-dy);
inc2 = 2*dx;
for (i=0; i<dy; i++) {
if (p >= 0) {
x += incx;
p += inc1;
}
else
p += inc2;
y += incy;
pixel(x, y);
}
}
}
void init(){
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glMatrixMode(GL_PROJECTION);
glutInitWindowPosition(0,0);
glutInitWindowSize(500, 500);
glutCreateWindow("BRESENHAM'S LINE");
glClearColor(1.0,1.0,1.0,0);
glColor3f(0.0f,1.0f,0.0f);
gluOrtho2D(0,500,0,500);
}
int main(int argc, char **argv) {
printf("Enter the values of x1,y1 : ");
scanf("%f", &X1);
scanf("%f", &Y1);
printf("Enter the values of x2,y2 : ");
scanf("%f", &X2);
scanf("%f", &Y2);
glutInit (&argc, argv);
init();
glutDisplayFunc(bresenham);
glutMainLoop ();
return 0;
}
|
C
|
#ifndef CAMERA_H
#define CAMERA_H
#define CAM_PARALLEL 1
#define CAM_CONIC 2
#define CAM_TRIPODE 3
#define CAM_PAN 4
#define CAM_STOP 0
#define CAM_EXAMINAR 1
#define CAM_PASEAR 2
typedef struct _Camera
{
// we consider a rigth handed reference system for the camera
// V point where the camera is placed (world coordinates)
// A point the camera is looking at (world coordinates)
// up vector : unit vector, perpendicular to AV (world componnents)
// origin camera reference system : at V
// Z camera : defined by vector from A to V (penetrates the viewer's eye)
// Y camera : defined by up vector
// X camera : looking from V towards A goes rigthwards
float camViewX; // View point
float camViewY;
float camViewZ;
float camAtX; // look At point
float camAtY;
float camAtZ;
float camUpX; // Up vector
float camUpY;
float camUpZ;
float camAperture; // field of view radians // NOTE : OpenGL uses degrees
// defined as they are used by OpenGL
// always => positive ; Far > Near (distance from plane to camera origin)
float camNear;
float camFar;
int camProjection; // PARALLEL or CONIC
int camMovimiento; // EXAMINAR, ANDAR, TRIPODE or PAN
// ****** dependent values ******
// window system dependent
float aspectRatio;
// for ortho projection
float x1, x2, y1, y2, z1, z2;
// camera i j k vectors in world coordinates
float camIX, camIY, camIZ;
float camJX, camJY, camJZ;
float camKX, camKY, camKZ;
} camera;
void DestroyCamera ( _Camera **theCamera );
camera *CreatePositionCamera( float positionX, float positionY, float positionZ );
void SetCamera( _Camera *thisCamera, float viewX, float viewY, float viewZ,
float atX, float atY, float atZ,
float upX, float upY, float upZ );
void SetDependentParametersCamera( _Camera *thisCamera );
void SetGLCamera( _Camera *thisCamera );
void SetGLAspectRatioCamera( _Camera *thisCamera );
// Free camera advances "step" following vector VA, step admits negative values
void AvanceFreeCamera( _Camera *thisCamera, float step );
// ROTATION
void YawCamera( _Camera *thisCamera, float angle );// local axis Y camera
void Rotate_Latitude( _Camera *thisCamera, float inc );
void Rotate_Longitude( _Camera *thisCamera, float inc );
void PitchCamera( _Camera *thisCamera, float angle ); // local axis Z camera
void PanCamera( _Camera *thisCamera, float stepX, float stepY );
#endif /* CAMERA_H */
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
//º¸µåÆÇ ÃʱâÈ »óÅÂ
int main(int argc, char *argv[]) {
int gameboard[6][6]={0};
board();
return 0;
}
int board(int gameboard[6][6]) {
int i,j;
printf(" 0 1 2 3 4 5\n--------------\n");
for(i=0;i<6;i++){
printf("%d|",i);
for(j=0;j<6;j++){
printf("%d|",gameboard);
}
printf("\n--------------\n");
}
return gameboard[6][6];
}
|
C
|
/*
* timer_setup.c
*
* Created: 14/09/2018 8:53:20 AM
* Author: Oliver K jkim838 846548800
*
* Revision 1.3.0
*
* This script file contains definitions for functions related to Timer and PWM.
*
*/
/*** Header Files ***/
#include <avr/io.h>
#include <stdint.h>
/*** Custom Header Files ***/
#include "timer_setup.h"
#include "Macro_Definitions.h"
/*** Custom Macro Definition ***/
void timer2_init(){
/*** TCCR2A: TC2 Control Register A ***/
// Operate at Normal Timer Mode...
/*** TCCR2B: TC2 Control Register B ***/
/** Prescaler Selection **/
#ifdef XPLAINED_MINI_MODE
// The program is being tested on a Xplained Mini Board, and it is running at 16MHz.
TCCR2B |= (1 << CS22); // Set prescaler to 64
TCCR2B &= ~(1 << CS21); // @F_CPU 16 MHz... F(Timer) = 250KHz
TCCR2B &= ~(1 << CS20);
#else
// The program is running at 8MHz.
TCCR2B &= ~(1 << CS22); // Set prescaler to 32
TCCR2B |= (1 << CS21); // @F_CPU 8 MHz... F(Timer) = 250KHz
TCCR2B |= (1 << CS20);
#endif
/*** TIMSK0: TC0 Interrupt Mask Register ***/
TIMSK2 |= (1 << OCIE2A); // Timer/Counter2 Output Compare A Match Interrupt Enabled
TIMSK2 |= (1 << OCIE2B); // Timer/Counter2 Output Compare B Match Interrupt Enabled
}
// NOTE
|
C
|
// 计算谱半径
#include <stdio.h>
#include <math.h>
int main(int argc, char const *argv[])
{
int nums;
scanf("%d", &nums);
int i;
double a, b, temp;
double res = 0.0;
for(i=0; i<nums; i++){
scanf("%lf %lf", &a, &b);
temp = sqrt(a*a + b*b);
if(temp > res) res = temp;
}
printf("%.2lf\n", res);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int a, b, c;
int max(int, int);
while (scanf("%d %d %d", &a, &b, &c) != EOF)
printf("%d\n", max(a, max(b, c)));
}
int max(int a, int b)
{
if (a > b)
return a;
else
return b;
}
|
C
|
/* ************************************************************************** */
/* LE - / */
/* / */
/* ft_string.c .:: .:/ . .:: */
/* +:+:+ +: +: +:+:+ */
/* By: xamartin <marvin@le-101.fr> +:+ +: +: +:+ */
/* #+# #+ #+ #+# */
/* Created: 2017/12/06 18:23:30 by xamartin #+# ## ## #+# */
/* Updated: 2018/02/03 18:07:04 by xamartin ### #+. /#+ ###.fr */
/* / */
/* / */
/* ************************************************************************** */
#include "libft.h"
size_t string(char *str, t_opt option)
{
size_t i;
char *tmp;
i = 0;
if (str)
tmp = ft_strdup(str);
else
tmp = ft_strdup("(null)");
apoption(&option, &tmp, 0);
if (option.accurancy || (option.accurancy && (option.blank
&& (option.ok == 1 || !option.ok || option.zero))))
blank(&tmp, &option, 0);
ft_putstr(tmp);
i = ft_strlen(tmp);
ft_strdel(&tmp);
return (i);
}
size_t string1(wchar_t *wstr, t_opt option)
{
size_t i;
char *str;
i = 0;
str = ft_strdup("");
apoption(&option, &str, 0);
if (option.accurancy || (option.accurancy && (option.blank
&& (option.ok == 1 || !option.ok || option.zero))))
blank(&str, &option, 0);
if (wstr)
i += ft_putwstr(wstr);
else
{
i += 6;
ft_putstr("(null)");
}
ft_strdel(&str);
return (i);
}
size_t ft_string(char *format, va_list ap)
{
size_t i;
size_t j;
t_opt option;
i = 1;
j = parseall(format, &option, 0);
if (option.star)
option.accurancy = (int)va_arg(ap, int);
if (option.l == 1 || format[ft_strlen(format) - 1] == 'S')
i = string1((wchar_t *)va_arg(ap, wchar_t *), option);
else
i = string((char *)va_arg(ap, char *), option);
return (i);
}
|
C
|
/**
* @file event.h
*
* @brief Simple definition of an event
*
* @author Gornet Mélanie
*
* This is a simple definition of an event
*/
#include <stdbool.h>
#include "particle.h"
#ifndef EVENT_H
#define EVENT_H
/**
* @brief An alias to the structure representing the event
*/
typedef struct event event;
/**
* @brief The structure representing an event.
*/
struct event {
/** The time at which the event occurs */
double time;
/** A pointer to the first particle involved in the collision */
particle *p_particle_a;
/** A pointer to the second particle involved in the collision */
particle *p_particle_b;
/** The number of collisions in which the particle a has been involved at the time of the event */
int nb_collisions_particle_a;
/** The number of collisions in which the particle b has been involved at the time of the event */
int nb_collisions_particle_b;
};
/**
* @brief Test if an event is valid according to the definition of a
* valid event in the subject
*
* @param p_my_event a pointer to the event to consider
* @param time the time when the event is checked
*
* @return `true` if the evnt is valid, `false` else
*/
bool is_valid(event *p_my_event, double time);
/**
* @brief Print the elements of a particle
*
* @param p_particle a pointer to the particle to print
*/
void print_particle(particle *p_particle);
/**
* @brief Print the elements of an event
*
* @param p_event a pointer to the event to print
*/
void print_event(event *p_event);
#endif
|
C
|
//멀티쓰레드
#include <stdio.h>
#include <Windows.h>
CRITICAL_SECTION cs; //cs에는 하나의 스레드만 들어갈 수 있다.
void delay()
{
for (int i = 0; i < 10000000; i++);
}
DWORD __stdcall foo(void *p)
{
// int x = 0;
static int x = 0;
for (int i = 0; i < 20; i++)
{
//Serialization : 직렬화
EnterCriticalSection(&cs); //cs에 들어간다
//------------------------
x = 100; delay();
x = x + 1; delay();
printf("%s : %d\n", p, x); delay();
//--------------------
LeaveCriticalSection(&cs); //cs에 나온다.
}
printf("%s finish\n", p);
return 0;
}
int main()
{
InitializeCriticalSection(&cs);
//foo("A");
HANDLE h1 = CreateThread(0, 0, foo, "A", 0, 0);
HANDLE h2 = CreateThread(0, 0, foo, "B", 0, 0);
//2개이상의 스레드를 대기하는 법
HANDLE h[2] = { h1, h2 };
WaitForMultipleObjects(2, h, TRUE, //모두 종료될때까지
INFINITE);
DeleteCriticalSection(&cs);
//리눅스
//pthread_join(h1)
//pthread_join(h2)
}
|
C
|
/*
** EPITECH PROJECT, 2021
** error.c
** File description:
** error function
*/
#include "my.h"
#include "struct.h"
#include <stdlib.h>
void get_coords(map_i_t *map_i)
{
int idx = 0;
map_i->loc_coord = malloc(sizeof(row_col) * map_i->nb_loc);
for (int i = 0; map_i->map[i]; ++i)
for (int j = 0; map_i->map[i][j]; ++j) {
if (map_i->map[i][j] == 'P') {
map_i->p_coord.row = i;
map_i->p_coord.col = j;
map_i->p_coord_cpy = map_i->p_coord;
}
if (map_i->map[i][j] == 'O') {
map_i->loc_coord[idx].row = i;
map_i->loc_coord[idx].col = j;
++idx;
}
}
}
void upd_numbers(char c, int *nb_p, int *nb_boxes, int *nb_loc)
{
*nb_p += (c == 'P');
*nb_boxes += (c == 'X');
*nb_loc += (c == 'O');
}
int matching_boxes_locations(map_i_t *map_i)
{
int nb_p = 0;
int nb_boxes = 0;
int nb_loc = 0;
for (int i = 0; map_i->map[i]; ++i)
for (int j = 0; map_i->map[i][j] != '\0'; ++j) {
if (map_i->map[i][j] != '#' && map_i->map[i][j] != 'P'
&& map_i->map[i][j] != 'X' && map_i->map[i][j] != 'O'
&& map_i->map[i][j] != ' ' && map_i->map[i][j] != '\n')
return 84;
upd_numbers(map_i->map[i][j], &nb_p, &nb_boxes, &nb_loc);
}
if (nb_p != 1 || (nb_boxes == 0 && nb_loc == 0) ||
nb_boxes < nb_loc)
return 84;
map_i->nb_boxes = nb_boxes;
map_i->nb_loc = nb_loc;
map_i->nb_loc_cpy = nb_loc;
get_coords(map_i);
return 0;
}
int longest_line(char **tab)
{
int len = 0;
int max = 0;
for (int i = 0; tab[i]; ++i) {
len = my_strlen(tab[i]);
max = (len > max) ? len : max;
}
return max;
}
int error(int ac, char **av, map_i_t *map_i)
{
char *map;
if (ac != 2)
return 84;
map = load_file_in_mem(av[1]);
if (map == NULL)
return 84;
map_i->map = my_str_to_word_array_delim(map, '\n');
map_i->map_cpy = copy_tab(map_i->map);
free(map);
if (matching_boxes_locations(map_i) == 84) {
free(map_i->map);
free(map_i->map_cpy);
return 84;
}
map_i->nb_row = my_tab_length(map_i->map);
map_i->nb_col = longest_line(map_i->map);
return 0;
}
|
C
|
#include <stdlib.h>
#include <unistd.h>
char *affiche_h(char c)
{
write(1, &c, 1);
return c;
}
char *affiche_e(char c)
{
write(1, &c, 1);
return c;
}
char *affiche_l(char c)
{
write(1, &c, 1);
return c;
}
char *affiche_l(char c)
{
write(1, &c, 1);
return c;
}
char *affiche_o(char c)
{
write(1, &c, 1);
return c;
}
char *affiche_0(char c)
{
write(1, &c, 1);
return c;
}
int main(void)
{
char *hello;
hello = (char *)malloc(sizeof(char) * 6);
hello[0] = 'h';
hello[1] = 'e';
hello[2] = 'l';
hello[3] = 'l';
hello[4] = 'o';
hello[5] = '\0';
affiche_h('h');
affiche_e('e');
affiche_l('l');
affiche_l('l');
affiche_o('o');
affiche_0('h');
write(1, " world", 6);
free(hello);
}
|
C
|
/*
** EPITECH PROJECT, 2019
** pushswap
** File description:
** push_list
*/
#include <linked_list.h>
void push_back(dlist_t **dlist, void *data, int name)
{
node_t *new_elemnt = malloc(sizeof(node_t));
new_elemnt->prev = NULL;
new_elemnt->next = NULL;
new_elemnt->data = data;
new_elemnt->name = name;
if (is_empty_dlist(*dlist) == true) {
(*dlist) = malloc(sizeof(dlist_t));
(*dlist)->end = new_elemnt;
(*dlist)->begin = new_elemnt;
(*dlist)->len = 0;
} else {
new_elemnt->prev = (*dlist)->end;
(*dlist)->end->next = new_elemnt;
(*dlist)->end = new_elemnt;
}
(*dlist)->len += 1;
}
void push_front(dlist_t **dlist, void *data, int name)
{
node_t *new_elemnt = malloc(sizeof(node_t));
new_elemnt->prev = NULL;
new_elemnt->next = NULL;
new_elemnt->data = data;
new_elemnt->name = name;
if (is_empty_dlist(*dlist) == true) {
*dlist = malloc(sizeof(dlist_t));
(*dlist)->begin = new_elemnt;
(*dlist)->end = new_elemnt;
(*dlist)->len = 0;
} else {
new_elemnt->next = (*dlist)->begin;
(*dlist)->begin->prev = new_elemnt;
(*dlist)->begin = new_elemnt;
}
(*dlist)->len += 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "customer.h"
#include "seller.h"
void *seller(void *seller_args) {
seller_args_t args = *((seller_args_t *) seller_args);
printf("{%s} id: %d, priority: %d\n", args.name, args.id, args.priority);
return NULL;
}
|
C
|
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t p1,p2,p3,p4;
pid_t parent = getpid();
int c=0;
printf("Parent Process\n",getpid());
p1=fork();
if(p1<0)
{
return -1;
}
if(p1==0)
{
printf("Process 2 with pid: %d CREATED\n",getpid());
p2 = fork();
if(p2==0)
{
printf("Process 3 with pid: %d CREATED\n",getpid());
p3=fork();
if(p3==0)
{
printf("Process 4 with pid: %d CREATED\n",getpid());
p4=fork();
if(p4==0)
{
printf("Process 5 with pid: %d CREATED\n",getpid());
}
}
}
else{
printf("");
}
}
else{
printf("");
}
return 0;
}
|
C
|
#include <string.h>
#include <stdlib.h>
#include <math.h>
int Back(const char* str, int len, int i) {
int c = str[i] - 48;
if (i == len - 1)
return c* pow(10, len - i - 1);
int numero = c*pow(10, len - i -1);
return numero + Back(str, len, i + 1);
}
int AToI(const char* str) {
if (str == NULL)
return 0;
int len = strlen(str);
int som = Back(str, len, 0);
return som;
}
|
C
|
#include<unistd.h>
#include<pthread.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
extern void err_quit(const char *, ...);
void *thr_fn1(void *arg)
{
printf("thread 1 returning...\n");
return ((void *)1);
}
void *thr_fn2(void *arg)
{
printf("thread 2 returning...\n");
return ((void *)2);
}
int main(void)
{
int err;
pthread_t tid1, tid2;
void *tret;
err = pthread_create(&tid1, NULL, thr_fn1, NULL);
if(err != 0)
err_quit("Can't create thread 1: %s\n", strerror(err));
err = pthread_create(&tid2, NULL, thr_fn2, NULL);
if(err != 0)
err_quit("Can't create thread 2: %s\n", strerror(err));
if((err = pthread_join(tid1, &tret)))
err_quit("Can't join with thread 1: %s\n", strerror(err));
printf("thread 1 exit code %d\n", (int)tret);
sleep(2);
if((err = pthread_join(tid2, &tret)))
err_quit("Can't join with thread 2: %s\n", strerror(err));
printf("thread 2 exit code %d\n", (int)tret);
exit(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#define ERROR(x) do { perror(x); exit(-1); } while (0)
#define ASSERT(x, y) do { if (!(x)) { perror(y); exit(-1); } } while (0)
void check(int i) {
if (i == 0x1234) {
printf("ok\n");
}
}
int main(int argc, char *argv[]) {
char buffer[4];
int i;
volatile int j, k;
int fd;
if (argc != 2) {
printf("Usage: %s <file>\n", argv[0]);
exit(-1);
}
ASSERT((fd = open(argv[1], O_RDONLY)) != -1, "open");
ASSERT(read(fd, buffer, 4) == 4, "read");
j = 0x1234;
k = 0x5678;
i = (buffer[0] == '*') ? j : k; /* mux0x */
check(i);
return 0;
}
|
C
|
#include "sum.h"
#include "pipes.h"
#include <unistd.h>
#include <sys/wait.h>
int sum_of_one_proc(const int *arr, size_t size, int64_t *sum) {
if (arr == NULL || sum == NULL || size < 1) {
return NULL_ARGS;
}
*sum = 0;
size_t i_end = (int)((size - 1) / UPPER_BOUND);
for (size_t i = 0; i <= i_end; ++i) {
for (size_t k = 0; k < UPPER_BOUND && k + UPPER_BOUND * i < size; ++k) {
*sum += arr[k + UPPER_BOUND * i];
}
}
return SUCCESS;
}
int single_proc_handler(size_t proc_number, pipes_t *pipes, const int *arr, size_t size) {
if (close_all_except_write_pipe(pipes, proc_number) != 0) {
exit(EXIT_FAILURE);
}
int64_t sum = 0;
sum_of_one_proc(arr, size, &sum);
if (write_pipe(pipes, proc_number, sum) != 0) {
close_pipes(pipes);
exit(EXIT_FAILURE);
}
if (close_pipes(pipes) != 0) {
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
int calculate_sum(const int *arr, size_t size, int64_t *sum) {
if (arr == NULL || sum == NULL || size < 1) {
return NULL_ARGS;
}
size_t num_cores = sysconf(_SC_NPROCESSORS_ONLN);
pipes_t *pipes = create_pipes(num_cores);
if (pipes == NULL) {
return CREATE_PIPES_FAILED;
}
size_t current_proc = 0;
size_t size_one_proc = (size_t)(size / num_cores);
for (const int *arr_begin = arr; current_proc < num_cores; ++current_proc, arr_begin += size_one_proc) {
int pid = fork();
if (pid == -1) {
close_pipes(pipes);
return FORK_FAILED;
}
if (pid == 0) {
if (current_proc + 1 == num_cores) {
size_one_proc = size - current_proc * size_one_proc;
}
single_proc_handler(current_proc, pipes, arr_begin, size_one_proc);
}
}
close_all_write_pipes(pipes);
int status = 0;
current_proc = 0;
for (; current_proc < num_cores; ++current_proc) {
if (wait(&status) < 0 || !WIFEXITED(status)) {
close_pipes(pipes);
return WAIT_FAILED;
}
}
*sum = 0;
current_proc = 0;
for (; current_proc < num_cores; ++current_proc) {
int64_t small_sum = 0;
if (read_pipe(pipes, current_proc, &small_sum) != 0) {
close_pipes(pipes);
return READ_PIPE_FAILED;
}
*sum += small_sum;
}
close_pipes(pipes);
return SUCCESS;
}
|
C
|
//
// StaticLink.h
// FuckC
//
// Created by pinn on 2018/12/25.
// Copyright © 2018 PINN. All rights reserved.
//
#ifndef StaticLink_h
#define StaticLink_h
#include <stdio.h>
#include <stdlib.h>
#endif /* StaticLink_h */
//通过 "数组+游标" 的方式存储具有线性关系数据的存储结构就是静态链表。
//静态链表中的节点
typedef struct {
int data;//数据域
int cur;//游标
}component;
//备用链表
//静态链表中,除了数据本身通过游标组成的链表外,还需要有一条连接各个空闲位置的链表,称为备用链表。
//备用链表的作用是回收数组中未使用或之前使用过(目前未使用)的存储空间,留待后期使用。
//通常,备用链表的表头位于数组下标为 0(a[0]) 的位置,而数据链表的表头位于数组下标为 1(a[1])的位置。
#define maxSize 6
/**
备用链表
*/
void reserveArr(component *array);
/**
初始化静态链表
*/
int initArr(component *array);
/**
显示静态链表
*/
void displayArr(component *array, int body);
/**
从备用链表上摘下空闲节点
*/
int mallocArr(component *array);
|
C
|
/**
* Dada Kernel
* October 2014
*
* Wiktor Lukasik (wiktor@lukasik.org)
*/
#include "console.h"
#include "sys.h"
void cpuid() {
register int b asm("ebx");
register int c asm("ecx");
register int d asm("edx");
__asm__("movl $0, %eax");
__asm__("cpuid");
cpu_name[0] = (char) b;
cpu_name[1] = (char) (b >> 8);
cpu_name[2] = (char) (b >> 16);
cpu_name[3] = (char) (b >> 24);
cpu_name[4] = (char) (d);
cpu_name[5] = (char) (d >> 8);
cpu_name[6] = (char) (d >> 16);
cpu_name[7] = (char) (d >> 24);
cpu_name[8] = (char) (c);
cpu_name[9] = (char) (c >> 8);
cpu_name[10] = (char) (c >> 16);
cpu_name[11] = (char) (c >> 24);
cpu_name[12] = '\0';
}
void outportb(unsigned short port, unsigned char data) {
asm volatile ("outb %1, %0" : : "dN" (port), "a" (data));
}
unsigned char inportb(unsigned short port) {
unsigned char rv;
asm volatile ("inb %1, %0" : "=a" (rv) : "dN" (port));
return rv;
}
void panic(char * msg) {
if(msg != 0) {
printk("PANIC MESSAGE: %s\n", msg);
}
halt_and_catch_fire();
}
void halt_and_catch_fire() {
printk("SYSTEM HALTED!");
// TODO: come up with a more definitive kill method.
for(;;) {}
}
|
C
|
//C program to find vowels and consonants in a string using pointer.
#include<stdio.h>
void main()
{
char b[10];
char *p;
printf("Enter any string to find vowel or cosonant\n");
scanf("%s",b);
p=b;
if(*p=='a'||*p=='e'||*p=='i'||*p=='o'||*p=='u'||*p=='A'||*p=='E'||*p=='I'||*p=='O'||*p=='U')
{
printf("Given string is Vowel\n");
}
else
{
printf("Given string is consonant\n");
}
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
int t=10000000;//t of play in seconds
int speed=10;//speed of snake(1 to 100 is prefereble).
int cw=82,ch=22;//canvas size
char CAN[50][125];//canvas array
int TAILX[4600]={0},taily[4600]={0},tails=0;//tail coordinates and number of tails
int DIR=1,x=1,y=1;//position and direction
int FX=0,fy=0;//food positions
char c,o,l;//key pressed
int score=0;
char highscore[10]="1000";
int h=0,h_=0;
FILE *ptr;
//*************clear canvas**********************
void clr()
{
for(int i=0;i<ch;i++)
{for(int j=0;j<cw;j++)
{if(i==0||j==0||i==ch-1||j==cw-1)
CAN[i][j]='+';
else
CAN[i][j]=' ';
}}
}
//************display canvas**********************
void disp()
{system("CLS");
printf("Press x to exit.!|Score:%d|Speed:%d|Highscore:%d\n",score,speed,h_);
for(int i=0;i<ch;i++)
{for(int j=0;j<cw;j++)
putchar(CAN[i][j]);
printf("\n");
}
}
//*************food generation****************************
void food()
{int ftx,fty,ic=0;
a:
ic=0;ftx=time(NULL)%(cw-1);fty=time(NULL)%(ch-1);
for(int e=0;e<tails;e++)
{if(TAILX[e]==ftx&&taily[e]==fty)ic=1;}
if(ic==0&&ftx!=0&&ftx!=cw-1&&fty!=0&&fty!=ch-1&&ftx<cw-1&&fty<ch-1){FX=ftx;fy=fty;}
else goto a;
}
//*************MAIN*******************************************************************************************************
void main()
{//*************************Main Menu*********************************************
ma:
ptr=fopen("s.sc","r");
if(ptr==NULL)
{
h=0;
h_=0;
fclose(ptr);
}
else{
fscanf(ptr,"%d",&h);
h_=h;
fclose(ptr);
}
clr();
strcpy(CAN[5],"+ Welcome To Snake Game");
strcpy(CAN[6],"+ +++++++++v2.0++++++++");
strcpy(CAN[9],"+ Press any Key to Start");
strcpy(CAN[11],"+ Press o for Options");
strcpy(CAN[13],"+ Press x for Exit");
strcpy(CAN[17],"+ $$$$Created By Xidhu$$$$");
strcpy(CAN[19],"+ Copyrighted By 2019 Nixin");
disp();
o=getch();
if(o=='o'){goto op;}
if(o=='x'){goto ex;}
//***************************************************************
int game=1;
food();//food initialising
for(int i=0;i<t*speed;i++)
{
clr();
//*******************Game Over********************************
for(int u=1;u<tails;u++)
{
if(TAILX[u]==x&&taily[u]==y)
game=0;
}
if(game==0)
{goto ex;}
//*************************************************************
//***********************FOOD****************************************************
CAN[fy][FX]='0';//food dropping
if(x==FX&&y==fy)//food picking
{food();tails++;score+=speed*10;}
if(score>h)
h_=score;
//****************Key Press******************************
if(kbhit())
{
c=getch();
if(c==77&&DIR!=2)DIR=1;//right
if(c==75&&DIR!=1)DIR=2;//left
if(c==72&&DIR!=4)DIR=3;//up
if(c==80&&DIR!=3)DIR=4;//down
if(c=='x')goto ex;//exit
}
//****************MOVE*****************************************
if(DIR==1){CAN[y][x]=' ';++x;CAN[y][x]='*';}
if(DIR==2){CAN[y][x]=' ';--x;CAN[y][x]='*';}
if(DIR==3){CAN[y][x]=' ';--y;CAN[y][x]='*';}
if(DIR==4){CAN[y][x]=' ';++y;CAN[y][x]='*';}
//******************Tail Generation****************************
if(i!=0)
{
for(int t=tails;t>0;t--)
{
TAILX[t]=TAILX[t-1];
taily[t]=taily[t-1];
}
TAILX[0]=x;taily[0]=y;
for(int t=0;t<=tails;t++)
{
CAN[taily[t]][TAILX[t]]='*';
}
}else TAILX[0]=x;taily[0]=y;
//**************************************************************
//******************Boundary Conditions*************************
if(x==cw-1&&DIR==1)//right boundary crossing
{CAN[y][x]='+';
CAN[y][1]='*';
x=0;
}
if(x==0&&DIR==2)//left boundary crossing
{CAN[y][x]='+';
CAN[y][80]='*';
x=cw-1;
}
if(y==0&&DIR==3)//up boundary crossing
{CAN[y][x]='+';
CAN[ch-2][x]='*';
y=ch-1;
}
if(y==ch-1&&DIR==4)//down boundary crossing
{CAN[y][x]='+';
CAN[1][x]='*';
y=0;
}
if(x==0&&(DIR==3||DIR==4))x++;//moving through left boundary
if(x==cw-1&&(DIR==3||DIR==4))x--;//moving through right boundary
if(y==0&&(DIR==1||DIR==2))y++;//moving through up boundary
if(y==ch-1&&(DIR==1||DIR==2))y--;//moving through down boundary
//***************************************************************
disp();//display canvas
for(int j=0;j<580000000/speed;j++);//speed adjust
//************************************************************************************************************************
}
//*********************************************Options Menu*****************************
op:
clr();
strcpy(CAN[5],"+ Options");
strcpy(CAN[6],"+ ++++++++");
strcpy(CAN[9],"+ Press s for change Speed");
strcpy(CAN[11],"+ Press d for change");
strcpy(CAN[12],"+ Dimensions of Canvas");
strcpy(CAN[14],"+ Press m for Main Menu");
strcpy(CAN[17],"+ $$$$Created By Xidhu$$$$");
strcpy(CAN[19],"+ Copyrighted By 2019 Nixin");
disp();
l=getch();
if(l=='s')
{q:
clr();
strcpy(CAN[5],"+ Speed Of Snake");
strcpy(CAN[6],"+ +++++++++++++++++++++");
strcpy(CAN[9],"+ Input the Speed(1 to 100 is preferable):");
disp();
scanf("%d",&speed);if(speed<1||speed>100){goto q;};
goto op;
}else if(l=='d')
{w:
clr();
strcpy(CAN[5],"+ Size of Canvas");
strcpy(CAN[6],"+ +++++++++++++++++++++");
strcpy(CAN[9],"+Input the width (30 to 100):");
disp();
scanf("%d",&cw);if(cw<30||cw>100){goto w;};
h:
strcpy(CAN[9],"+Input the height (22 to 46):");
disp();
scanf("%d",&ch);if(ch<22||ch>46){goto h;};
goto op;
}
else if(l=='m')
goto ma;
//******************EXIT****************************************************************
ex:clr();
strcpy(CAN[10],"+ GAME OVER............!");
strcpy(CAN[16],"+ Press Any key to Exit..!");
if(score>h)
{
ptr=fopen("s.sc","w+");
fprintf(ptr,"%d",score);
fclose(ptr);
strcpy(CAN[19],"+ You have New Highscore..!");
}
disp();
printf("Score = %d",score);
getch();
}
|
C
|
/*
* File: faults.c
* Author: C17431
*
* Created on February 20, 2018, 8:52 AM
*/
#include "xc.h"
#include "faults.h"
#include "defines.h"
#define DRV_FLT_LED FAULT_LED_PORT
static LED_FLT_STATE fltLEDState = FAULT_LED_ON;
static uint8_t fltLEDToggleCnt = 0, fltDelayBlinks = 0;
static uint8_t fltLEDBlinkCnt[3] = {0,0,0};
static uint8_t *fltLEDBlinkCntPtr = &fltLEDBlinkCnt[0];
//extern volatile FLT_CODE faultCode;
/*******************************************************************************
* Function: FAULT_CheckMax
* Inputs: Pointer to faultStructure, input fault source, pointer to
* variable that captures fault code, and call back function pointer
* Output: Returns 1 if fault active else 0
* Description: Checks if input fault source is greater than set max threshold,
* sets fltState which captures event and will remove fault once
* input source goes below Hysteresis limit (if set). Function does
* not clear fltState.
*******************************************************************************/
bool FAULT_CheckMax(FLT_STATE *faultInput, int16_t faultSource, uint16_t *fltState)
{
//If fault present return 1, else return 0
if((faultSource >= faultInput->fltThreshold) && (faultInput->faultActive == false))
{
faultInput->fltCounter++;
if(faultInput->fltCounter > faultInput->fltThresholdCnt)
{
if(*fltState == false)
*fltState = faultInput->fltCode;
faultInput->faultActive = 1;
faultInput->fltCounter = 0;
return true;
}
else {
return false;
}
}
else if((faultSource < (faultInput->fltHysLimit)) && (faultInput->faultActive == true))
{
faultInput->fltCounter++;
if(faultInput->fltCounter > faultInput->fltHysCnt)
{
faultInput->fltCounter = 0;
faultInput->faultActive = 0;
return false;
}
else {
return (faultInput->faultActive); //true
}
}
else {
faultInput->fltCounter = 0;
return (faultInput->faultActive);
}
}
/*******************************************************************************
* Function: FAULT_CheckMin
* Inputs: Pointer to faultStructure, input fault source, pointer to
* variable that captures fault code, and call back function pointer
* Output: Returns 1 if fault active else 0
* Description: Checks if input fault source is less than set threshold,
* sets fltState which captures event and will remove fault once
* input source goes above Hysteresis limit (if set). Function does
* not clear fltState.
*******************************************************************************/
bool FAULT_CheckMin(FLT_STATE *faultInput, int16_t faultSource, uint16_t *fltState)
{
//If fault present return 1, else return 0
if((faultSource <= faultInput->fltThreshold) && (faultInput->faultActive == false))
{
faultInput->fltCounter++;
if( faultInput->fltCounter > faultInput->fltThresholdCnt)
{
if(*fltState == false)
*fltState = faultInput->fltCode;
faultInput->faultActive = 1;
faultInput->fltCounter = 0;
return true;
}
else {
return false;
}
}
else if((faultSource > (faultInput->fltHysLimit)) && (faultInput->faultActive == true))
{
faultInput->fltCounter++;
if( faultInput->fltCounter > faultInput->fltHysCnt)
{
faultInput->fltCounter = 0;
faultInput->faultActive = 0;
return false;
}
else {
return (faultInput->faultActive); //true
}
}
else {
faultInput->fltCounter = 0;
return (faultInput->faultActive);
}
}
/*******************************************************************************
* Function: FAULT_SetLEDStates
* Description: This function should be called prior to scheduling the FAULT_BlinkLED
* task to determine the blink counts based on fault code
*******************************************************************************/
void FAULT_SetLEDStates (uint16_t fltState)
{
fltLEDBlinkCnt[0] = (fltState >> 8);
fltLEDBlinkCnt[1] = fltLEDBlinkCnt[0] + ((fltState & 0x00F0) >> 4);
fltLEDBlinkCnt[2] = fltLEDBlinkCnt[1] + (fltState & 0x000F);
}
/*******************************************************************************
* Function: FAULT_ResetLEDStates
* Description: This function should be used after fault was removed and FAULT_BlinkLED
* task is no longer scheduled. This functions clears all states related
* to blinking the fault LED to prepare for next use.
*******************************************************************************/
void FAULT_ResetLEDStates(void)
{
fltLEDBlinkCntPtr = &fltLEDBlinkCnt[0];
fltLEDState = FAULT_LED_ON;
fltLEDToggleCnt = fltDelayBlinks = 0;
}
/*******************************************************************************
* Function: FAULT_BlinkLED
* Description: This function should be scheduled when system enters fault mode,
* LED will blink based on fault code passed to FAULT_SetLEDStates
*******************************************************************************/
void FAULT_BlinkLED(void)
{
if(fltLEDBlinkCnt[0] == 0)
return; // If 0, SetFaultLEDStates wasn't called which means
// missing information to blink LED properly
switch(fltLEDState)
{
case FAULT_LED_ON:
DRV_FLT_LED = true;
fltLEDState = FAULT_LED_OFF;
break;
case FAULT_LED_OFF:
DRV_FLT_LED = false;
if(++fltLEDToggleCnt < *fltLEDBlinkCntPtr)
{
fltLEDState = FAULT_LED_ON;
}
else
{
fltLEDState = DLY_BTWN_BLNKS;
fltLEDBlinkCntPtr++;
}
break;
case DLY_BTWN_BLNKS: // Delay between blink sets
if(++fltDelayBlinks >= (FAULT_BLINKLED_DLYCNT-1))
{
fltLEDState = (fltLEDToggleCnt >= *fltLEDBlinkCntPtr) ? DLY_RESTART : FAULT_LED_ON;
fltDelayBlinks = 0;
}
break;
case DLY_RESTART: // Longer delay after last blink set and before restarting
if(++fltDelayBlinks >= (FAULT_BLINKLED_OFFCNT - 1))
{
// Reset States
fltLEDBlinkCntPtr = &fltLEDBlinkCnt[0];
fltLEDState = FAULT_LED_ON;
fltLEDToggleCnt = fltDelayBlinks = 0;
}
break;
default:
break;
}
}
|
C
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{
struct ListNode *head, *tail;
int carry;
head = tail = (struct ListNode *)malloc(sizeof(struct ListNode));
tail->next = NULL;
while(true)
{
tail->val = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
if(tail->val > 9)
{
tail->val -= 10;
carry = 1;
}
else
{
carry = 0;
}
if(l1)
{
l1 = l1->next;
}
if(l2)
{
l2 = l2->next;
}
if(!l1 && !l2 && !carry)
{
break;
}
tail->next = (struct ListNode *)malloc(sizeof(struct ListNode));
tail = tail->next;
tail->next = NULL;
}
return head;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** connection
** File description:
** connect to the other player
*/
#include "navy.h"
void handler(int sig, siginfo_t *si, void *unused)
{
if (info.p2 == 0)
info.p2 = si->si_pid;
}
int player_1(char **pos)
{
struct sigaction sa;
info.p1 = getpid();
info.p2 = 0;
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = handler;
sigemptyset(&sa.sa_mask);
my_printf("my_pid: %d\nwaiting for enemy connection...\n", info.p1);
while (info.p2 == 0)
sigaction(SIGUSR1, &sa, NULL);
my_printf("\nenemy connected\n\n");
kill(info.p2, SIGUSR1);
if (prepar_in_game(pos) == 0) {
my_printf("I won\n");
return (0);
} else {
my_printf("Enemy won\n");
return (1);
}
}
int player_2(char **pos, char *av)
{
info.p2 = 0;
info.p1 = my_getnbr(av);
struct sigaction sa;
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = handler;
sigemptyset(&sa.sa_mask);
my_printf("my_pid: %d\n", getpid());
kill(info.p1, SIGUSR1);
while (info.p2 == 0)
sigaction(SIGUSR1, &sa, NULL);
info.p2 = getpid();
my_printf("successfully connected\n\n");
if (prepar_in_game(pos) == 0) {
my_printf("I won\n");
return (0);
} else {
my_printf("Enemy won\n");
return (1);
}
}
|
C
|
#include <stdio.h>
int main() {
int i, num, mv = 0, mp = 0;
for(i = 1; i <= 100; i++){
scanf("%d", &num);
if(num>mv){
mv = num;
mp = i;
}
}
printf("%d\n%d\n", mv, mp);
return 0;
}
|
C
|
/*
* KNN.c
* For assignment 4
* Created by Haomin Lin on 9/22/19.
* Copyright © 2019 Haomin Lin. All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "KNN.h"
#include "queue.h"/* include two .h files for functions in this file */
/*
* define function all_distances
*/
void all_distances(int size, int dimension, int r, Queue *distances){
/* declare variables */
int attribute_now = 0;
double distance;
for(int i = 0; i < size; i++){
double od_distance = 0.0;
for(int j = 0; j < dimension + 1; j++){
/* calculate distance for each dimension */
if(j < dimension){
od_distance += (raw_data[r][j] - trainer_data[i][j]) * (raw_data[r][j] - trainer_data[i][j]);
}
/* assign the label to a variable for later use */
else{
attribute_now = trainer_data[i][j];
}
}
/* calculate square root of the distance */
distance = sqrt(od_distance);
/* put the distance and label into the priority queue */
queue_insert(distances, distance, attribute_now);
}
}
/*
* define function count_neighbors
*/
void count_neighbors(int attribute, Queue* distances, int k){
/* initialize and allocate space for array sum */
for(int j = 0; j < attribute; j++){
sum = (int*)malloc(attribute*sizeof(int));
sum[j] = 0;
}
/* define an array for comparison */
int counter[attribute];
for(int j = 0; j < attribute; j++){
counter[j] = j;
}
/* count the first k nearest neighbors in each cluster */
for(int j = 0; j < k; j++){
for(int i = 0; i < attribute; i++){
int follow = counter[i];/* initialize the variable for comparison */
if(distances->next->attr == follow){
int m = distances->next->attr;
sum[m] += 1;/* add one for corresponding cluster */
remove_queue(distances);
/* remove the currently nearest one in the queue so that next time we can still read the currently nearest one directly*/
break;
}
}
}
}
/*
* define function label_node
*/
void label_node(int raw_size, int attribute, int dimension, int r){
/* declare variables */
int d = 0;
int sum_max = 0;
/* find the cluster that has most nearest neighbors*/
for(int s = 0; s < attribute; s++){
if (sum[s] != 0) {
if(sum[s] >= sum_max){
sum_max = sum[s];
d = s;
}
}
}
raw_data[r][dimension] = d;/* give the label to the raw data */
}
void read_raw_data(char* file_name){
/* declare variables */
// int dimension = 0;
// int size = 0;
//
FILE *fread = fopen(file_name, "r");
/* report error if file open fails */
if(fread == NULL){
printf("No data!\n");
exit(0);
}
/*
* read the size and dimension for later use
* the raw data only holds size and dimension
*/
fscanf(fread, "%d %d", &info[1], &info[2]);
/* allocate space for two dimension arrays */
raw_data = (double**)malloc(info[1] * sizeof(double*));
for(int i = 0; i < info[1]; i++){
raw_data[i] = (double*)malloc((info[2] + 1)*sizeof(double));
}
/* put the read data into the array */
for(int i = 0; i < info[1]; i++){
for(int j = 0; j < info[2]; j++){
fscanf(fread, "%lf", &raw_data[i][j]);
}
}
}
/*
* define function read_trainer_data
*/
void read_trainer_data(char* file_name){
/* declare variables */
// int dimension = 0;
// int size = 0;
// int attr = 0;
FILE *fread = fopen(file_name, "r");
if(fread == NULL){
printf("No data!\n");
exit(0);
}
/*
* read the size and dimension for later use
* the raw data holds size, dimension, and number of labels
*/
fscanf(fread, "%d %d %d", &info[0], &info[3], &info[4]);
/* allocate space for two dimension arrays */
trainer_data = (double**)malloc(info[3] * sizeof(double*));
for(int i = 0; i < info[3]; i++){
trainer_data[i] = (double*)malloc((info[4] + 1)*sizeof(double));
}
/* put the read data into the array */
for(int i = 0; i < info[3]; i++){
for(int j = 0; j < info[4] + 1; j++){
fscanf(fread, "%lf", &trainer_data[i][j]);
}
}
}
/*
* define function write_data
*/
void write_data(int raw_size, int dimension, char *outfile){
FILE* fwrite = fopen(outfile, "w");
/* report error if file creation fails */
if (fwrite == NULL){
printf("Failed!");
}
/* write the trained data into output files */
for(int i = 0; i < raw_size; i++){
for(int j = 0; j < dimension; j++){
fprintf(fwrite, "%lf,", raw_data[i][j]);
/* write the coordinates*/
}
fprintf(fwrite, "%d\n", (int)raw_data[i][dimension]);
/* write the dimension */
}
fclose(fwrite);
}
/*
* define function free_arrays
*/
void free_arrays(){
for(int i = 0; i < info[1]; i++){
free(raw_data[i]);
}
free(raw_data);
for(int i = 0; i < info[3]; i++){
free(trainer_data[i]);
}
free(trainer_data);
free(sum);
free(info);
}
|
C
|
#include <stdio.h>
int main(void)
{
int n;
int m=1;
int k=1;
int g;
printf("Enter n:\n");
scanf("%d", &n);
printf("%8d%8d",m,k);
for (int i = 3; i <= n; i++)
{
g=m+k;
m=k;
k=g;
printf("%8d",g);
if(i%5==0){
printf("\n");
}
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int numeros;
//int cantidadNumerosTotales = 0;
//int cantidadPares = 0;
//int sumaPositivos = 0;
//int maximo;
//int minimo;
//int negMax;
//int posMin;
//int entreNumeros;
//int promedio;
char pregunta;
do {
printf("Ingrese un numero:");
scanf("%d",&numeros);
printf("Quiere seguir? Y/N:");
fflush(stdin); //solucion
scanf("%c",&pregunta);
}while (pregunta == 'y');
return 0;
}
|
C
|
liste_occur* creer_case_liste_occur(char c)
{
int i=7;
liste_occur* nouv_case;
nouv_case = malloc(sizeof(liste_occur));
nouv_case->symbole = c;
nouv_case->nmb_occur = 0;
for(i=0; c > 0; i++) //ici on converti le num ascii du caractére c en binaire
{ //par fraction on rempli les cases du tableu
nouv_case->code_bin[i] = c%2; //le num binaire est alors rentré à l'envers dans le tableau
c = c/2; //c'est pourquoi dans la fonction affichage, la boucle for on affiche d'abord les derniéres cases du tableau
}
nouv_case->suivant = NULL;
return(nouv_case);
}//fin creer_case_liste_occur
|
C
|
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define DATA "The sea is calm tonight, the tide is full . . ."
int main(int argc, char *argv[])
{
int sock;
struct sockaddr_in name;
struct hostent *hp, *gethostbyname();
/* Create socket on which to send. */
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
perror("opening datagram socket");
exit(1);
}
/*
* Construct name, with no wildcards, of the socket to
* send to. Gethostbyname() returns a structure including
* the network address of the specified host. The port
* number is taken from the command line.
*/
hp = gethostbyname(argv[1]); ////// NOTE insert: localhost //////
if (hp == 0) {
fprintf(stderr, "%s: unknown host\n", argv[1]);
exit(2);
}
memcpy(&name.sin_addr, hp->h_addr, hp->h_length);
name.sin_family = AF_INET;
name.sin_port = htons(atoi(argv[2])); ////// NOTE insert: PORT retrieved by the server //////
/* Send message. */
if (sendto(sock, DATA, sizeof(DATA), 0,(struct sockaddr *)&name, sizeof(name)) < 0)
perror("sending datagram message");
close(sock);
return 0;
}
|
C
|
#include <stdio.h>
void strncat(char *s1, char *s2, int len)
{
int i = 0; //Counters
int j = 0;
while (i < len)
{
if (*(s1 + j) != '\0')
{
j++;
}
else
{
*(s1 + j) = *(s2 + i); //Add an element of 's2' to the end of 's1'
i++;
j++;
*(s1 + j) = '\0'; //Clearing all the elements of 's1' after 'len' position
}
}
while (*s1 != '\0')
{
printf("%c", *s1);
s1++;
}
}
main()
{
char s1[30] = "Hello ";
char s2[30] = "World";
strncat(s1, s2, 4);
printf("\n");
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* status.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mribouch <mribouch@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/05/01 14:53:45 by mribouch #+# #+# */
/* Updated: 2019/05/23 13:46:41 by mribouch ### ########.fr */
/* */
/* ************************************************************************** */
#include "fractol.h"
t_window *ft_zoom_mandel(t_window *infos, int x, int y)
{
infos->value.dx = infos->value.dx + x - (infos->width / 2);
infos->value.dy = infos->value.dy + y - (infos->height / 2);
infos->value.zmx1 *= infos->value.z;
infos->value.zmx2 *= (1 / infos->value.z);
infos->value.zmy1 *= infos->value.z;
infos->value.zmy2 *= (1 / infos->value.z);
infos->value.dx *= infos->value.z;
infos->value.dy *= infos->value.z;
infos->value.max_iter++;
return (infos);
}
t_window *ft_dezoom_mandel(t_window *infos, int x, int y)
{
infos->value.dx = infos->value.dx - x + (infos->width / 2);
infos->value.dy = infos->value.dy - y + (infos->height / 2);
infos->value.zmx1 /= infos->value.z;
infos->value.zmx2 /= (1 / infos->value.z);
infos->value.zmy1 /= infos->value.z;
infos->value.zmy2 /= (1 / infos->value.z);
infos->value.dx /= infos->value.z;
infos->value.dy /= infos->value.z;
infos->value.max_iter--;
return (infos);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void main() {
int numbCounter = 0;
int lookNum, rows = 0, cols = 0, num;
printf("What number do you want to find? ");
scanf("%d", &lookNum);
printf("Enter the rows of your array: ");
scanf("%d", &rows);
printf("Enter the cols of your array: ");
scanf("%d", &cols);
int intArr[rows][cols];
//Array Setup
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter the value for %d, %d : ", i, j);
scanf("%d", &intArr[i][j]);
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (intArr[i][j] == lookNum) {
numbCounter += 1;
}
}
}
printf("The number of times %d occurs in the integer array you defined is %d : ", lookNum, numbCounter);
}
|
C
|
/***********************************************************
5num.c -- 五数要約
***********************************************************/
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *k1, const void *k2) /* 比較 */
{
if (*((double *)k1) < *((double *)k2)) return -1;
if (*((double *)k1) > *((double *)k2)) return 1;
/* else */ return 0;
}
void fivenum(int n, double x[]) /* 五数要約 */
{
int i, j;
double t;
qsort(x, n, sizeof(double), cmp); /* クイックソート */
for (i = 0; i < 4; i++) {
t = (n - 1.0) * i / 4.0; j = (int)t;
printf("%g ", x[j] + (x[j + 1] - x[j]) * (t - j));
}
printf("%g\n", x[n - 1]);
}
#include "statutil.c"
#define NMAX 5000
int main(void)
{
int n;
double t;
static double x[NMAX];
n = 0;
while (! readerror(t = getnum(stdin)))
if (missing(t)) continue;
else if (n >= NMAX) error("多すぎます");
else x[n++] = t;
fivenum(n, x);
return 0;
}
|
C
|
#include<stdio.h>
int main(){
int a[10],b[10],i;
for(i=0;i<10;i++){
printf("a[%d]=%d\n",i,i+1);}
for(i=0;i<10;i++){
b[i]=i*i;
printf("b[%d]=%d\n",i,b[i]);}}
|
C
|
/*程序功能:
* 使用framebuffer向屏幕上面绘制颜色块。
* 具体为:
* 在屏幕的指定区域,绘制红,绿,蓝三种方形颜色块。
*目前的问题:
绘制颜色(ok).
如何正确的映射内存?
*
* 一个例子输出:
* # ./fbColor
* depth(bits per pixel) = 16
* xres= 1024,yres = 600,xres_virtual = 1024,yres_virtual = 600
* xoffset = 0, yoffset = 0, grayscale = 0
* height = 0 , width = 0 ,activate = 0
* pixclock = 14800, l_margin = 96, r_margin = 48, u_margin = 16, d_margin = 3
* hsync_len = 32, vsync_len = 6 , sync = 3, vmode = 0
* smemlen = 1228800
* fix_line(in byte) = 2048
* !!!!!fb mem:40000000,mmstart:0
* fb_fix.smem_start:e8000000
* 0,e8000000
* */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
//#include <asm/page.h>
#include <linux/fb.h>
#define FB_DEV "/dev/fb0"
#define PAGE_MASK 0XFFFFF000//why?
#define TRUE 1
#define FALSE 2
#define MY_DEBUG 1
//color geometry
#define COLOR_WIDTH 80
#define R_START 0
#define G_START ((R_START)+(COLOR_WIDTH))
#define B_START ((G_START)+(COLOR_WIDTH))
//red offset is 11
//green offset is 5
//blue offset is 0
#define PIX_BIT 16
#define RED_OFF 11
#define RED_LEN 5
#define GREEN_OFF 5
#define GREEN_LEN 6
#define BLUE_OFF 0
#define BLUE_LEN 5
#define RED (((1<<RED_LEN)-1) << (RED_OFF))
#define GREEN (((1<<GREEN_LEN)-1) << (GREEN_OFF))
#define BLUE (((1<<BLUE_LEN)-1) << (BLUE_OFF))
//假设一个像素16bit,rgb是565的。
//正常来说:红绿蓝
//0xf800,0x07e0,0x0011
//这里:
//red offset:11,length:5
//green offset:5,length:6
//blue offset:0,length:5
static struct fb_fix_screeninfo fb_fix;
static struct fb_var_screeninfo fb_var;
static unsigned long fb_mem_offset;
static unsigned long fb_mem_offset2;
static void *fb_mem;
static int fb;
void draw_dot(uint32_t x, uint32_t y)
{
if (-1L == (long)fb_mem)
{
printf("mmap error! mem:%x offset:%x\n", fb_mem, fb_mem_offset);
return;
}
//关于行和列,
//由于内存线性排列,第y行的第一个像素是y*fb_fix.line_length
//由于像素是fb_var.bits_per_pixel>>3字节,所以第x列为...+x*(fb_var.bits_per_pixel>>3)
unsigned int offset;
offset = y*fb_fix.line_length+x*(fb_var.bits_per_pixel>>3);
//offset = y*fb_fix.line_length+2*x;
uint16_t value = 0;
if(x < G_START)
{
value = RED;
}
else if(x< B_START)
{
value = GREEN;
}
else
{
value = BLUE;
}
uint16_t *pv = &value;
memcpy((void*)((unsigned long)fb_mem + offset), pv, 2);
//wrong
//memset((void*)((unsigned long)fb_mem + offset), RED, fb_var.bits_per_pixel>>3);
//memset((void*)((unsigned long)fb_mem + offset), GREEN, fb_var.bits_per_pixel>>3);
//memset((void*)((unsigned long)fb_mem + offset), BLUE, fb_var.bits_per_pixel>>3);
//wrong but don't know why?
//memset((void*)((unsigned long)fb_mem + offset), RED>>2, 1);
//memset((void*)((unsigned long)fb_mem + offset+1), RED, 1);
}
int main(int argc, char *argv[])
{
printf("unsigned short len:%d\n",sizeof(unsigned short));
printf("uint16_t len:%d\n",sizeof(uint16_t));
//////1)intialize frame buffer
memset(&fb_fix, 0, sizeof(struct fb_fix_screeninfo));
memset(&fb_var, 0, sizeof(struct fb_var_screeninfo));
memset(&fb_var, 0, sizeof(struct fb_var_screeninfo));
fb_mem_offset = 0;
fb_mem = 0;
//open frame buffer file
int fb = open(FB_DEV, O_RDWR);
if(fb < 0)
{
printf("Error opening %s,Check kernel config\n",FB_DEV);
return FALSE;
}
//////2)get information of frame buffer
if(-1 == ioctl(fb,FBIOGET_VSCREENINFO,&(fb_var)))
{
printf("Error:ioctl FBIOGET_VSCREENINFO\n");
return FALSE;
}
if (-1 == ioctl(fb,FBIOGET_FSCREENINFO,&(fb_fix)))
{
printf("Error:ioctl FBIOGET_FSCREENINFO\n");
return FALSE;
}
//////3)map physics address to virtual address
//fb_fix.smem_start:Start of frame buffer mem
fb_mem_offset = (unsigned long)(fb_fix.smem_start) & (~PAGE_MASK);//why?
//unsigned long fb_realMapLen = fb_fix.smem_len + fb_mem_offset;
fb_mem_offset2= (unsigned long)(fb_fix.smem_start)&(~(sysconf(_SC_PAGE_SIZE) - 1));
size_t fb_realMapLen = fb_fix.smem_len+fb_fix.smem_start - fb_mem_offset2;
fb_mem = mmap(NULL, fb_realMapLen,
PROT_READ | PROT_WRITE, MAP_SHARED, fb, 0);
if (-1L == (long)fb_mem)
{
printf("mmap error! mem:%ld offset:%x\n",fb_mem,
fb_mem_offset);
return FALSE;
}
///////4)print info
//每个像素的字节数目
printf("depth(bits per pixel) = %d\n",fb_var.bits_per_pixel);
//(两种分辨率)visible resolution,virtual resolution
printf("xres= %d,yres = %d,xres_virtual = %d,yres_virtual = %d\n",
fb_var.xres,fb_var.yres,fb_var.xres_virtual,fb_var.yres_virtual);
//(两种分辨率之间的映射偏移量)offset from virtual to visible resolution
printf(" xoffset = %d, yoffset = %d, grayscale = %d\n",
fb_var.xoffset,fb_var.yoffset,fb_var.grayscale);
//framebuffer的内存大小Length of frame buffer mem
printf("smemlen = %d\n",fb_fix.smem_len);
//每"行"的字节数目.length of a line in bytes
printf("fix_line(in byte) = %d\n",fb_fix.line_length);
//height,width of picture in mm
printf(" height = %d , width = %d ,activate = %d \n",
fb_var.height,fb_var.width,fb_var.activate);
//pixel clock in ps (pico seconds)
printf(" pixclock = %d, l_margin = %d, r_margin = %d, u_margin = %d, d_margin = %d\n",
fb_var.pixclock,fb_var.left_margin,fb_var.right_margin,
fb_var.upper_margin,fb_var.lower_margin);
//length of horizontal,vertical sync
printf(" hsync_len = %d, vsync_len = %d , sync = %d, vmode = %d\n",
fb_var.hsync_len,fb_var.vsync_len,fb_var.sync,fb_var.vmode);
#if MY_DEBUG == 1
//////messy test
//my test
printf("!!!!!fb mem:%x,mmstart:%x\n",fb_mem,fb_fix.mmio_start);
//my test for offset
printf("fb_fix.smem_start:%x\n",fb_fix.smem_start);
printf("%x,%x\n",fb_mem_offset,fb_mem_offset2);
printf("red offset:%d\n",fb_var.red.offset);
printf("red len:%d\n",fb_var.red.length);
printf("green offset:%d\n",fb_var.green.offset);
printf("green len:%d\n",fb_var.green.length);
printf("blue offset:%d\n",fb_var.blue.offset);
printf("blue len:%d\n",fb_var.blue.length);
//my test for color
printf("red:%x\n",RED);
printf("green:%x\n",GREEN);
printf("blue:%x\n",BLUE);
#endif
//////5)draw color
int i,j;
for(i=R_START; i<R_START+COLOR_WIDTH; ++i)
{
for(j = 0;j<COLOR_WIDTH;++j)
{
draw_dot(i,j);//red,at (i,j)
}
}
for(i=G_START; i<G_START+COLOR_WIDTH; ++i)
{
for(j = 0;j<COLOR_WIDTH;++j)
{
draw_dot(i,j);//green,at (i,j)
}
}
for(i=B_START; i<B_START+COLOR_WIDTH; ++i)
{
for(j = 0;j<COLOR_WIDTH;++j)
{
draw_dot(i,j);//blue,at (i,j)
}
}
close(fb);
fb=-1;
munmap(fb_mem,fb_realMapLen);
return 0;
}
|
C
|
#include<stdio.h>
#include<pthread.h>
void *imprime_seno (void *x_seno)
{
int *x_seno = (int*)x_seno;
printf ("Valor do seno eh: %.2f",*x_seno);
pthread_exit(NULL);
}
int main ()
{
pthread_t thread_seno;
if (pthread_create(&thread_seno, NULL, incrementa_x, &x))
printf ("Erro na criacao do thread_seno");
if (pthread_seno_join(thread_seno, NULL))
printf ("Erro na juncao do thread");
return 0;
}
|
C
|
/*
* queuetest.c
*
* Created on: Feb 22, 2015
* Author: Tri
*/
#include <stdlib.h>
#include <stdio.h>
#include "queue.h"
typedef struct {
int x;
double y;
} Foo; // Just some arbitrary struct
int main() {
const int max_entries = MAX_ENTRIES;
Foo* new_foo1;
Foo* new_foo2;
Foo* new_foo3;
Foo* new_foo4;
Foo* new_foo5;
Foo* new_foo6;
Foo* new_foo7;
Foo* new_foo8;
Foo* new_foo9;
Foo* returned_foo;
int queueoverflow;
Queue *new_queue = create_queue(max_entries);
//--------------------------------------------------------------------------------------
// Allocate a Foo and push it onto the queue.
new_foo1 = (Foo *) malloc(sizeof(Foo));
new_foo1->x = 6;
new_foo1->y = 14.79;
printf("Enqueuing: x = %d, y = %.3f\n", new_foo1->x, new_foo1->y);
queueoverflow = enqueue(new_queue, (void *) new_foo1);
printf("queue overflow: %d\n", queueoverflow);
printf(
"//--------------------------------------------------------------------------------------\n");
//--------------------------------------------------------------------------------------
new_foo2 = (Foo *) malloc(sizeof(Foo));
new_foo2->x = 10;
new_foo2->y = 25.34;
printf("Enqueuing: x = %d, y = %.3f\n", new_foo2->x, new_foo2->y);
queueoverflow = enqueue(new_queue, (void *) new_foo2);
printf("queue overflow: %d\n", queueoverflow);
printf(
"//--------------------------------------------------------------------------------------\n");
//--------------------------------------------------------------------------------------
// Allocate a Foo and push it onto the queue.
new_foo3 = (Foo *) malloc(sizeof(Foo));
new_foo3->x = 98;
new_foo3->y = 54.39;
printf("Enqueuing: x = %d, y = %.3f\n", new_foo3->x, new_foo3->y);
queueoverflow = enqueue(new_queue, (void *) new_foo3);
printf("queue overflow: %d\n", queueoverflow);
printf(
"//--------------------------------------------------------------------------------------\n");
//--------------------------------------------------------------------------------------
// Allocate a Foo and push it onto the queue.
new_foo4 = (Foo *) malloc(sizeof(Foo));
new_foo4->x = 52;
new_foo4->y = 101.45;
printf("Enqueuing: x = %d, y = %.3f\n", new_foo4->x, new_foo4->y);
queueoverflow = enqueue(new_queue, (void *) new_foo4);
printf("queue overflow: %d\n", queueoverflow);
printf(
"//--------------------------------------------------------------------------------------\n");
//--------------------------------------------------------------------------------------
// Allocate a Foo and push it onto the queue.
new_foo5 = (Foo *) malloc(sizeof(Foo));
new_foo5->x = 42;
new_foo5->y = 11.355;
printf("Enqueuing: x = %d, y = %.3f\n", new_foo5->x, new_foo5->y);
queueoverflow = enqueue(new_queue, (void *) new_foo5);
printf("queue overflow: %d\n", queueoverflow);
printf(
"//--------------------------------------------------------------------------------------\n");
//--------------------------------------------------------------------------------------
// Allocate a Foo and push it onto the queue.
new_foo6 = (Foo *) malloc(sizeof(Foo));
new_foo6->x = 92;
new_foo6->y = 18.5;
printf("Enqueuing: x = %d, y = %.3f\n", new_foo6->x, new_foo6->y);
queueoverflow = enqueue(new_queue, (void *) new_foo6);
printf("queue overflow: %d\n", queueoverflow);
printf(
"//--------------------------------------------------------------------------------------\n");
//--------------------------------------------------------------------------------------
// Allocate a Foo and push it onto the queue.
new_foo7 = (Foo *) malloc(sizeof(Foo));
new_foo7->x = 32;
new_foo7->y = 68.5;
printf("Enqueuing: x = %d, y = %.3f\n", new_foo7->x, new_foo7->y);
queueoverflow = enqueue(new_queue, (void *) new_foo7);
printf("queue overflow: %d\n", queueoverflow);
printf(
"//--------------------------------------------------------------------------------------\n");
returned_foo = peek(new_queue);
if (returned_foo != '\0') {
printf("Peek: x = %d, y = %.3f\n", returned_foo->x, returned_foo->y);
}
printf("**********************\n");
returned_foo = dequeue(new_queue);
returned_foo = peek(new_queue);
printf("Peek: x = %d, y = %.3f\n", returned_foo->x, returned_foo->y);
printf("**********************\n");
returned_foo = dequeue(new_queue);
returned_foo = peek(new_queue);
printf("Peek: x = %d, y = %.3f\n", returned_foo->x, returned_foo->y);
printf("**********************\n");
returned_foo = dequeue(new_queue);
returned_foo = peek(new_queue);
printf("Peek: x = %d, y = %.3f\n", returned_foo->x, returned_foo->y);
printf("**********************\n");
returned_foo = dequeue(new_queue);
returned_foo = peek(new_queue);
printf("Peek: x = %d, y = %.3f\n", returned_foo->x, returned_foo->y);
printf("**********************\n");
returned_foo = dequeue(new_queue);
returned_foo = peek(new_queue);
printf("Peek: x = %d, y = %.3f\n", returned_foo->x, returned_foo->y);
printf("**********************\n");
returned_foo = dequeue(new_queue);
returned_foo = peek(new_queue);
if (returned_foo != '\0') {
printf("Peek: x = %d, y = %.3f\n", returned_foo->x, returned_foo->y);
}
printf("**********************\n");
//--------------------------------------------------------------------------------------
// Allocate a Foo and push it onto the queue.
new_foo8 = (Foo *) malloc(sizeof(Foo));
new_foo8->x = 35;
new_foo8->y = 70.5;
printf("Enqueuing: x = %d, y = %.3f\n", new_foo8->x, new_foo8->y);
queueoverflow = enqueue(new_queue, (void *) new_foo8);
printf("queue overflow: %d\n", queueoverflow);
printf(
"//--------------------------------------------------------------------------------------\n");
returned_foo = peek(new_queue);
if (returned_foo != '\0') {
printf("Peek: x = %d, y = %.3f\n", returned_foo->x, returned_foo->y);
}
printf("**********************\n");
//--------------------------------------------------------------------------------------
// Allocate a Foo and push it onto the queue.
new_foo9 = (Foo *) malloc(sizeof(Foo));
new_foo9->x = 86;
new_foo9->y = 77.35;
printf("Enqueuing: x = %d, y = %.3f\n", new_foo9->x, new_foo9->y);
queueoverflow = enqueue(new_queue, (void *) new_foo9);
printf("queue overflow: %d\n", queueoverflow);
printf(
"//--------------------------------------------------------------------------------------\n");
returned_foo = dequeue(new_queue);
returned_foo = peek(new_queue);
if (returned_foo != '\0') {
printf("Peek: x = %d, y = %.3f\n", returned_foo->x, returned_foo->y);
}
printf("**********************\n");
return 0;
}
|
C
|
/*
* Author: Manuel Ángel Suárez Álvarez
* E-mail Manuel_Angel99@outlook.com
* Created: 2016-08-13 20:03:31
*
* File: gdt.c
* Description: Implements the necesary functions for setting up the GDT
*/
#include <stdint.h>
#include <stddef.h>
#include <arch/x86/gdt.h>
// Setup a descriptor in the Global Descriptor Table
void gdt_set_gate(size_t num, uint32_t base, uint32_t limit, uint8_t access, uint8_t gran)
{
// Setup the descriptor base address
gdt[num].base_low = (base & 0xFFFF);
gdt[num].base_middle = (base >> 16) & 0xFF;
gdt[num].base_high = (base >> 24) & 0xFF;
// Setup the descriptor limits
gdt[num].limit_low = (limit & 0xFFFF);
gdt[num].granularity = ((limit >> 16) & 0x0F);
// Finally, set up the granularity and access flags
gdt[num].granularity |= (gran & 0xF0);
gdt[num].access = access;
}
void setup_gdt(void)
{
//NULL segment, it can be used to hold the GDT address
gdt_set_gate(0, 0, 0, 0, 0);
//Kernel mode code
gdt_set_gate(1, 0, 0xFFFFFFFF, 0x9A, 0xCF);
//Kerel mode data
gdt_set_gate(2, 0, 0xFFFFFFFF, 0x92, 0xCF);
//User mode code
gdt_set_gate(3, 0, 0xFFFFFFFF, 0xFA, 0xCF);
//User mode data
gdt_set_gate(4, 0, 0xFFFFFFFF, 0xF2, 0xCF);
gdt_pointer.base = sizeof(GlobalDescriptorTableEntry_t) * 5 - 1; // Subsract 1 because sizeof doesn't start from 0
gdt_pointer.address = (uint32_t)&gdt;
// Remove the old GDT and install the new one
load_gdt();
}
|
C
|
/* Code to generate CNF from Boolean & separation logic expressions */
/* General */
#define HAVE_LONGLONG 1
#if HAVE_LONGLONG
/* Might need to disable this when compiler doesn't support long long's */
typedef long long int llong;
typedef unsigned long long int ullong;
#else
typedef long int llong;
typedef unsigned long int ullong;
#endif
char *strsave(char *s);
/* Where should error output be directed */
#define ERRFILE stdout
/************** Boolean ***************************/
/* Two fundamental operator types: AND and XOR.
Special types: PI for primary input,
IPI for PI originating as bit in integer word,
BUF for single argument,
and ZERO for Boolean zero
*/
typedef enum {OP_ZERO, OP_AND, OP_XOR, OP_PI, OP_IPI, OP_BUF} op_t;
typedef struct OELE op_ele, *op_ptr;
struct OELE {
hash_ele hash_stuff; /* Used by unique table */
op_t op;
int nargs;
op_ptr *args; /* Pointers to children */
char *invert_args; /* For each child, 1 if invert, 0 otherwise */
int output_id; /* Assigned when generating CNF */
int creation_id; /* Generated during creation. Used for hashing */
int pass; /* Used to guide depth-first traversals */
int unique; /* Is this a canonical operation? */
char *name; /* For primary inputs */
};
/* Display Boolean value as 0, 1, or X (for non-constant value) */
char op_char(op_ptr arg);
/* Create a new PI */
op_ptr new_pi(char *name);
/* Print expression */
void expr_display(FILE *fp, op_ptr arg, int invert);
op_ptr zero();
op_ptr one();
/* Boolean operations */
op_ptr and_op(op_ptr arg1, op_ptr arg2);
op_ptr or_op(op_ptr arg1, op_ptr arg2);
op_ptr xor_op(op_ptr arg1, op_ptr arg2);
op_ptr not_op(op_ptr arg);
op_ptr ite_op(op_ptr iarg, op_ptr targ, op_ptr earg);
/************** Integer / float *******************************/
/*** Declare word sizes ***/
/* Maximum word size for interpreter (bits) [Must be multiple of CSIZE and >= 32]*/
#ifndef WSIZE
#define WSIZE 64
#endif
#define CSIZE 8 /* Size of byte */
#define FLOAT_SIZE 32 /* Size of float */
typedef enum { DATA_SIGNED, DATA_UNSIGNED, DATA_FLOAT } data_t;
/* Represent integers as array of Booleans */
typedef struct {
op_ptr bits[WSIZE];
} bvec_ele, *bvec_ptr;
/* Free a bvec */
void free_vec(bvec_ptr v);
/* Print a bvec */
void bvec_display(FILE *fp, bvec_ptr v);
/* Quick 0/1/X display of bvec */
void bvec_char(char *dest, bvec_ptr v, int width);
/* Expand from 1 bit to word size */
bvec_ptr bool2int(op_ptr arg);
/* Create set of primary input variables */
bvec_ptr int_pi(char *name, int wsize, int isunsigned);
bvec_ptr int_const(llong val);
bvec_ptr uint_const(ullong val);
bvec_ptr float_const(float fval);
bvec_ptr int_add(bvec_ptr v1, bvec_ptr v2);
bvec_ptr int_negate(bvec_ptr v); /* Arithmetic negation */
bvec_ptr int_not(bvec_ptr v); /* Bitwise complement */
bvec_ptr int_and(bvec_ptr v1, bvec_ptr v2);
bvec_ptr int_or(bvec_ptr v1, bvec_ptr v2);
bvec_ptr int_xor(bvec_ptr v1, bvec_ptr v2);
bvec_ptr int_mult(bvec_ptr v1, bvec_ptr v2);
bvec_ptr int_div(bvec_ptr v1, bvec_ptr v2, int isunsigned);
bvec_ptr int_rem(bvec_ptr v1, bvec_ptr v2, int isunsigned);
bvec_ptr int_shiftleft(bvec_ptr v1, bvec_ptr v2, int wsize);
bvec_ptr int_shiftrightarith(bvec_ptr v1, bvec_ptr v2, int wsize);
bvec_ptr int_shiftrightlogical(bvec_ptr v1, bvec_ptr v2, int wsize);
bvec_ptr int_mux(op_ptr cntl, bvec_ptr v1, bvec_ptr v2);
bvec_ptr change_type(bvec_ptr val, int old_wsize, data_t old_dtype, int new_wsize, data_t new_dtype);
/* Set high order bits of word to either sign bit or zero */
bvec_ptr mask_size(bvec_ptr val, int wsize, int isunsigned);
/* Create unsigned byte by little endian order */
bvec_ptr extract_byte(bvec_ptr val, int offset);
/* Replace specified byte */
bvec_ptr replace_byte(bvec_ptr word, bvec_ptr byte, int offset);
/* Floating point operations */
bvec_ptr float_negate(bvec_ptr v);
bvec_ptr float_mult(bvec_ptr v1, bvec_ptr v2);
bvec_ptr float_fix_nan(bvec_ptr v);
bvec_ptr float_isnan(bvec_ptr v);
/* Predicates */
op_ptr int_eq(bvec_ptr v1, bvec_ptr v2);
op_ptr int_lt(bvec_ptr v1, bvec_ptr v2);
op_ptr int_le(bvec_ptr v1, bvec_ptr v2);
op_ptr int_ult(bvec_ptr v1, bvec_ptr v2);
op_ptr int_ule(bvec_ptr v1, bvec_ptr v2);
op_ptr int_isnonzero(bvec_ptr v);
op_ptr float_eq(bvec_ptr v1, bvec_ptr v2);
op_ptr float_lt(bvec_ptr v1, bvec_ptr v2);
/************* I/O **************************************/
void show_const(FILE *fp, bvec_ptr v, int wsize, int isunsigned);
void gen_cnf(FILE *fp, FILE *info_fp, op_ptr arg);
/* Determine if formula satisfiable (using BDDs).
If so, optionally print satisfying solution to file.
Return 1 iff satisfiable
*/
int gen_solve(FILE *fp, op_ptr arg);
/* Read straightline program from file.
Formats:
# ANYTHING Comment
ID b [NAME] Boolean variable
ID i MAXVAL [NAME] Integer variable
ID c VAL Integer constant
ID ~ BARG Complement
qa BARG Universal quantifier
qe BARG Existential quantifier
ID & BARG1 ... BARGN And
ID | BARG1 ... BARGN Or
ID ^ BARG1 ... BARGN Xor
ID = IARG1 IARG2 Equality
ID < IARG1 IARG2 Less than
ID <= IARG1 IARG2 Less than or equal to
Where:
ID is sequentially numbered identifier (starting from 1)
BARG is either ID or -ID, where ID is the ID of a Boolean value
IARG is the ID of an integer value
*/
op_ptr straightline_read(FILE *fp);
|
C
|
#include <stdio.h>
int
main()
{
int i,j,rows;
/* printf(" enter the rows ");
scanf("%d\n", &rows );*/
printf("enter the no u want");
scanf("%d\n", &rows);
for(i = 0; i < rows; i++){
for (j = 0;j <= i;j++){
printf( "*" );
}
printf( "\n" );
}
return 0;
}
|
C
|
/*
* File: main.c
* Author: ZeroSama
*
* Created on 26 de Junho de 2014, 11:37
*/
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
int main(int argc, char** argv) {
// 4 - Faça um programa que converta uma temperatura de Celsius para Fahrenheit e vice-versa.
// Utilize as fórmulas abaixo:
// Fahrenheit para Celsius: C = (F – 32) / 1,8
// Celsius para Fahrenheit: F = C * 1,8 + 32
int opcao,numero;
printf("Escolha \n");
printf("1 - Fahrenheit para Celsius;\n");
printf("2 - Celsius para Fahrenheit;\n");
scanf("%d",&opcao);
if (opcao == 1 || opcao == 2){
printf("Entre com a temperadura: ");
scanf("%d",&numero);
if(opcao == 1){
printf("%d = (%d -32) /1,8\n",((numero-32)/1,8),numero);
}
else{
printf("%d = %d * 1,8 + 32\n",(numero*1,8+32),numero);
}
}
else{
printf("opcao não encontrado\n");
}
return (EXIT_SUCCESS);
}
|
C
|
/****************************************************************
File: Stack.h
----------------
This is an interface for a stack ADT. The ADT supports routines
for stack creation, deletion, pushing (inserting), popping and
printing in an interpreted way.
****************************************************************/
#ifndef UTILS_STACK
#define UTILS_STACK
/****************************************************************
Type: Stack
--------------
Declaration of a Stack object takes the form,
Stack st;
*/
typedef struct stack *Stack;
/****************************************************************
Function: createStack()
-----------------------
Creates a new stack and returns it.
Example usages:
Stack q1;
q1 = Stack();
Stack q2 = createStack();
*/
Stack createStack(void);
/****************************************************************
Function: isEmpty(Stack)
---------------------------
Returns true if the argument is an empty stack, false otherwise.
Example usage, given the Stack variable st:
if (!isEmpty(st))
printf("This is not an empty stack.\n");
*/
int isEmpty (Stack st);
/****************************************************************
Function: deleteStack(stack)
-------------------------------
Destroys the stack given as an argument. Always call this after
a Stack st is no longer needed, as:
deleteStack(st);
*/
void deleteStack(Stack st);
/****************************************************************
Function: push(stack, int)
--------------------------------
pushes the second argument to the stack. The data is put on the
top of the stack.
Example usage, given Stack variable st:
push(st, 2);
pushed the number 2 on top of the stack.
*/
void push(Stack st, int data);
/****************************************************************
Function: pop(Stack)
---------------------------
Removes the item on the top of the stack and returns its value.
Example usage, given Stack variable st and int variable data:
data = pop(st);
If 2 were at the top of the stack, data now contains the
value 2.
WARNING: pop will return 0 if an attempt is made to pop
from the empty stack. It is the client's responsibility to
determine if the stack is empty before calling pop.
*/
int pop(Stack st);
/****************************************************************
Function: printStack(Stack)
------------------------------
Prints the current stack, if not empty, each element is separated
by a space
Example of usage, given Stack variable st:
push(st, 1);
push(st, 2);
push(st, 3);
printStack(st);
---> "3 2 1"
*/
void printStack (Stack st);
#endif
|
C
|
#include "pipex.h"
#include <string.h>
#include <signal.h>
void ft_exit(char *str)
{
write(2, str, ft_strlen(str));
write(2, "\n", 1);
exit(0);
}
void freematrix(char **matrix)
{
int i;
i = -1;
while ((matrix)[++i])
free((matrix)[i]);
free(matrix);
}
void ft_execute(char *path, char **cmd)
{
char **tab;
char *tmp1;
char *tmp2;
int i;
i = 0;
tab = ft_split(path, ':');
while (tab[i])
{
if (cmd[0][0] != '/')
{
tmp1 = ft_strjoin(tab[i], "/");
tmp2 = ft_strjoin(tmp1, cmd[0]);
}
execve(tmp2, cmd, environ);
free(tmp1);
free(tmp2);
++i;
}
freematrix(tab);
ft_exit("Error: Invalid command");
}
char *get_env(char *key, char **env)
{
int i;
size_t key_len;
i = 0;
key = ft_strjoin(key, "=");
key_len = ft_strlen(key);
while (env[i] != '\0')
{
if (ft_strncmp(env[i], key, key_len) == 0)
{
free(key);
return (env[i] + key_len);
}
i++;
}
free(key);
return (NULL);
}
void childpipe(int fd[2], int outfile, char *cmd2, char *path)
{
char **args;
close(fd[1]);
args = ft_split(cmd2, ' ');
if(args[0] == NULL)
ft_exit("Error: Empty command");
if (dup2(fd[0], 0) == -1)
exit(0);
if (dup2(outfile, 1) == -1)
exit(0);
if (args[0][0] == '/') {
if (execve(args[0], args, environ))
ft_exit("Error: Invalid command");
}
else
ft_execute(path, args);
freematrix(args);
close(outfile);
close(fd[0]);
}
void parentfpipe(int fd[2], int infile, char *cmd1, char *path)
{
char **args;
close(fd[0]);
args = ft_split(cmd1, ' ');
if(args[0] == NULL)
ft_exit("Error: Empty command");
if (dup2(infile, 0) == -1)
ft_exit("Failed to connect infile with STDIN");
if (dup2(fd[1], 1) == -1)
ft_exit("Failed to connect STDOUT with pipe's WRITE END");
if (args[0][0] == '/')
{
if (execve(args[0], args, environ) == -1)
ft_exit("Error: Invalid command");
}
else
ft_execute(path, args);
freematrix(args);
close(infile);
close(fd[1]);
wait(NULL);
}
void pipex(char **argv, char *path)
{
pid_t getpid; // fork()
int infile; //for reading
int outfile; //for writing
int fd[2]; //pipe argument
infile = open(argv[1], O_RDONLY);
if (infile == -1)
ft_exit("Failed to open infile");
outfile = open(argv[4], O_WRONLY);
if (outfile == -1)
ft_exit("Failed to open outfile");
if (pipe(fd) == -1)
ft_exit("Failed to pipe");
getpid = fork();
if (getpid == -1)
ft_exit("Failed to fork");
else if (getpid == 0) //child process
childpipe(fd, outfile, argv[3], path);
else //parent process
parentfpipe(fd, infile, argv[2], path);
}
|
C
|
/*
** algorithm.c for malloc in /home/gregoi_j/rendu/PSU_2014_malloc
**
** Made by Jean-Baptiste Grégoire
** Login <gregoi_j@epitech.net>
**
** Started on Sun Feb 1 16:12:39 2015 Jean-Baptiste Grégoire
** Last update Fri Feb 13 00:30:20 2015 Jean-Baptiste Grégoire
*/
#include "malloc.h"
t_header *first_fit(t_header **used_list, t_header **free_list,
size_t size)
{
t_header *it;
t_header *new;
it = *free_list;
while (it)
{
if (it->size == size + sizeof(t_header))
{
list__delete(free_list, it);
list__add(used_list, it);
return (it);
}
else if (it->size > size + sizeof(t_header))
{
new = (void *)((size_t)(it->addr) +
it->size - size - sizeof(t_header));
new->size = size;
new->addr = (void *)((size_t)(new) + sizeof(t_header));
it->size = it->size - size - sizeof(t_header);
list__add(used_list, new);
return (new);
}
it = it->next;
}
return (NULL);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <signal.h>
#include "SharedStructure.h"
void sig_handler(int);
int CheckTermination(int term);
int main () {
signal(SIGINT, sig_handler); //Register the signal handler
int shmId;
int readerIndex = 0;
int position = 0;
char *shmPtr;
//Get the shared memory pointer to the file
key_t memKey = ftok("test", 1);
if ((shmId = shmget(memKey, FOO, S_IRUSR)) < 0) {
perror ("I can't find...\n");
exit(1);
}
if ((shmPtr = shmat(shmId, 0, 0)) == (void*) -1) {
perror ("Can't attach\n");
exit(1);
}
//Usable pointer to the file
struct messageStruct *sharedFile = (struct messageStruct *) shmPtr;
char c;
int hasReaderSpot = 0;
while(!hasReaderSpot) {
for (int i = 0; i < NUM_READERS && !hasReaderSpot; i++) {
if (sharedFile->readers[i] == 0) {
readerIndex = i;
sharedFile->readers[i] = i + 1; //tell other readers that this space is being used
hasReaderSpot = 1;
}
}
//printf("Could not get a reader spot\n");
}
sharedFile = (struct messageStruct *) shmPtr;
while(1) {
if (sharedFile->readers[readerIndex] == 0){
printf("Note: %s\n", sharedFile->message);
sharedFile->readers[readerIndex] = 1; //set the reader display status
}
if(CheckTermination(0)) break;
sharedFile = (struct messageStruct *) shmPtr;
}
if (shmdt (shmPtr) < 0) {
perror ("Can't deattach\n");
exit(1);
}
return 0;
}
/**
* To assist with exiting gracefully by marking when it is time to exit by the signal of ^C
* @param term 0 to check, 1 to set
* @return 1 to terminate
*/
int CheckTermination(int term) {
static int terminate = 0;
if(term != 0) {
terminate = 1;
}
return terminate;
}
/* Signal Handler for the Parent Process */
void sig_handler(int signum) {
CheckTermination(1);
return;
}
|
C
|
#include <stdio.h>
#include <windows.h>
#include <math.h >
#pragma warning (disable : 4996)
int FindNumber(int arr[] , int len){
int number = 0;
for (int i = 0; i < len; i++){
// 相同的数异或为0, 最终只剩下唯一单独的数
number ^= arr[i];
}
return number;
}
int main(){
int arr[] = {2,2,4,1,9,4,9,8,1};
int len = sizeof(arr) / sizeof(arr[0]);
int number = FindNumber( arr, len);
printf(" %d ", number);
system("pause");
return 0;
}
|
C
|
#include "holberton.h"
/**
* rev_string - reverses a string
* @s: pointer to stringg
*/
void rev_string(char *s)
{
int i, j;
char k;
i = 0;
j = 0;
while (*s != '\0')
{
j++;
s++;
}
if (j > 0 && *s == '\0')
{
s -= j;
j--;
}
while (i < j)
{
k = *(s + i);
*(s + i) = *(s + j);
*(s + j) = k;
++i;
--j;
}
}
|
C
|
//This will receive a string from tcl and process it as an RPN expression.
//Any token on the command line is first checked to see if it is a variable
//name. Then it is checked to see if it is a command name. Then it is
//checked for the special form: "fixN" or st:abc. Anything not fitting any
//of these forms is assumed to be a literal number to insert onto the stack.
// -------------------------------
/*include(Copyright)*/
//TODO:
// - implement list command
// -
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <tcl.h>
//#include "../Version.h"
#define STRLEN 256
#define STKSIZE 8 /* how many stack elements */
extern int Rpn_Init(Tcl_Interp *interp); /* run when library loaded */
extern int Rpn_SafeInit(Tcl_Interp *interp);
extern Tcl_ObjCmdProc rpn; /* do I need these? */
extern Tcl_ObjCmdProc rpx;
typedef struct { /* interpretor context */
int error; /* non-zero if an error occurred */
char errstrg[STRLEN]; /* description of the last error */
int fixval; /* how many digits to show */
int use_rads; /* in radian mode */
double stk[STKSIZE]; /* rpn stack */
Tcl_HashTable vartab; /* table of variables and their values */
} ri;
//common to all interpretors
static Tcl_HashTable cmdtab; /* table of commands and their routines */
static Tcl_HashTable rintab; /* table of interpretors */
// convert string to double */
// ----------------------------------------------
int GetDouble(char *sptr, int slen, double *tdoub) {
char ts[STRLEN], *t = ts, *eptr;
register int i, lead = 1;
double sign = 1;
double retval;
if (slen > STRLEN) {
*tdoub = 0;
return 0; // ERROR;
}
for(; slen && *sptr; slen--, sptr++) { /* for each character in sptr */
if (*sptr == ',') { /* ignore commas */
continue;
} else if (lead && *sptr == '+') { /* and leading plusses */
;
} else if (lead && *sptr == '-') { /* tally total number of leading negatives */
sign *= -1;
} else {
*t++ = *sptr;
lead = 0;
}
}
*t = 0; /* null terminate */
errno = 0;
*tdoub = strtod(ts, &eptr) * sign; /* convert the value */
i = (eptr - ts);
//printf("strtod:%s: errno:%d diff:%d", ts, errno, i);fflush(stdout);
if (errno || i != strlen(ts)) {
*tdoub = 0;
return 0; // ERROR;
}
//printf(" tdoub:%f errno:%d\n", *tdoub, errno);
return 1;
}
//Compare out to a given digit fixval, but no less than 11 digits
// ----------------------------------------------
static double fcmp(double a, double b, int fixval) {
double small = pow(10,-(fixval > 11 ? fixval : 11));
//printf("a=%.14f b=%.14f diff=%.14f small=%.14f\n",a,b,a-b,small); fflush(stdout);
if (fabs(a-b) < small) return 0;
if (a > b) return 1;
return -1;
}
// Create a new interpretor structure
// ----------------------------------------------
ri *rpn_new() {
int isnew;
ri *r = malloc(sizeof(ri));
//printf("rpn_new:%0X\n", r); fflush(stdout);
r->error = 0;
r->fixval = 9;
r->use_rads = 1;
Tcl_InitHashTable(&r->vartab, TCL_STRING_KEYS); /* create variable table */
Tcl_SetHashValue(Tcl_CreateHashEntry(&r->vartab, "_E" ,&isnew), Tcl_NewDoubleObj(M_E));
Tcl_SetHashValue(Tcl_CreateHashEntry(&r->vartab, "_PI",&isnew), Tcl_NewDoubleObj(M_PI));
return(r);
}
// ----------------------------------------------
static void push(ri *r, double a) { /* Push a onto the stack */
int i;
for(i = STKSIZE-1; i > 0; i--) /* for each stack element */
r->stk[i] = r->stk[i-1]; /* roll it up */
r->stk[0] = a;
}
// ----------------------------------------------
static void rdn(ri *r) { /* roll down stack (not incl 0) */
int i;
for(i = 1; i < (STKSIZE-1); i++) /* for each stack register */
r->stk[i] = r->stk[i+1]; /* roll it down */
}
// ----------------------------------------------
static double to_rads(ri *r, double inval) { /* convert to radians */
if (r->use_rads)
return(inval);
return(inval * M_PI / 180.0);
}
// ----------------------------------------------
static double from_rads(ri *r, double inval) { /* convert to degrees */
if (r->use_rads)
return(inval);
return(inval / M_PI * 180.0);
}
/* The Func_xx routines get called from their correspnding RPN command */
// ----------------------------------------------
static void Func_plus(ri *r) {r->stk[0] += r->stk[1]; rdn(r);}
static void Func_minus(ri *r) {r->stk[0] = r->stk[1] - r->stk[0]; rdn(r);}
static void Func_times(ri *r) {r->stk[0] *= r->stk[1]; rdn(r);}
static void Func_divide(ri *r) {r->stk[0] = r->stk[1] / r->stk[0]; rdn(r);}
static void Func_mod(ri *r) {r->stk[0] = fmod(r->stk[1], r->stk[0]); rdn(r);}
static void Func_min(ri *r) {r->stk[0] = (r->stk[1] < r->stk[0]) ? r->stk[1] : r->stk[0]; rdn(r);}
static void Func_max(ri *r) {r->stk[0] = (r->stk[1] > r->stk[0]) ? r->stk[1] : r->stk[0]; rdn(r);}
static void Func_sin(ri *r) {r->stk[0] = sin(to_rads(r,r->stk[0]));}
static void Func_cos(ri *r) {r->stk[0] = cos(to_rads(r,r->stk[0]));}
static void Func_tan(ri *r) {r->stk[0] = tan(to_rads(r,r->stk[0]));}
static void Func_asin(ri *r) {r->stk[0] = from_rads(r,asin(r->stk[0]));}
static void Func_acos(ri *r) {r->stk[0] = from_rads(r,acos(r->stk[0]));}
static void Func_atan(ri *r) {r->stk[0] = from_rads(r,atan(r->stk[0]));}
static void Func_rad(ri *r) {r->use_rads = 1;}
static void Func_deg(ri *r) {r->use_rads = 0;}
static void Func_int(ri *r) {r->stk[0] = floor(r->stk[0]);}
static void Func_frc(ri *r) {r->stk[0] -= floor(r->stk[0]);}
static void Func_rnd(ri *r) {r->stk[0] = floor(r->stk[0] + 0.5);}
static void Func_sqrt(ri *r) {r->stk[0] = sqrt(r->stk[0]);}
static void Func_sqr(ri *r) {r->stk[0] = r->stk[0] * r->stk[0];}
static void Func_abs(ri *r) {r->stk[0] = fabs(r->stk[0]);}
static void Func_ln(ri *r) {r->stk[0] = log(r->stk[0]);}
static void Func_exp(ri *r) {r->stk[0] = exp(r->stk[0]);}
static void Func_inv(ri *r) {r->stk[0] = (1 / r->stk[0]);}
static void Func_log(ri *r) {r->stk[0] = log10(r->stk[0]);}
static void Func_10x(ri *r) {r->stk[0] = pow(10,r->stk[0]);}
static void Func_yx(ri *r) {r->stk[0] = pow(r->stk[1],r->stk[0]); rdn(r);}
static void Func_clr(ri *r) {r->stk[0] = 0;}
static void Func_rdn(ri *r) {r->stk[0] = r->stk[1];rdn(r);}
static void Func_chs(ri *r) {r->stk[0] = -r->stk[0];}
static void Func_pi(ri *r) {push(r,M_PI);}
static void Func_ent(ri *r) {push(r,r->stk[0]);}
static void Func_xch(ri *r) {register double td = r->stk[0]; r->stk[0] = r->stk[1]; r->stk[1] = td;}
static void Func_not(ri *r) {r->stk[0] = !r->stk[0];}
static void Func_ne(ri *r) {r->stk[0] = fcmp(r->stk[1],r->stk[0],r->fixval) != 0 ? 1 : 0; rdn(r);}
static void Func_eq(ri *r) {r->stk[0] = fcmp(r->stk[1],r->stk[0],r->fixval) == 0 ? 1 : 0; rdn(r);}
static void Func_gt(ri *r) {r->stk[0] = fcmp(r->stk[1],r->stk[0],r->fixval) > 0 ? 1 : 0; rdn(r);}
static void Func_ge(ri *r) {r->stk[0] = fcmp(r->stk[1],r->stk[0],r->fixval) >= 0 ? 1 : 0; rdn(r);}
static void Func_lt(ri *r) {r->stk[0] = fcmp(r->stk[1],r->stk[0],r->fixval) < 0 ? 1 : 0; rdn(r);}
static void Func_le(ri *r) {r->stk[0] = fcmp(r->stk[1],r->stk[0],r->fixval) <= 0 ? 1 : 0; rdn(r);}
// ----------------------------------------------
static void Func_rtop(ri *r) { /* r->stk[0] = x, r->stk[1] = y */
register double m, sgn;
m = sqrt(pow(r->stk[0],2.0) + pow(r->stk[1],2.0));
if (r->stk[1] >= 0) sgn = 1; else sgn = -1;
if (r->stk[0] > 0)
r->stk[1] = from_rads(r,atan(r->stk[1] / r->stk[0]));
else if (r->stk[0] < 0)
r->stk[1] = from_rads(r,atan(r->stk[1] / r->stk[0]) + (sgn * M_PI));
else
r->stk[1] = from_rads(r,sgn * M_PI_2);
r->stk[0] = m;
}
// ----------------------------------------------
static void Func_ptor(ri *r) {
register double x;
x = r->stk[0] * cos(to_rads(r,r->stk[1]));
r->stk[1] = r->stk[0] * sin(to_rads(r,r->stk[1]));
r->stk[0] = x;
}
// ----------------------------------------------
static void Func_trim(ri *r) /* trim digits beyond the fix value */
{
char ts[STRLEN];
double td;
snprintf(ts, STRLEN, "%.*f", r->fixval, r->stk[0]);
if (!GetDouble(ts, STRLEN, &td)) {
snprintf(r->errstrg, STRLEN, "Improper numeric value: %s",ts);
r->error = 1;
}
r->stk[0] = td;
}
// ----------------------------------------------
static void store(ri *r, Tcl_Interp *interp, char *istrg) { /* store in a memory location */
double td = 0;
char c = *istrg++;
Tcl_HashEntry *hashent;
Tcl_Obj *hobj;
int isnew;
if (!isalpha(*istrg)) { /* symbol must start with an alpha */
snprintf(r->errstrg, STRLEN, "Invalid variable symbol: %s",istrg);
r->error = 1;
return;
}
hashent = Tcl_CreateHashEntry(&(r->vartab), istrg, &isnew);
//printf("store 2; hashent=%08X\n", hashent);
if (isnew) { /* if this is a new entry */
hobj = Tcl_NewDoubleObj(td); /* make an object for it */
Tcl_SetHashValue(hashent, hobj);
} else { /* else get the starting value */
hobj = Tcl_GetHashValue(hashent);
if (Tcl_GetDoubleFromObj(interp, hobj, &td) != TCL_OK) {
snprintf(r->errstrg, STRLEN, "Couldn't convert double");
r->error = 1;
return;
}
}
switch(c) {
case ':': td = r->stk[0]; break;
case '*': td *= r->stk[0]; break;
case '/': td /= r->stk[0]; break;
case '+': td += r->stk[0]; break;
case '-': td -= r->stk[0]; break;
}
Tcl_SetDoubleObj(hobj, td); /* set the value into the hash table */
}
// Call the generic rpn interpretor context
// ----------------------------------------------
int rpn(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
int i;
Tcl_Obj *ov[objc + 1];
ov[0] = Tcl_NewStringObj("rpn",1);
for (i = 0; i < objc; i++) {
//printf("asn i:%d\n",i); fflush(stdout);
ov[i + 1] = objv[i];
}
return (rpx(clientData, interp, objc + 1, ov));
}
// Main entry point to RPN routine
// ----------------------------------------------
int rpx(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
int i, j, slen, oc, isnew;
char *sptr, rstrg[STRLEN];
double tdoub;
Tcl_Obj **ov;
Tcl_HashEntry *hashent;
void *func;
ri *r;
if (objc < 2) {
sptr = "rpn";
} else {
sptr = Tcl_GetStringFromObj(objv[1],&slen);
}
//printf("sptr: %s\n",sptr); fflush(stdout);
// if (!*sptr) {
// Tcl_AddErrorInfo(interp, "Illegal rpn interpretor name");
// return TCL_ERROR;
// }
if (!strcmp(sptr,"forget")) {
if (!(hashent = Tcl_GetHashValue(Tcl_FindHashEntry(&rintab, sptr)))) {
Tcl_AddErrorInfo(interp, "Interpreter not found");
return TCL_ERROR;
} else {
r = Tcl_GetHashValue(hashent);
Tcl_DeleteHashTable(&(r->vartab));
Tcl_DeleteHashEntry(hashent);
free(hashent);
return TCL_OK;
}
} else if (!strcmp(sptr,"list")) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("Not implemented",-1));
return TCL_ERROR;
} else if ((hashent = Tcl_FindHashEntry(&rintab, sptr)) == NULL) { //interpretor not found
//printf("new: %s\n",sptr); fflush(stdout);
r = rpn_new();
Tcl_SetHashValue(Tcl_CreateHashEntry(&rintab, sptr, &isnew), (ClientData)r);
} else { //interpretor was found
r = Tcl_GetHashValue(hashent);
}
//FIXME:
//r = (ri *)Tcl_GetHashValue(Tcl_FindHashEntry(&rintab, "rpn"));
//printf("r:%0X\n",r); fflush(stdout); //pointer to interp
//printf(" objc: %d\n", objc); fflush(stdout);
//printf(" i 0: %s\n", Tcl_GetStringFromObj(objv[0],&slen)); fflush(stdout);
//printf(" i 1: %s\n", Tcl_GetStringFromObj(objv[1],&slen)); fflush(stdout);
for (i = 2; i < objc; i++) { /* for each parameter */
Tcl_ListObjGetElements(interp, objv[i], &oc, &ov);
for (j = 0; j < oc; j++) { /* for each list element of parameter */
r->error = 0;
sptr = Tcl_GetStringFromObj(ov[j], &slen);
//printf(" j %d: %s\n", j, sptr); fflush(stdout);
if ((hashent = Tcl_FindHashEntry(&r->vartab, sptr)) != NULL) { /* if a variable found */
//printf("found var\n");fflush(stdout);
if (Tcl_GetDoubleFromObj(interp, Tcl_GetHashValue(hashent), &tdoub) != TCL_OK) {
return TCL_ERROR; /* couldn't convert float */
}
push(r,tdoub); /* use the variable's value */
} else if ((hashent = Tcl_FindHashEntry(&cmdtab, sptr)) != NULL) { /* if a command found */
//printf("found cmd; func=%08X\n", func); fflush(stdout);
func = Tcl_GetHashValue(hashent);
(*((void (*)())(func))) (r);
} else if (!strncmp(sptr,"fix",3)) {
//printf("found fix; v=%s\n", sptr+3); fflush(stdout);
r->fixval = atoi(sptr+3);
r->fixval %= 100; /* only valid 0 - 99 */
} else if (!strncmp(sptr,"st",2) && strchr(":+-*/",sptr[2])) {
store(r, interp, sptr+2);
} else {
//printf("found explicit:%s:\n", sptr); fflush(stdout);
#ifdef OLDWAY /* TCL can't handle a double negative */
if (Tcl_GetDoubleFromObj(interp, ov[j], &tdoub) != TCL_OK) {
return TCL_ERROR; /* couldn't convert float */
}
#else /* use my own string convert function */
if (!GetDouble(sptr, slen, &tdoub)) {
snprintf(r->errstrg, STRLEN, "Improper numeric value: %s",sptr);
r->error = 1;
}
#endif
push(r,tdoub); /* use the explicit value */
}
if (r->error) {
Tcl_AddErrorInfo(interp, r->errstrg);
return TCL_ERROR;
}
//printf(" stk: %10.2f %10.2f %10.2f %10.2f \n", r->stk[0], r->stk[1], r->stk[2], r->stk[3]); fflush(stdout);
}
}
if (isnan(r->stk[0])) {
//printf("NAN\n");
Tcl_SetResult(interp, "Error", TCL_STATIC);
} else if (isinf(r->stk[0]) == -1) {
//printf("-INF\n");
Tcl_SetResult(interp, "-Infinite", TCL_STATIC);
} else if (isinf(r->stk[0]) == 1) {
//printf("INF\n");
Tcl_SetResult(interp, "Infinite", TCL_STATIC);
} else {
snprintf(rstrg, STRLEN, "%.*f", r->fixval, r->stk[0]);
Tcl_SetObjResult(interp, Tcl_NewStringObj(rstrg,-1));
}
//printf("DONE\n");fflush(stdout);
return TCL_OK;
}
// Initialization for this module
// ----------------------------------------------
int Rpn_Init(Tcl_Interp *interp) {
int isnew;
//printf("Initing 0\n");
Tcl_InitHashTable(&cmdtab, TCL_STRING_KEYS); /* create command table */
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "+", &isnew), (ClientData)Func_plus);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "-", &isnew), (ClientData)Func_minus);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "*", &isnew), (ClientData)Func_times);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, ".", &isnew), (ClientData)Func_times);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "/", &isnew), (ClientData)Func_divide);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "%", &isnew), (ClientData)Func_mod);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "min", &isnew), (ClientData)Func_min);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "max", &isnew), (ClientData)Func_max);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "sin", &isnew), (ClientData)Func_sin);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "cos", &isnew), (ClientData)Func_cos);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "tan", &isnew), (ClientData)Func_tan);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "asin", &isnew), (ClientData)Func_asin);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "acos", &isnew), (ClientData)Func_acos);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "atan", &isnew), (ClientData)Func_atan);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "rad", &isnew), (ClientData)Func_rad);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "deg", &isnew), (ClientData)Func_deg);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "int", &isnew), (ClientData)Func_int);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "frc", &isnew), (ClientData)Func_frc);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "rnd", &isnew), (ClientData)Func_rnd);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "sqrt", &isnew), (ClientData)Func_sqrt);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "sqr", &isnew), (ClientData)Func_sqr);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "abs", &isnew), (ClientData)Func_abs);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "ln", &isnew), (ClientData)Func_ln);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "exp", &isnew), (ClientData)Func_exp);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "inv", &isnew), (ClientData)Func_inv);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "log", &isnew), (ClientData)Func_log);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "10x", &isnew), (ClientData)Func_10x);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "yx", &isnew), (ClientData)Func_yx);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "clr", &isnew), (ClientData)Func_clr);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "rdn", &isnew), (ClientData)Func_rdn);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "chs", &isnew), (ClientData)Func_chs);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "pi", &isnew), (ClientData)Func_pi);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "ent", &isnew), (ClientData)Func_ent);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "xch", &isnew), (ClientData)Func_xch);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "trim", &isnew), (ClientData)Func_trim);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "!", &isnew), (ClientData)Func_not);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "!=", &isnew), (ClientData)Func_ne);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "=", &isnew), (ClientData)Func_eq);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, ">", &isnew), (ClientData)Func_gt);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, ">=", &isnew), (ClientData)Func_ge);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "<", &isnew), (ClientData)Func_lt);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "<=", &isnew), (ClientData)Func_le);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "rtop", &isnew), (ClientData)Func_rtop);
Tcl_SetHashValue(Tcl_CreateHashEntry(&cmdtab, "ptor", &isnew), (ClientData)Func_ptor);
Tcl_InitHashTable(&rintab, TCL_STRING_KEYS); /* create command table */
Tcl_SetHashValue(Tcl_CreateHashEntry(&rintab, "rpn", &isnew), (ClientData)rpn_new());
Tcl_CreateObjCommand(interp,"rpn",rpn,(ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
Tcl_CreateObjCommand(interp,"rpx",rpx,(ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
return TCL_OK;
}
// ----------------------------------------------
int Rpn_SafeInit(Tcl_Interp *interp) {return Rpn_Init(interp);} /* do we need this? */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <limits.h>
#include <libgen.h>
#include "sha.h"
#include "bootimg.h"
typedef unsigned char byte;
int read_padding(FILE* f, unsigned itemsize, int pagesize)
{
byte* buf = (byte*)malloc(sizeof(byte) * pagesize);
unsigned pagemask = pagesize - 1;
unsigned count;
if((itemsize & pagemask) == 0) {
free(buf);
return 0;
}
count = pagesize - (itemsize & pagemask);
fread(buf, count, 1, f);
free(buf);
return count;
}
void write_string_to_file(char* file, char* string)
{
FILE* f = fopen(file, "w");
fwrite(string, strlen(string), 1, f);
fwrite("\n", 1, 1, f);
fclose(f);
}
int usage() {
printf("usage: unpackbootimg\n");
printf("\t-i|--input boot.img\n");
printf("\t[ -o|--output output_directory]\n");
printf("\t[ -p|--pagesize <size-in-hexadecimal> ]\n");
printf("\t[ --dry-run ]\n");
return 0;
}
int main(int argc, char** argv)
{
char tmp[PATH_MAX];
char* directory = "./";
char* filename = NULL;
int pagesize = 0;
byte dry_run = 0;
byte param_found = 0;
argc--;
argv++;
while(argc > 0){
char *arg = argv[0];
// First check for parameters without expecting values
if(!strcmp(arg, "--dry-run")) {
dry_run = 1;
param_found = 1;
}
if (param_found == 1) {
argc --;
argv ++;
param_found = 0;
continue;
}
// Second check for parameters expecting values
char *val = argv[1];
argc -= 2;
argv += 2;
if(!strcmp(arg, "--input") || !strcmp(arg, "-i")) {
filename = val;
} else if(!strcmp(arg, "--output") || !strcmp(arg, "-o")) {
directory = val;
} else if(!strcmp(arg, "--pagesize") || !strcmp(arg, "-p")) {
pagesize = strtoul(val, 0, 16);
} else {
return usage();
}
}
if (filename == NULL) {
return usage();
}
int total_read = 0;
FILE* f = fopen(filename, "rb");
boot_img_hdr header;
printf("Reading header... ");
int i;
for (i = 0; i <= 512; i++) {
fseek(f, i, SEEK_SET);
fread(tmp, BOOT_MAGIC_SIZE, 1, f);
if (memcmp(tmp, BOOT_MAGIC, BOOT_MAGIC_SIZE) == 0)
break;
}
total_read = i;
if (i > 512) {
printf("Android boot magic not found.\n");
return 1;
}
fseek(f, i, SEEK_SET);
printf("Android magic found at offset: %d\n", i);
fread(&header, sizeof(header), 1, f);
if (pagesize == 0) {
pagesize = header.page_size;
}
printf("Kernel:\t\t\tsize:%u\t\taddr:0x%x\n",header.kernel_size,header.kernel_addr);
printf("Kernelbaseaddress:\t\t\t\taddr:0x%x\n",header.kernel_addr - 0x00008000);
printf("Ramdisk:\t\tsize:%u\t\taddr:0x%x\n",header.ramdisk_size,header.ramdisk_addr);
printf("Second:\t\t\tsize:%u\t\t\taddr:0x%x\n",header.second_size,header.second_addr);
printf("Page:\t\t\tsize:%u\n",header.page_size);
printf("Name:\t\t%.*s\n",BOOT_NAME_SIZE,header.name);
printf("Cmd:\t\t%.*s\n",BOOT_ARGS_SIZE,header.cmdline);
if (dry_run) {
return 0;
}
//printf("cmdline...\n");
sprintf(tmp, "%s/%s", directory, basename(filename));
strcat(tmp, "-cmdline");
write_string_to_file(tmp, header.cmdline);
//printf("base...\n");
sprintf(tmp, "%s/%s", directory, basename(filename));
strcat(tmp, "-base");
char basetmp[200];
sprintf(basetmp, "%08x", header.kernel_addr - 0x00008000);
write_string_to_file(tmp, basetmp);
//printf("pagesize...\n");
sprintf(tmp, "%s/%s", directory, basename(filename));
strcat(tmp, "-pagesize");
char pagesizetmp[200];
sprintf(pagesizetmp, "%d", header.page_size);
write_string_to_file(tmp, pagesizetmp);
total_read += sizeof(header);
total_read += read_padding(f, sizeof(header), pagesize);
if (header.kernel_size > 0 ) {
printf("Extracting kernel (%u bytes)...\n",header.kernel_size);
sprintf(tmp, "%s/%s", directory, basename(filename));
strcat(tmp, "-zImage");
FILE *k = fopen(tmp, "wb");
byte* kernel = (byte*)malloc(header.kernel_size);
fread(kernel, header.kernel_size, 1, f);
total_read += header.kernel_size;
fwrite(kernel, header.kernel_size, 1, k);
fclose(k);
} else {
printf("No kernel image found.\n");
}
total_read += read_padding(f, header.kernel_size, pagesize);
if (header.ramdisk_size > 0) {
printf("Extracting ramdisk (%u bytes)...\n",header.ramdisk_size);
sprintf(tmp, "%s/%s", directory, basename(filename));
strcat(tmp, "-ramdisk.gz");
FILE *r = fopen(tmp, "wb");
byte* ramdisk = (byte*)malloc(header.ramdisk_size);
fread(ramdisk, header.ramdisk_size, 1, f);
total_read += header.ramdisk_size;
fwrite(ramdisk, header.ramdisk_size, 1, r);
fclose(r);
} else {
printf("No ramdisk image found.\n");
}
total_read += read_padding(f, header.ramdisk_size, pagesize);
if (header.second_size > 0){
printf("Extracting second (%u bytes)...\n",header.second_size);
sprintf(tmp, "%s/%s", directory, basename(filename));
strcat(tmp, "-secimg");
FILE *r = fopen(tmp, "wb");
byte* ramdisk = (byte*)malloc(header.second_size);
fread(ramdisk, header.second_size, 1, f);
total_read += header.second_size;
fwrite(ramdisk, header.second_size, 1, r);
fclose(r);
} else {
printf("No secondary image found.\n");
}
total_read += read_padding(f, header.second_size, pagesize);
fclose(f);
printf("Total Read: %d\n", total_read);
return 0;
}
|
C
|
// kadai-14
#include <stdio.h>
#include <stdlib.h>
typedef struct shouhin {
char code[10];
char name[40];
int price;
} shouhinData;
int main(){
shouhinData items[100];
int i = 0;
while( scanf("%s %s %d", items[i].code, items[i].name, &(items[i].price)) != EOF){
printf("商品コード:%s\n", items[i].code);
printf("商品名:%s\n", items[i].name);
printf("値段:%d\n\n", items[i].price);
i++;
}
}
|
C
|
#include<stdio.h>
int main()
{
float d,p;
printf("Enter diameter:");
scanf("%f",&d);
p=2*3.1416*(d/2);
printf("Perimeter=%.3f",p);
return 0;
}
|
C
|
#include <stdio.h>
/* Exercise 1_10 */
main ()
{
int c;
while((c = getchar()) != EOF)
{
if (c == '\t')
printf("\\t"); /* I am not sure if this is implied in the book. However perhaps if I had done ex1-2 (as I now have), experimentation could of revealed the result.
Using \ as the escape character, I am escaping \, hence writing it (then followed by t). Hmmm actually they did mention it, with the mention of
the escape sequence for a double quotation mark is \", so this implies for backslash(forward, whatever), it is \\.
Note I could of written printf("%s", "\\t"), as %s is mentioned for sting constants. Note you need to write "" for the string constant, as that is what
a string constant. Note that "\t" is a string constant of 1 character - ""\\t" is one of two. This is because of the escape character \.
"\t" in printf will print a tab - that is four blank spaces. */
if (c == '\b') /* In bash shell on ubuntu linux, will need to enter CTRL + H to get \b to be printed out. CTRL + H sends ascii code 8 which is backspace */
printf("\\b");
if (c == '\\')
printf("\\\\"); /* Note that \\\ won't compile. \\ is an escape sequence for backslash. In \\\, the third \ is waiting for a character to create an escape sequence - this is
the same as just applying printf to "\" - compile error will ensue */
/* Remember I am not using anything I have not come up to in the book yet. The below is equivalent to if(c != '\t' && c != '\b' && c !='\\') putchar(c)*/
if (c != '\t')
if (c != '\b')
if (c != '\\')
putchar(c);
}
}
|
C
|
#include "holberton.h"
/**
* rot13 - using rot13 to encode a string
* @s: character being changed
* Return: Always 0.
*/
char *rot13(char *s)
{
char in[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char out[] = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";
int a;
int b;
for (a = 0; s[a] != '\0'; a++)
{
for (b = 0; in[b]; b++)
{
if (s[a] == in[b])
{
s[a] = out[b];
break;
}
}
}
return (s);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int i =15;
int j =20;
int main()
{
printf("I=%d\n",i);
printf("J=%d\n",j);
return 0;
}
|
C
|
// Copyright (c) 2020, devgo.club
// All rights reserved.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc, char const *argv[])
{
if (argc != 3)
{
fprintf(stderr, "Usage: %s <file> <bytes>\n", argv[0]);
return EXIT_FAILURE;
}
char const *file = argv[1];
int bytes = 0;
if (sscanf(argv[2], "%d", &bytes) != 1)
{
fprintf(stderr, "convert %s to int failed: %s\n", argv[2], strerror(EINVAL));
return EINVAL;
}
// fprintf(stdout, "%s --> %d\n", argv[2], bytes);
if (truncate(file, bytes) < 0)
{
fprintf(stderr, "truncate failed: %s\n", strerror(errno));
return errno;
}
return EXIT_SUCCESS;
}
|
C
|
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "mainAux.h"
#include "commands.h"
#include "linkedList.h"
#define maxCommandSize 256
/* parsing input from the user and addresses the relevant command method */
void readAndReactBuffer() {
char command[maxCommandSize];
char * token;
char *xString, *yString, *zString;
FILE * fp;
double x, y, z;
int validateFlag;
x = y = z = -1;
while(fgets(command, maxCommandSize, stdin) != NULL) {
token = strtok(command, " \t\r\n");
if (token != NULL && strlen(token) > 256) {
printf("ERROR: invalid command\n");
continue;
}
if (token != NULL) {
if (strcmp(token, "hint") == 0) {
xString = strtok(NULL, " \t\r\n");
yString = strtok(NULL, " \t\r\n");
if (xString == NULL || yString == NULL) {
printf("ERROR: invalid command\n");
printf("Enter your command:\n");
continue;
}
if (atoi(xString) == 0) {
printf("Error: value not in range 1-%d\n", N);
printf("Enter your command:\n");
continue;
} else {
x = atof(xString);
}
if (atoi(yString) == 0) {
printf("Error: value not in range 1-%d\n", N);
printf("Enter your command:\n");
continue;
} else {
y = atof(yString);
}
if (x < 1 || y < 1 || x > N || y > N || (x - (int) x) != 0 || (y - (int) y) != 0) {
printf("Error: value not in range 1-%d\n", N);
printf("Enter your command:\n");
continue;
}
hint((int)y, (int)x);
printf("Enter your command:\n");
continue;
} else if (strcmp(token, "solve") == 0) {
xString = strtok(NULL, " \t\r\n");
if (xString == NULL) {
printf("ERROR: invalid command\n");
printf("Enter your command:\n");
continue;
}
fp = fopen(xString, "r"); /*open file in reading mode*/
if (fp == NULL) {
printf("Error: File doesn't exist or cannot be opened\n");
printf("Enter your command:\n");
continue;
}
fclose(fp);
solve(xString);
} else if (strcmp(token, "edit") == 0) {
xString = strtok(NULL, " \t\r\n");
if (xString == NULL) {
edit(xString);
printf("Enter your command:\n");
continue;
}
fp = fopen(xString, "r"); /*open file in reading mode*/
if (fp == NULL) {
printf("Error: File cannot be opened\n");
printf("Enter your command:\n");
continue;
}
fclose(fp);
edit(xString);
} else if (strcmp(token, "mark_errors") == 0) {
xString = strtok(NULL, " \t\r\n");
if (xString == NULL) {
printf("ERROR: invalid command\n");
printf("Enter your command:\n");
continue;
}
if (strcmp(xString, "0") != 0 && atoi(xString) == 0) {
printf("Error: the value should be 0 or 1\n");
printf("Enter your command:\n");
continue;
}
x = atof(xString);
if ((x - (int) x) != 0) {
printf("Error: the value should be 0 or 1\n");
printf("Enter your command:\n");
continue;
}
mark_errors((int)x);
printf("Enter your command:\n");
continue;
} else if (strcmp(token, "print_board") == 0) {
print_board();
} else if (strcmp(token, "set") == 0) {
xString = strtok(NULL, " \t\r\n");
yString = strtok(NULL, " \t\r\n");
zString = strtok(NULL, " \t\r\n");
if (mode == 0) {
printf("ERROR: invalid command\n");
printf("Enter your command:\n");
continue;
}
if (xString == NULL || yString == NULL || zString == NULL) {
printf("ERROR: invalid command\n");
printf("Enter your command:\n");
continue;
}
if (strcmp(yString, "0") == 0 || strcmp(xString, "0") == 0) {
printf("Error: value not in range 0-%d\n", N);
printf("Enter your command:\n");
continue;
}
if (atoi(xString) == 0) { /* x isn't an integer*/
printf("Error: value not in range 0-%d\n", N);
printf("Enter your command:\n");
continue;
} else {
x = atof(xString);
}
if (atoi(yString) == 0) {
printf("Error: value not in range 0-%d\n", N);
printf("Enter your command:\n");
continue;
} else {
y = atof(yString);
}
if (strcmp(zString, "0") != 0 && atoi(zString) == 0) {
printf("ERROR: invalid command\n");
printf("Enter your command:\n");
continue;
} else {
z = atof(zString);
}
if (x <= 0 || y <= 0 || z < 0 || x > N || y > N || z > N || (x - (int) x) != 0 || (y - (int) y) != 0 ||
(z - (int) z) != 0) { /*z can be 0*/
printf("Error: value not in range 0-%d\n", N);
printf("Enter your command:\n");
continue;
}
set((int)x, (int)y, (int)z);
} else if (strcmp(token, "validate") == 0) {
validateFlag = validate();
if (validateFlag == 1) {
printf("Validation passed: board is solvable\n");
} else if (validateFlag == 0) {
printf("Validation failed: board is unsolvable\n");
}
} else if (strcmp(token, "generate") == 0) {
int numberOfEmptyCells;
if (mode != 1) {
printf("ERROR: invalid command\n");
printf("Enter your command:\n");
continue;
}
numberOfEmptyCells = countNumberOfEmptyCells();
xString = strtok(NULL, " \t\r\n");
yString = strtok(NULL, " \t\r\n");
if (xString == NULL || yString == NULL) {
printf("ERROR: invalid command\n");
printf("Enter your command:\n");
continue;
} else {
x = atof(xString);
}
if (strcmp(yString, "0") != 0 && atoi(yString) == 0) {
printf("Error: value not in range 0-%d\n", numberOfEmptyCells);
printf("Enter your command:\n");
continue;
} else {
y = atof(yString);
}
if (strcmp(xString, "0") != 0 && atoi(xString) == 0) {
printf("Error: value not in range 0-%d\n", numberOfEmptyCells);
printf("Enter your command:\n");
continue;
}
if (x < 0 || y < 0 || x > numberOfEmptyCells || y > numberOfEmptyCells || (x - (int) x) != 0 || (y - (int) y) != 0) {
if (numberOfEmptyCells != 0) {
printf("Error: value not in range 0-%d\n", numberOfEmptyCells);
printf("Enter your command:\n");
continue;
}
}
if (isBoardEmpty() == 0) { /* we must check that the board is completely empty*/
printf("Error: board is not empty\n");
printf("Enter your command:\n");
continue;
}
matrixBeforeGenerate = copyMatrix(matrix,N);
generate((int)x, (int)y, 0);
freeMatrix(matrixBeforeGenerate,N);
printf("Enter your command:\n");
continue;
} else if (strcmp(token, "undo") == 0) {
undo();
} else if (strcmp(token, "redo") == 0) {
redo();
} else if (strcmp(token, "save") == 0) {
xString = strtok(NULL, " \t\r\n");
if (xString == NULL) {
printf("ERROR: invalid command\n");
printf("Enter your command:\n");
continue;
}
save(xString);
} else if (strcmp(token, "num_solutions") == 0) {
num_solutions();
printf("Enter your command:\n");
continue;
} else if (strcmp(token, "autofill") == 0) {
autofill();
} else if (strcmp(token, "reset") == 0) {
reset();
} else if (strcmp(token, "exit") == 0) {
freeMatrix(matrix, N);
freeMatrix(fixedFlagMatrix, N);
freeMatrix(errorsMatrix, N);
freeMatrix(solMatrix, N);
while (head != NULL || last != NULL) { /*clean the linkedList after successful gameover*/
deleteLast();
}
current = NULL;
printf("Exiting...\n");
exit(1);
} else {
printf("ERROR: invalid command\n");
}
printf("Enter your command:\n");
}
}
/* this part is for an EOF exit. */
freeMatrix(matrix, N);
freeMatrix(fixedFlagMatrix, N);
freeMatrix(errorsMatrix, N);
freeMatrix(solMatrix, N);
while (head != NULL || last != NULL) { /* clean the linkedList after successful gameover */
deleteLast();
}
current = NULL;
printf("Exiting...\n");
exit(1);
}
/*Restart the game*/
void start_game() {
n=3; /* default! */
m=3;
N = n*m;
mode = 0; /* default! */
markErrorsFlag = 1;
matrix = create_empty_game_board();
errorsMatrix = create_empty_game_board();
fixedFlagMatrix = create_empty_game_board();
solMatrix = create_empty_game_board();
while (head != NULL || last != NULL) { /*clean the linkedList after a successful gameover*/
deleteLast();
}
current = NULL;
printf("Enter your command:\n");
readAndReactBuffer(); /*start reading inputs*/
}
|
C
|
/**
* @file PWM.c
* @author
* @brief
* @version 0.1
* @date 2021-08-11
*
* @copyright Copyright (c) 2021
*
*/
#include "DataTypes.h"
#include "PWM.h"
/**
* @brief Initailze Phase Correct PWM
*
* @return EN_ERRORSTATE_t Error state
*/
EN_ERRORSTATE_t PWM_ENInitPhaseCorrect(void)
{
EN_ERRORSTATE_t state;
state = E_OK;
CLRBIT(TCCR1A, WGM10);
CLRBIT(TCCR1A, WGM11);
CLRBIT(TCCR1B, WGM12);
SETBIT(TCCR1B, WGM13);
#if OCRA_MODE == OCRA_NON_INVERTING_MODE
CLRBIT(TCCR1A, COM1A0);
SETBIT(TCCR1A, COM1A1);
#elif OCRA_MODE == OCRA_INVERTING_MODE
SETBIT(TCCR1A, COM1A0);
SETBIT(TCCR1A, COM1A1);
#endif
#if OCRB_MODE == OCRB_NON_INVERTING_MODE
CLRBIT(TCCR1A, COM1B0);
SETBIT(TCCR1A, COM1B1);
#elif OCRB_MODE == OCRB_INVERTING_MODE
SETBIT(TCCR1A, COM1B0);
SETBIT(TCCR1A, COM1B1);
#endif
TCCR1B &= 0XF8;
TCCR1B |= PWM_SCALER;
return state;
}
/**
* @brief DutyCycle
*
* @param DutyCycle Speed
* @return EN_ERRORSTATE_t Error state
*/
EN_ERRORSTATE_t PWM_ENDutyCycle(uint8_t DutyCycle)
{
EN_ERRORSTATE_t state;
ICR1 = TIMER1_ICR_TOP_CAPACITY;
state = E_OK;
#if OCRA_MODE == OCRA_NON_INVERTING_MODE
OCR1A = ((TIMER1_ICR_TOP_CAPACITY * (uint32_t)DutyCycle) / 100);
#elif OCRA_MODE == OCRA_INVERTING_MODE
OCR1A = TIMER1_ICR_TOP_CAPACITY - ((TIMER1_ICR_TOP_CAPACITY * DutyCycle) / 100);
#else
state = E_ERROR;
#endif
#if OCRB_MODE == OCRB_NON_INVERTING_MODE
OCR1B = ((TIMER1_ICR_TOP_CAPACITY * (uint32_t)DutyCycle) / 100);
#elif OCRB_MODE == OCRB_INVERTING_MODE
OCR1B = TIMER1_ICR_TOP_CAPACITY - ((TIMER1_ICR_TOP_CAPACITY * DutyCycle) / 100);
#else
state = E_ERROR;
#endif
return state;
}
|
C
|
/* Take a maximum of 100 characters from the user.
* Stop taking inputs when the user enters dot (.),
* and print the number lowercase, uppercase letters,
* and the number of digits the user entered.
* Use break. (Take the characters with enter (newline) between them) */
#include <stdio.h>
int main()
{
int i;
int lower_count = 0, upper_count = 0, digit_count = 0;
char ch;
scanf("%c", &ch);
for(i = 0; i < 100; i++){
if(ch == '.'){
break;
}
if(ch >= 'a' && ch <= 'z'){
lower_count++;
}
else if(ch >= 'A' && ch <= 'Z'){
upper_count++;
}
else if(ch >= '0' && ch <= '9'){
digit_count++;
}
scanf("%c", &ch);
}
printf("Lowercase: %d \n", lower_count);
printf("Uppercase: %d \n", upper_count);
printf("Digit: %d \n", digit_count);
return 0;
}
|
C
|
/*********************************************************************************************/
/**
* \fn max_h_Case(int a)
* \brief Fonction qui vérifie la limite des cases de la grille.
*
* \param a La taille de la grille.
*/
/*int max_h_Case(int a) {
if(a%2 == 1) {
a = a-1;
a++;
}
return a;
}*/
/**
* \fn max_v_Case(int b)
* \brief Fonction qui vérifie la limite des cases de la grille .
*
* \param b La taille de la grille.
*/
/*int max_v_Case(int b) {
if(b%2 == 1) {
b = b-1;
b++;
}
return b;
} //*/
/*********************************************************************************************/
/**
* \fn verifier_Case_Noire_Ligne( t_couleurs matr[N][N], int ligne, int valeur)
* \brief Fonction qui vérifie que les cases noire correspondent au nombre horisentals de la matrice periphérique .
*
* \param matr La matrice qui represente la grille
* \param ligne Les lignes de la grille
* \param valeur Les valeurs de la matrice periphérique
*/
/*_Bool verifier_Case_Noire_Ligne( t_couleurs matr[N][N], int ligne, int valeur){
int i,j=0;
_Bool comp=false,find=false; ///find : trouver une case noire/ comp : trouver toute les cases
int c=0; //compteur qui correspond au nombre de case a trouvé
while(j<N-1 && comp==false) // parcourir toute la ligne et on a pas encore trouvé toute les cases
{
if(matr[ligne][j]==1) // si on a trouvé la premiére case noire
{
i=j+1; //on verifi la deuxiéme case
find=true; //on a trouvé la premiére case
c=valeur-1; //parcourir les cases restantes
if(c==0){ // si il est demandé de trouver qu'une seule valeur
comp=true;
}
else
{
*//*trois condition :
1ere parcourir le reste des cases a verifier ;
2eme on verifie qu'on a pas atteint la fin de la ligne ;
3eme on s'arrete quand on trouve une case noiree*/
/*while(i<i+c && i<N-1 && find==true)
{
if(matr[ligne][i]==1){ //on a trouvé la deuxieme case noire
i++;} //on passe a la case à coté
else{
find=false;} // si la deuxiéme n'est pas noire on sort de la boucle
}
if(find==true){
comp=true;}
else{ // remetre le compteur à 0 pour la prochaine recherche
c=0;}
}
}
j++;
}
return comp;
} //*/
/*********************************************************************************************/
/**
* \fn verifier_Case_Noire_Col( t_couleurs matr[N][N], int col, int valeur)
* \brief Fonction qui verifie que les cases noire correspondent au nombre verticals de la matrice periphérique .
*
* \param matr La matrice qui représente la grille
* \param col Les colonnes de la grille
* \param valeur Les valeurs de la matrice periphérique
*/
/*_Bool verifier_Case_Noire_Col( t_couleurs matr[N][N], int col, int valeur){
int i,j=0,c=0;
_Bool comp=false,find= false;
while(j<N-1 && comp==false)
{
if(matr[j][col]==1)
{
i=j+1;
find=true;
c=valeur-1;
if(c==0){
comp=true;
}
else
{
while(i<i+c && i<=N-1 && find==true)
{
if(matr[i][col]==1){
i++;}
else{
find=false;}
}
if(find==true){
comp=true;}
else{
c=0;}
}
}
j++;
}
return comp;
} //*/
|
C
|
/* The MIT License
Copyright (C) 2011, 2012 Zilong Tan (eric.zltan@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include "tree_util.h"
int tree_height(struct tree_root_np *root)
{
int hl, hr;
if (root == NULL)
return 0;
hl = tree_height(root->left);
hr = tree_height(root->right);
if (hl > hr)
return hl + 1;
return hr + 1;
}
int tree_verify(struct tree_root *root,
int (*compare) (const void *, const void *))
{
struct tree_root *p;
struct tree_root *last = NULL;
size_t count = 0;
if (root == NULL)
return 0;
tree_for_each(p, root) {
if (last == NULL)
last = p;
else if (compare(p, last) <= 0)
return -1;
++count;
}
if (count != TREE_COUNT(root))
return -1;
return 0;
}
size_t tree_count(struct tree_root_np * root)
{
if (root == NULL)
return 0;
return tree_count(root->left) + tree_count(root->right) + 1;
}
static inline void
__tree_print(struct tree_root *root,
void (*callback)(struct tree_root *),
uint64_t bitpath)
{
int n;
int h = 0;
if (root->left)
__tree_print(root->left, callback, bitpath << 1);
if (root->right)
__tree_print(root->right, callback, bitpath << 1 | 1);
for (n = 32; n > 0; n >>= 1) {
if ((bitpath & (uint64_t)(-((uint64_t)1 << (64 - n)))) == 0) {
bitpath <<= n;
h += n;
}
}
bitpath <<= 1; /* skip the tree marker bit */
h = 63 - h;
while (h-- > 0) {
if (bitpath & 0x8000000000000000ULL)
putchar('R');
else
putchar('L');
bitpath <<= 1;
}
putchar('\t');
if (callback)
callback(root);
}
void tree_print(struct tree_root *root, void (*callback)(struct tree_root *))
{
if (root)
__tree_print(root, callback, 1);
}
|
C
|
#ifndef MORFOSSINTAXE_H_INCLUDED
#define MORFOSSINTAXE_H_INCLUDED
/*Estrutura da Lista de Palavra.*/
typedef struct palavra{
char texto[100]; //Palavra da frase original.
char raiz[100]; //Raiz da palavra.
double percentagem; //Certeza da ferramenta em relacao a análise realizada.
int quantidade; //Quantas vezes a palavra se repete.
int tamanho; //Tamanho da palavra.
struct palavra *proximo; //Próxima palavra.
struct palavra *anterior; //Palavra anterior.
} Palavra;
/*Estrutura de Lista de Categoria de Palavras de acordo com sua classificação.*/
typedef struct categoria{
char texto[10]; //Análise morfossintática.
int qtd_palavras; //Quantidade de palavras que a categoria possui.
Palavra *palavra; //Inicio da lista de palavras (Lista de Lista).
struct categoria *proximo; //Proxima categoria.
struct categoria *anterior; //Categoria anterior.
} Categoria;
/*Estrutura para Lista de Frequencias.*/
typedef struct frequencia{
char variavel[100]; //Variável em estudo: x.
int freq_abs; //Frequência absoluta: ni.
float freq_rel; //Frequencia relativa: fi.
int freq_abs_acumulada; //Frequencia absoluta acumulada: Ni.
float freq_rel_acumulada; //Frequencia relativa acumulada: Fi.
struct frequencia *proximo; //Proxima frequencia
} Frequencia;
/*Lista de Média Aritmetica e Desvio Padrão das Categorias de Palavras com base na certeza de etiquetação.*/
typedef struct medDesvCat{
char categoria[10]; //Categoria de uma palavra.
double media_aritmetica; //Media aritmética com base na medida de etiquetação da categoria.
double desvio_padrao; //Desvio padrão com base na medida de etiquetação da categoria.
struct medDesvCat *proximo; //Proxima informação de medidas.
} MedDesvCat;
/*Estrutura de Lista de frequencia das palavras para implementação de Quartil*/
typedef struct freqPalavras{
char palavra[100];
int quantidade;
struct freqPalavras *proximo;
} FreqPalavras;
/*Estrutura para histograma de probabilidades*/
typedef struct histograma{
double limite_inferior;
double limite_superior;
int freq_abs;
double freq_rel;
double ponto_medio;
struct histograma *proximo;
} Histograma;
typedef struct frequenciaCerteza{
double certeza;
int frequencia;
struct frequenciaCerteza* proximo;
} FrequenciaCerteza;
/*Inicio da lista de categorias com palavras.*/
Categoria *categoria_header;
/*Inicio da lista de frequencias da categoria gramatical utilizada.*/
Frequencia *freq_categoria_h;
/*Inicio da lista de frequencias do tamanho das palavras.*/
Frequencia *freq_tamanho_palavra_h;
/*Inicio da lista de media e desvio padrão com base na certeza de etiquetação*/
MedDesvCat *med_desv_h;
/*Ultimo da lista de media e desvio padrao*/
MedDesvCat *med_desv_ultimo;
/*Inicio da Frequencia de Palavras*/
FreqPalavras *freq_palavras_h;
/*Inicio da lista do histograma de probabilidades com base na certeza de etiquetação*/
Histograma* histograma_h;
Histograma* histograma_fim;
FrequenciaCerteza* freq_certeza_h;
double maiorCertezaHistograma;
double menorCertezaHistograma;
int totalCategorias = 0; //Total de categorias durante a execução do programa.
int totalPalavras = 0; //Total de palavras lidas do arquivo.
/*Medidas de localização e dispersao, relativas ao tamanho das palavras: media
aritmetica, mediana, moda e desvio padrao.*/
int totalTamanhoPalavras = 0; //Quantos diferentes tamanhos de palavras existem.
double ma_tam_palavra = 0; //Média Aritmética dos tamanhos de palavras.
int mediana_tam_palavra = 0; //Mediana dos tamanhos de palavras.
int moda_tam_palavra = 0; //Moda dos tamanhos de palavras.
double desvio_padrao_tam_palavra = 0; //Desvio padrão dos tamanhos de palavras.
int somaFreqPalavras = 0; //Soma da quantidade de Frequencia das palavras.
int mediana_posicao = 0;
float quartil_1;
float quartil_2;
float quartil_3;
Categoria* getResultado();
void iniciar();
void destroi();
int insere(char* texto, char* raiz, char* categoria, double percentagem);
bool checkInput(char value[]);
Palavra* acharMeioPalavra(Palavra *comeco_el, Palavra *ultimo_el);
Categoria* acharMeioCategoria(Categoria *comeco_el, Categoria *ultimo_el);
Palavra* buscaBinariaPalavra(Palavra *p, char* texto);
Categoria* buscaBinariaCategoria(Categoria *l, char* texto);
int insereCategoria(Categoria *p_new, Categoria *p_elemento);
int inserePalavra(Palavra *p_new, Palavra *p_palavra, Palavra **p_header);
int calcFreqMed(Categoria *lista); //Calcular frequencias e medidas das questões apresentadas no trabalho prático.
int insereFrequenciaCatOrdenada(Frequencia** frequencia, Frequencia** header); //Frequencia das categorias.
int insereFrequenciaTamOrdenada(Frequencia** frequencia, Frequencia** header); //Frequencia da incidencia do tamanho das palavras.
int insereMedDesv(MedDesvCat** med_desv); //Insere na lista de media e desvio padrão com base na etiquetação.
int insereFreqPalavraOrdenada(Palavra* palavra); //Insere na lista de Frequencia das palavras.
int getQuartil(char texto[]);//Retorna quartil de acordo com palavra informada
void calculaQuartil(); //Calcula Quartis das Frequencias de Palavras;
int insereHistograma(double limite_inferior, double limite_superior, int frequencia, double ponto_medio);
int insereFrequenciaCertezaOrd(Palavra *palavra);
void showFreqTamPalavras();
void showFreqCategorias();
void showMedDesvCat();
void showLocDisp();
void showFreqPalavras();
void calcHistograma();
#endif // MORFOSSINTAXE_H_INCLUDED
|
C
|
#include <stdio.h>
struct keysflag
{
unsigned int is_keyword : 1; // single bit width field, with use of colon we can say how many bits width field we want
unsigned int is_extern : 1;
unsigned int is_static : 3; // 3 bits wide
} flags = { 1, 1, 7 };
int main()
{
unsigned char c = 255;
printf("Value of c is %d\n", c);
c = c ^ flags.is_extern; // assuming flags.is_extern is single bit field and with value 1 the xor operation should set c to 254
printf("Value of c is %d\n", c);
if (flags.is_extern)
{
printf("Is external variable\n");
}
}
|
C
|
#include "monty.h"
stainst_t stainst;
/**
* push_function - adds a new node at the beginning of a dlistint_t list.
* @stack: stack
* @line_number: line number
* Return: void
*/
void push_function(stack_t **stack, unsigned int line_number)
{
stack_t *new = NULL;
(void) line_number;
if (!stack)
exit(EXIT_FAILURE);
new = malloc(sizeof(stack_t));
if (!new)
{
fprintf(stderr, "Error: malloc failed\n");
exit(EXIT_FAILURE);
}
if (stainst.token == NULL || !stack)
{
fprintf(stderr, "L%u: usage: push integer\n", line_number);
exit(EXIT_FAILURE);
}
new->n = stainst.number;
new->next = *stack;
new->prev = NULL;
if (new->next != NULL)
(new->next)->prev = new;
*stack = new;
}
/**
* pall_function - adds a new node at the beginning of a dlistint_t list.
* @stack: stack
* @line_number: line number
* Return: void
*/
void pall_function(stack_t **stack, unsigned int line_number)
{
stack_t *aux = NULL;
(void) line_number;
aux = *stack;
while (aux)
{
printf("%i\n", aux->n);
aux = aux->next;
}
}
/**
* pint_function - adds a new node at the beginning of a dlistint_t list.
* @stack: stack
* @line_number: line number
* Return: void
*/
void pint_function(stack_t **stack, unsigned int line_number)
{
stack_t *aux = NULL;
if (!stack || !*stack)
{
fprintf(stderr, "L%u: can't pint, stack empty\n", line_number);
exit(EXIT_FAILURE);
}
aux = *stack;
printf("%i\n", aux->n);
}
/**
* pop_function - adds a new node at the beginning of a dlistint_t list.
* @stack: stack
* @line_number: line number
* Return: void
*/
void pop_function(stack_t **stack, unsigned int line_number)
{
stack_t *aux = NULL;
if (!stack || !*stack)
{
fprintf(stderr, "L%u: can't pop an empty stack\n", line_number);
exit(EXIT_FAILURE);
}
aux = *stack;
*stack = (*stack)->next;
free(aux);
}
/**
* swap_function - adds a new node at the beginning of a dlistint_t list.
* @stack: stack
* @line_number: line number
* Return: void
*/
void swap_function(stack_t **stack, unsigned int line_number)
{
stack_t *aux = NULL;
if (!stack || !*stack || !(*stack)->next)
{
fprintf(stderr, "L%u: can't swap, stack too short\n", line_number);
exit(EXIT_FAILURE);
}
aux = *stack;
aux = (*stack)->next;
(*stack)->prev = (*stack)->next;
(*stack)->next = aux->next;
aux->prev = NULL;
if (aux->next)
aux->next->prev = *stack;
aux->next = *stack;
*stack = (*stack)->prev;
}
|
C
|
#define _POSIX_C_SOURCE 1
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <strings.h>
#include <stdarg.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
#include <unistd.h>
#include "yjson.h"
char ySymbolStr[][10] = {"null", "true", "false"};
int _debug = 0;
int _calllevel = 0;
void debug(const char *fmt, ...)
{
if (_debug <= 0) {
return;
}
static int spacecnt = 2;
va_list args;
va_start(args, fmt);
int i;
for (i = 0; i < _calllevel * spacecnt; i++) {
putchar(' ');
}
vprintf(fmt, args);
// auto add newline char
size_t len = strlen(fmt);
if (len != 0 && fmt[len - 1] != '\n') {
putchar('\n');
}
va_end(args);
}
enum {
dev_unknown,
dev_tty,
dev_file,
};
int gTypeTTY = dev_unknown;
char *CtrlRed = "\033[0;31m";
char *CtrlReset = "\033[0;m";
char *prefix = "";
char *suffix = "";
void error(const char *fmt, ...)
{
if (gTypeTTY == dev_unknown) {
gTypeTTY = isatty(fileno(stderr)) ? dev_tty: dev_file;
if (gTypeTTY == dev_tty) {
prefix = CtrlRed;
suffix = CtrlReset;
}
}
fprintf(stderr, "%s", prefix);
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fprintf(stderr, "%s", suffix);
if (fmt[strlen(fmt) - 1] != '\n') {
fprintf(stderr, "\n");
}
}
void disabledebug()
{
_debug = 0;
}
void enabledebug()
{
_debug = 1;
}
void yHeadInit(yTypeHead *h, yMeta meta)
{
h->meta = meta;
}
enum {
sObjectBegin = '{',
sObjectEnd = '}',
sObjectDelt = ':',
sArrayBegin = '[',
sArrayEnd = ']',
sDelimeter = ',',
sStringBE = '"',
sStringTrans = '\\',
sStringTerm = '\0',
};
typedef void (*yTypeFn) (yType *);
typedef yType * (*yTypeParseFn) (char *, int *);
typedef struct {
int size;
yTypeFn init;
yTypeFn display;
} yTypeMap;
void yDisplayRecur(yType *p);
void yStringDisp(yType *p)
{
printf("\"%s\"", ((yString *)p)->s);
}
void yObjectDisp(yType *p)
{
yObjectNode *pp = ((yObject *)p)->node;
putchar(sObjectBegin);
while (pp != NULL) {
yStringDisp((yType *)pp->key);
putchar(sObjectDelt);
yDisplayRecur(pp->value);
pp = (yObjectNode *)pp->next;
if (pp == NULL) {
break;
}
printf("%c ", sDelimeter);
}
putchar(sObjectEnd);
}
void yArrayDisp(yType *p)
{
putchar(sArrayBegin);
yArrayNode *pp = ((yArray *)p)->node;
while (pp != NULL) {
yDisplayRecur(pp->elm);
pp = (yArrayNode *)pp->next;
if (pp == NULL) {
break;
}
printf("%c ", sDelimeter);
}
putchar(sArrayEnd);
}
void yNumberDisp(yType *p)
{
printf("%.3f", ((yNumber *)p)->n);
}
void ySymbolDisp(yType *p)
{
printf("%s", ySymbolStr[((ySymbol *)p)->val]);
}
yTypeMap map[] = {
[eInvalid] = {0, NULL, NULL},
[eObject] = {sizeof(yObject), NULL, yObjectDisp},
[eArray] = {sizeof(yArray), NULL, yArrayDisp},
[eString] = {sizeof(yString), NULL, yStringDisp},
[eNumber] = {sizeof(yNumber), NULL, yNumberDisp},
[eArrayNode] = {sizeof(yArrayNode), NULL, NULL},
[eSymbol] = {sizeof(ySymbol), NULL, ySymbolDisp},
[eObjectNode] = {sizeof(yObjectNode), NULL, NULL},
};
void *yAlloc(yMeta meta)
{
size_t len = map[meta].size;
yTypeHead *p = (yTypeHead *)malloc(len);
bzero(p, len);
if (meta != eArrayNode || meta != eObjectNode) {
yHeadInit(p, meta);
}
return p;
}
void yFree(yType *p)
{
// TODO:
// need free child-pointer and next-pointer
if (p != NULL) {
free(p);
}
}
void yDisplayRecur(yType *p)
{
yTypeFn fn = map[p->meta].display;
if (fn != NULL) {
fn(p);
} else {
printf("cannot display %p", p);
}
}
void yDisplay(void *p)
{
if (p == NULL) {
printf("nil");
return;
}
yType *pType = (yType *)p;
yDisplayRecur(pType);
putchar('\n');
}
int yParseDigit(char *s, size_t *oStep)
{
char *crs = s;
int v = 0;
while (isdigit(*crs)) {
v = (*crs - '0') + 10 * v;
crs++;
}
*oStep = crs - s;
return v;
}
int yParseInt(char *s, size_t *oStep)
{
char *crs = s;
int v = 0;
int sym = 1;
size_t step;
if (*crs == '-') {
sym = -1;
crs++;
} else if (*crs == '+') {
sym = 1;
crs++;
}
v = yParseDigit(crs, &step);
v = sym * v;
crs += step;
*oStep = crs - s;
return v;
}
double yParseNumber(char *s, size_t *oStep)
{
char *crs = s;
double v, ret;
size_t step;
ret = yParseInt(crs, &step);
crs += step;
if (*crs == '.') {
crs++;
v = yParseDigit(crs, &step);
v = v / pow(10, step);
if (ret >= 0) {
ret += v;
} else {
ret -= v;
}
crs += step;
}
if (*crs == 'e' || *crs == 'E') {
crs++;
v = yParseInt(crs, &step);
ret *= pow(10, v);
crs += step;
}
*oStep = crs - s;
return ret;
}
char transMap(char c)
{
static char Map[2][20] = {"\"\\/bfnrt", "\"\\/\b\f\n\r\t"};
size_t j;
char ret;
for (j = 0; j < sizeof(Map[0]); j++) {
if (c == Map[0][j]) {
ret = Map[1][j];
break;
}
}
return ret;
}
char *yParseString(char *s, size_t *oStep)
{
char *o = s;
int trans = 0;
while (!(*s == sStringBE && trans == 0)) {
if (*s == sStringTrans && trans == 0) {
trans = 1;
} else if (trans == 1) {
trans = 0;
}
s++;
}
*oStep = s - o;
char *ret = (char *)malloc(sizeof(*oStep));
size_t i, f;
for (i = 0, f = 0; f < *oStep; i++, f++) {
if (o[f] == sStringTrans) {
f++;
ret[i] = transMap(o[f]);
} else {
ret[i] = o[f];
}
}
ret[i] = sStringTerm;
return ret;
}
ySymbolVal yParseSymbol(char *s, size_t *oStep)
{
ySymbolVal v = ysInvalid;
size_t i;
for (i = 0; i < sizeof(ySymbolStr) / sizeof(ySymbolStr[0]); i++) {
if (strncasecmp(s, ySymbolStr[i], strlen(ySymbolStr[i])) == 0) {
v = i;
*oStep = strlen(ySymbolStr[i]);
break;
}
}
return v;
}
yNumber *ykParseNumber(char *s, size_t *oStep)
{
double d = yParseNumber(s, oStep);
yNumber *p = (yNumber *)yAlloc(eNumber);
p->n = d;
return p;
}
yString *ykParseString(char *crs, size_t *oStep)
{
crs++;
char *str = yParseString(crs, oStep);
yString *p = yAlloc(eString);
p->s = str;
*oStep += 2;
return p;
}
void forwardSpace(char **s)
{
while (isspace(**s)) {
(*s)++;
}
}
yArray *ykParseArray(char *crs, size_t *oStep)
{
char *o = crs;
crs++;
size_t step = 0;
yArray *pa = yAlloc(eArray);
yArrayNode **tail = &(pa->node);
while (*crs != sArrayEnd) {
yArrayNode *pn = yAlloc(eArrayNode);
pn->elm = yParse(crs, &step);
crs += step;
*tail = pn;
tail = (yArrayNode **)&(pn->next);
forwardSpace(&crs);
if (*crs == sDelimeter) {
crs++;
continue;
}
}
*oStep = crs - o + 1;
tail = NULL;
return pa;
}
yObject *ykParseObject(char *crs, size_t *oStep)
{
char *o = crs;
crs++;
yObject *po = yAlloc(eObject);
size_t step;
yObjectNode **tail = &(po->node);
while (*crs != sObjectEnd) {
yObjectNode *pn = yAlloc(eObjectNode);
pn->key = yParse(crs, &step);
crs += step;
forwardSpace(&crs);
if (*crs == sObjectDelt) {
crs++;
} else {
error("error: cannot find sObjectDelt");
return NULL;
}
pn->value = yParse(crs, &step);
crs += step;
*tail = pn;
tail = (yObjectNode **)&(pn->next);
forwardSpace(&crs);
if (*crs == sDelimeter) {
crs++;
continue;
}
}
crs++;
*oStep = crs - o;
tail = NULL;
return po;
}
ySymbol *ykParseSymbol(char *crs, size_t *oStep)
{
size_t step;
ySymbolVal v = yParseSymbol(crs, &step);
if (v != ysInvalid) {
ySymbol *p = yAlloc(eSymbol);
p->val = v;
*oStep = step;
return p;
} else {
error("error: unknown %p %s", crs, crs);
return NULL;
}
}
void *yParse(char *s, size_t *oStep)
{
char *crs = s;
size_t step;
void *p;
while (1) {
forwardSpace(&crs);
if (*crs == sStringTerm) {
break;
} else if (*crs == sObjectBegin) {
p = ykParseObject(crs, &step);
break;
} else if (*crs == sArrayBegin) {
p = ykParseArray(crs, &step);
break;
} else if (*crs == sStringBE) {
p = ykParseString(crs, &step);
break;
} else if (isdigit(*crs) || *crs == '+' || *crs == '-') {
p = ykParseNumber(crs, &step);
break;
} else {
p = ykParseSymbol(crs, &step);
break;
}
}
crs += step;
if (oStep != NULL) {
*oStep = crs - s;
}
return p;
}
|
C
|
/*
PROGRAMMER: khoa Tran
b. COURSE: CSCI 3133.01
c. DATE: feb 6, 2014
d. ASSIGNMENT: program 2
e. ENVIRONMENT: window 7, visual studio 2012
f. FILES INCLUDED: Visual studio 2012
h. INPUT: Allow your application to select the type of account and enter the number of checks written. The application should compute and display the banks service fees for the month
i. PRECONDITIONS: Input validation: Do not accept a negative value for the number of checks written
j. OUTPUT: All checks for the month are assigned the same charge, based on the total number of checks written during the month.
k. POSTCONDITIONS: Input validation: Do not accept a negative value for the number of checks written
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int menuchoice;
printf( "Menu choices\n");
printf( "<1> Checking\n");
printf( "<2> Money-Market\n\n");
printf("Please enter 1 for Checking or 2 for Money-Market:\n");
scanf_s("%d", &menuchoice);
if (menuchoice == 1)
{
printf("\nChecking Account\n");
printf("Your Total Charge is $15.00\n\n");
printf("--------------------------------------------------------------------------------");
return main();
}
if (menuchoice == 2)
{
float mm = 10;
int check;
printf("\nMoney-Market\n");
printf("Please Enter number of checks: ");
scanf_s("%d", &check);
if (check > 0 && check < 20)
{
float a = 0.1;
float total = mm + check*a;
printf("\nYour Total Charge = $%.2f\n\n",total);
printf("--------------------------------------------------------------------------------");
}
if (check >= 20 && check < 39)
{
float b = 0.08;
float total = mm + check*b;
printf("\nYour Total Charge = $%.2f\n\n",total);
printf("--------------------------------------------------------------------------------");
}
if (check >= 40 && check < 59)
{
float c = 0.06;
float total = mm + check*c;
printf("\nYour Total Charge = $%.2f\n\n",total);
printf("--------------------------------------------------------------------------------");
}
if (check >= 60)
{
float d = 0.04;
float total = mm + check*d;
printf("\nYour Total Charge = $%.2f\n\n",total);
printf("--------------------------------------------------------------------------------");
}
else if (check < 0)
{
printf("\nINVALID number of check please check your input\n\n");
printf("--------------------------------------------------------------------------------");
}// validation for input number of checks
return main();
}
if (menuchoice != 2 && menuchoice != 1)
{
printf("\nINVALID Choice please pick a valid option\n\n");
return main();
}//validation for input choices
system("pause");
return 0;
}
|
C
|
#include <stdio.h>
void temperatura_msemana(int n, int m, int matriz[n][m]){
int i;
int j;
int suma_temp=0;
float temp_media_Semana=0;
for (i=0; i<n;i++){
for(j=0; j<m; j++){
suma_temp= matriz[i][j] + suma_temp;
}
}
temp_media_Semana = (suma_temp /(168));
printf("la temperatura media de la semana fue %.2f °C\n",temp_media_Semana);
}
void tmp_media_c_dia(int n, int m, int matriz[n][m]){
int i;
int j;
float tmp_md1=0;
int suma_tmpd1=0;
float tmp_md2=0;
int suma_tmpd2=0;
float tmp_md3=0;
int suma_tmpd3=0;
float tmp_md4=0;
int suma_tmpd4=0;
float tmp_md5=0;
int suma_tmpd5=0;
float tmp_md6=0;
int suma_tmpd6=0;
float tmp_md7=0;
int suma_tmpd7=0;
int cont=0;
for (i=0; i<1; i++){
for(j=0; j<m; j++){
suma_tmpd1= matriz[i][j] + suma_tmpd1;
}
}
tmp_md1 = (suma_tmpd1 /(7));
printf("la temperatura media del día %d fue %.2f °C\n", i+1, tmp_md1);
for (i=1; i<2; i++){
for(j=0; j<m; j++){
suma_tmpd2= matriz[i][j] + suma_tmpd2;
}
}
tmp_md2 = (suma_tmpd2 /(7));
printf("la temperatura media del día %d fue %.2f °C\n", i+1, tmp_md2);
for (i=2; i<3; i++){
for(j=0; j<m; j++){
suma_tmpd3= matriz[i][j] + suma_tmpd3;
}
}
tmp_md3 = (suma_tmpd3 /(7));
printf("la temperatura media del día %d fue %.2f °C\n", i+1, tmp_md3);
for (i=3; i<4;i++){
for(j=0; j<m; j++){
suma_tmpd4= matriz[i][j] + suma_tmpd4;
}
}
tmp_md4 = (suma_tmpd4/7);
printf ("la temperatura media del día %d fue %.2f °C\n", i+1, tmp_md4);
for (i=4; i<5; i++){
for(j=0; j<m; j++){
suma_tmpd5= matriz[i][j] + suma_tmpd5;
}
}
tmp_md5 = (suma_tmpd5 /(7));
printf("la temperatura media del día %d fue %.2f °C\n", i+1, tmp_md5);
for (i=5; i<6;i++){
for(j=0; j<m; j++){
suma_tmpd6= matriz[i][j] + suma_tmpd6;
}
}
tmp_md6 = (suma_tmpd6 /(7));
printf("la temperatura media del día %d fue %.2f °C\n", i+1, tmp_md6);
for (i=6; i<7;i++){
for(j=0; j<m; j++){
suma_tmpd7= matriz[i][j] + suma_tmpd7;
}
}
tmp_md7 = (suma_tmpd7 /(7));
printf("la temperatura media del día %d fue %.2f °C\n", i+1, tmp_md7);
if (tmp_md1>30)
cont++;
if (tmp_md2>30)
cont++;
if (tmp_md3>30)
cont++;
if (tmp_md4>30)
cont++;
if (tmp_md5>30)
cont++;
if(tmp_md6>30)
cont++;
if(tmp_md7>30)
cont++;
printf("número de días en que la temperatura media fue mayor a 30 °C: %d\n", cont);
}
void
temp_minima(int n, int m, int matriz[n][m]){
int i;
int j;
int menor= 50;
int minima[n];
for (i=0; i<n; i++){
menor=50;
for (j=0; j<m; j++){
if (menor>matriz[i][j]){
menor=matriz[i][j];
}
}
minima[i] = menor;
printf ("\nLa menor temperatura del dia %d es %d °C", i+1, menor);
}
printf ("\n");
for (i=0; i<n;i++){
if (menor>minima[i]){
menor=minima[i];
}
}
printf ("\nLa menor temperatura de la semana es %d °C\n", menor);
}
void temp_maxima(int n, int m, int matriz[n][m]){
int maxima[n];
int i;
int j;
int mayor=0;
for (i=0; i<n; i++){
mayor=0;
for (j=0; j<m; j++){
if (mayor<matriz[i][j]){
mayor= matriz[i][j];
}
}
maxima[i] = mayor;
printf ("\nLa mayor temperatura del dia %d es %d °C", i+1, mayor);
}
for (i=0; i<n;i++){
if (mayor<maxima[i]){
mayor=maxima[i];
}
}
printf ("\n\nLa mayor temperatura de la semana es %d °C\n", mayor);
}
int main()
{
int n=7;
int m=24;
int matriz[n][m];
int i;
int j;
for(i=0; i<n; i++){
for (j=0; j<m; j++){
printf( "ingrese la temperatura de la hora %d del día %d en grados centigrados:\n", j+1,i+1);
scanf("%d",& matriz [i][j]);
}
}
temperatura_msemana(n,m,matriz);
tmp_media_c_dia(n,m, matriz);
temp_maxima(n,m,matriz);
temp_minima(n,m,matriz);
return 0;
}
|
C
|
#ifndef MSOLVER_H
#define MSOLVER_H
#include<cstdint>
//given a board and total number of mines,
//if this game is consistent
// set prob to MAX_PROB * (probability of a corresponding tile to be a mine)
// and return true
//elsewise return false
//_board: 0~8 is numbers, anything else is unknown
bool MSolve(int32_t _width,int32_t _height,int32_t _mines,const int8_t *_board,int32_t *prob);
//given a (back-)board and initial open position,
//return true if this game is guess free
//elsewise return false
//_board: 0~8 is numbers, anything else is mines
//should be self-consistent, and total number of mines is known and correct
bool MSolve(int32_t _width,int32_t _height,const int8_t *_board,int32_t initx,int32_t inity);
//Compare mine map to pre-computed must-guess configurations
//And adjust must-guess patch of the map to try to avoid guess
//return true if guess is required and adjusting is failed
//note: when false is returned, game is not guaranteed to be guess-free
bool MustGuess(int32_t _width,int32_t _height,int8_t *_board,int32_t initx,int32_t inity);
#endif
|
C
|
#include <stdio.h>
// 使用结构体(struct)将两个复数相加。
typedef struct complex
{
float real;
float imag;
} complex;
complex add(complex n1, complex n2);
int main(int argc, char const *argv[])
{
complex n1, n2, temp;
printf("The first complex: \n");
printf("Input the real and imag: \n");
scanf("%f %f", &n1.real, &n1.imag);
printf("The second complex: \n");
printf("Input the second real and imag: \n");
scanf("%f %f", &n2.real, &n2.imag);
temp = add(n1, n2);
printf("Sum = %.1f + %.1fi", temp.real, temp.imag);
return 0;
}
complex add(complex n1, complex n2)
{
complex temp;
temp.real = n1.real + n2.real;
temp.imag = n1.imag + n2.imag;
return temp;
}
|
C
|
#include <signal.h>
#include <assert.h>
#include "sr_nat.h"
#include "sr_protocol.h"
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int sr_nat_init(struct sr_nat *nat) { /* Initializes the nat */
assert(nat);
/* Acquire mutex lock */
pthread_mutexattr_init(&(nat->attr));
pthread_mutexattr_settype(&(nat->attr), PTHREAD_MUTEX_RECURSIVE);
int success = pthread_mutex_init(&(nat->lock), &(nat->attr));
/* Initialize timeout thread */
pthread_attr_init(&(nat->thread_attr));
pthread_attr_setdetachstate(&(nat->thread_attr), PTHREAD_CREATE_JOINABLE);
pthread_attr_setscope(&(nat->thread_attr), PTHREAD_SCOPE_SYSTEM);
pthread_attr_setscope(&(nat->thread_attr), PTHREAD_SCOPE_SYSTEM);
pthread_create(&(nat->thread), &(nat->thread_attr), sr_nat_timeout, nat);
/* CAREFUL MODIFYING CODE ABOVE THIS LINE! */
nat->mappings = NULL;
nat->icmp_query = 60;
nat->tcp_establish = 7440;
nat->tcp_transitory = 300;
nat->port_id = 0;
nat->nat_external_ip = 0;
/* Initialize any variables here */
return success;
}
int sr_nat_destroy(struct sr_nat *nat){
/* Destroys the nat (free memory) */
pthread_mutex_lock(&(nat->lock));
/* free nat memory here */
/* declare mapping variable */
struct sr_nat_connection *currentConns;
struct sr_nat_connection *wasteConns;
struct sr_nat_mapping *wasteMapping;
struct sr_nat_mapping *current = nat->mappings;
while(current)
{
currentConns = current->conns;
while(currentConns)
{
wasteConns = currentConns;
currentConns = currentConns->next;
free(wasteConns);
}
wasteMapping = current;
current = current->next;
free(wasteMapping);
}
pthread_kill(nat->thread, SIGKILL);
return pthread_mutex_destroy(&(nat->lock)) &&
pthread_mutexattr_destroy(&(nat->attr));
}
/*---------------------------------------------------------------------
* Method: sr_dismiss_mapping(struct sr_nat *, struct sr_nat_mapping *,
* struct sr_nat_mapping *);
* Scope: Local
*
* If cur is the first mapping, then prev must be NULL. Hence,
* nat_mappings should be the next element of the cureent one.
* Otherwise, the next of prev should point the next mapping of
* the current one.
*
*---------------------------------------------------------------------*/
void sr_dismiss_mapping(struct sr_nat *nat, struct sr_nat_mapping *prev_map,struct sr_nat_mapping *cur_map){
if (prev_map == NULL){
nat->mappings = cur_map->next;
}else{
prev_map->next = cur_map->next;
}
}
void *sr_nat_timeout(void *nat_ptr) { /* Periodic Timeout handling */
struct sr_nat *nat = (struct sr_nat *)nat_ptr;
while (1) {
sleep(1.0);
pthread_mutex_lock(&(nat->lock));
time_t curtime = time(NULL);
struct sr_nat_mapping *prev_map = NULL;
struct sr_nat_mapping *cur_map = nat->mappings;
struct sr_nat_connection *cur_conn = NULL;
struct sr_nat_connection *prev_conn = NULL;
pthread_mutex_unlock(&(nat->lock));
while(cur_map){
pthread_mutex_lock(&(nat->lock));
if(cur_map->type == nat_mapping_icmp && nat->icmp_query < (curtime - cur_map->last_updated)){
sr_dismiss_mapping(nat, prev_map, cur_map);
/* Destroy the current mapping. */
struct sr_nat_mapping *exp_entry = cur_map;
cur_map = cur_map->next;
free(exp_entry);
continue;
}else if(cur_map->type == nat_mapping_tcp){
cur_conn = cur_map->conns;
while(cur_conn != NULL){
if(nat->tcp_establish < curtime - cur_conn->last_updated && cur_conn->state == established){
if(prev_conn){
prev_conn->next = cur_conn->next;
}else{
cur_map->conns = cur_conn->next;
if(cur_map->conns == NULL){
sr_dismiss_mapping(nat, prev_map, cur_map);
}
}
}else if (nat->tcp_transitory < curtime - cur_conn->last_updated){
if(prev_conn){
prev_conn->next = cur_conn->next;
}else{
cur_map->conns = cur_conn->next;
if(cur_map->conns == NULL){
sr_dismiss_mapping(nat, prev_map, cur_map);
}
}
}
prev_conn = cur_conn;
cur_conn = cur_conn->next;
}
}else{
prev_map = cur_map;
cur_map = cur_map->next;
}
pthread_mutex_unlock(&(nat->lock));
}
pthread_mutex_unlock(&(nat->lock));
}
return NULL;
}
/* Get the mapping associated with given external port.
You must free the returned structure if it is not NULL. */
struct sr_nat_mapping *sr_nat_lookup_external(struct sr_nat *nat,
uint16_t aux_ext, sr_nat_mapping_type type ) {
pthread_mutex_lock(&(nat->lock));
/* handle lookup here, malloc and assign to copy */
struct sr_nat_mapping *copy = NULL;
struct sr_nat_mapping *current = nat->mappings;
while(current){
if(current->type == type && current->aux_ext == aux_ext){
copy = malloc(sizeof(struct sr_nat_mapping));
copy->type = current->type;
copy->ip_int = current->ip_int;
copy->ip_ext = current->ip_ext;
copy->aux_int = current->aux_int;
copy->aux_ext = current->aux_ext;
copy->last_updated = current->last_updated;
copy->conns = current->conns;
copy->next = current->next;
pthread_mutex_unlock(&(nat->lock));
return copy;
}
current = current->next;
}
pthread_mutex_unlock(&(nat->lock));
return copy;
}
/* Get the mapping associated with given internal (ip, port) pair.
You must free the returned structure if it is not NULL. */
struct sr_nat_mapping *sr_nat_lookup_internal(struct sr_nat *nat,
uint32_t ip_int, uint16_t aux_int, sr_nat_mapping_type type ) {
pthread_mutex_lock(&(nat->lock));
/* handle lookup here, malloc and assign to copy. */
struct sr_nat_mapping *copy = NULL;
struct sr_nat_mapping *current = nat->mappings;
while(current){
if(current->type == type && current->ip_int == ip_int && current->aux_int == aux_int){
copy = malloc(sizeof(struct sr_nat_mapping));
copy->type = current->type;
copy->ip_int = current->ip_int;
copy->ip_ext = current->ip_ext;
copy->aux_int = current->aux_int;
copy->aux_ext = current->aux_ext;
copy->last_updated = current->last_updated;
copy->conns = current->conns;
copy->next = current->next;
pthread_mutex_unlock(&(nat->lock));
return copy;
}
current = current->next;
}
pthread_mutex_unlock(&(nat->lock));
return copy;
}
/* Insert a new mapping into the nat's mapping table.
Actually returns a copy to the new mapping, for thread safety.
*/
struct sr_nat_mapping *sr_nat_insert_mapping(struct sr_nat *nat,
uint32_t ip_int, uint16_t aux_int, sr_nat_mapping_type type ) {
/* Check Params */
assert(nat);
assert(ip_int);
assert(aux_int);
pthread_mutex_lock(&(nat->lock));
/* handle insert here, create a mapping, and then return a copy of it */
struct sr_nat_mapping *mapping = malloc(sizeof(struct sr_nat_mapping));
mapping->ip_int = ip_int;
mapping->aux_int = aux_int;
mapping->ip_ext = nat->nat_external_ip;
mapping->aux_ext = nat->port_id + 1024;
nat->port_id = ((nat->port_id + 1) % 64500);
mapping->last_updated = time(NULL);
mapping->conns = NULL;
mapping->type = type;
mapping->next = nat->mappings;
nat->mappings = mapping;
pthread_mutex_unlock(&(nat->lock));
return mapping;
}
/*---------------------------------------------------------------------
* Method: build_connections(sr_ip_hdr_t *, sr_tcp_hdr_t *)
* Scope: Local
*
* Find the matching connection in the connection list.
*
*---------------------------------------------------------------------*/
struct sr_nat_connection* sr_nat_lookup_connection(
struct sr_nat* nat,
struct sr_nat_mapping* mapping,
uint32_t ip_src, uint32_t ip_dest,
uint32_t src_seq,uint16_t port_dest){
assert(mapping);
pthread_mutex_lock(&(nat->lock));
struct sr_nat_connection* walker = mapping->conns;
while(walker != NULL){
if((ip_src == walker->ip_src) && (ip_dest == walker->ip_dest) && (src_seq == walker->src_seq) && (port_dest == walker->port_dest)){
pthread_mutex_unlock(&(nat->lock));
return walker;
}
walker = walker->next;
}
pthread_mutex_unlock(&(nat->lock));
return NULL;
}
/*---------------------------------------------------------------------
* Method: build_connections(sr_ip_hdr_t *, sr_tcp_hdr_t *)
* Scope: Local
*
* This method build connections in case of TCP protocol. In case of
* ICMP protocol, building connections is not required. Connections
* are set to be NULL.
*
* NOTE : ICMP protocol will not call this function.
*
*---------------------------------------------------------------------*/
struct sr_nat_connection *build_connections(sr_ip_hdr_t *ip_hdr, sr_tcp_hdr_t *tcp_hdr){
struct sr_nat_connection *conn = (struct sr_nat_connection *)malloc(sizeof(struct sr_nat_connection));
conn->ip_src = ip_hdr->ip_src;
conn->src_seq = tcp_hdr->sequence_num;
conn->ip_dest = ip_hdr->ip_dst;
conn->port_dest = tcp_hdr->dest_port;
conn->last_updated = time(NULL);
conn->state = syn_sent;
conn->next = NULL;
return conn;
}
|
C
|
#include "stdio.h"
#include "conio.h"
void main ()
{
/* Variable/Function prototype Declaration */
char source[25];
char target[25];
void mystrcp (char *,char *);
int mystrlen (char *);
/*Main Program*/
clrscr();
printf ("Enter String to be copied less than 25 Char:");
gets(source);
mystrcp (source,target);
printf ("Copied string is %s",target);
}
/* String Copy Function */
void mystrcp (char *s,char *t)
{
int i;
int len;
len=mystrlen(s);
for (i = 0; i <= (len-1);i++)
{
*t = *s;
s++;
t++;
}
}
/* String length Function */
int mystrlen (char *p)
{
int x = 0;
while (1)
{
if (*p == '\0')
{
break;
}
else
{
x++;
p++;
}
}
return x;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <sys/queue.h>
#include "utils.h"
#include "config.h"
static TAILQ_HEAD(config_list, cfg_element) config_list = TAILQ_HEAD_INITIALIZER(config_list);
typedef struct cfg_element {
char *name;
char *value;
TAILQ_ENTRY(cfg_element) list;
} cfg_element_t;
static cfg_element_t *get_elem(const char *name)
{
cfg_element_t *e = NULL;
if (name == NULL)
return NULL;
TAILQ_FOREACH(e, &config_list, list) {
if (!strcmp(e->name, name))
return e;
}
return NULL;
}
static int add_elem(const char *name, const char *value)
{
cfg_element_t *e = NULL;
if (name == NULL || value == NULL)
return -1;
e = get_elem(name);
if (e == NULL) {
e = calloc(1, sizeof(cfg_element_t));
if (e == NULL)
return -1;
e->name = strdup(name);
e->value = NULL;
TAILQ_INSERT_TAIL(&config_list, e, list);
}
if (e->value != NULL) {
free(e->value);
e->value = NULL;
}
e->value = strdup(value);
return 0;
}
static void clear_space(char **p)
{
char *n = *p;
if (*n == 0)
return;
for(; *n == ' '; n++);
*p = n;
for(; *n; n++);
n--;
for(; *n == ' '; n--)
*n = 0;
}
static int parse_elem(char *buf, char **name, char **value)
{
char *n, *v;
if (buf == NULL || name == NULL || value == NULL)
return -1;
for(n = buf; *n != 0 && *n != '\r' && *n != '\n' && *n != '#'; ++n);
*n = 0;
v = strchr(buf, '=');
if (v == NULL)
return -1;
*v = 0;
v++;
*name = buf;
*value = v;
clear_space(name);
clear_space(value);
if (strlen(*name) == 0 || strlen(*value) == 0)
return -1;
return 0;
}
int read_config(const char *filename)
{
FILE *fp = NULL;
int ret = -1;
char buf[1024] = { 0 };
char *name = NULL, *value = NULL;
if (filename == NULL)
goto bail;
if ((fp = fopen(filename, "r")) == NULL) {
goto bail;
}
while (!feof(fp)) {
if (fgets(buf, sizeof(buf), fp) == NULL)
continue;
if (parse_elem(buf, &name, &value) != 0) {
printf("could not parse '%s'\n", buf);
continue;
}
if (add_elem(name, value) != 0) {
printf("could not add '%s'='%s'\n", name, value);
continue;
}
}
ret = 0;
bail:
if (fp != NULL)
fclose(fp);
return ret;
}
void free_config(void)
{
cfg_element_t *e, *n;
TAILQ_FOREACH_SAFE(e, &config_list, list, n) {
TAILQ_REMOVE(&config_list, e, list);
if (e->value != NULL)
free(e->value);
if (e->name != NULL)
free(e->name);
free(e);
}
}
char *get_config(const char *name)
{
cfg_element_t *e;
e = get_elem(name);
if (e != NULL)
return e->value;
return NULL;
}
char *get_config_safe(const char *name)
{
char *value = get_config(name);
if (value != NULL)
return value;
return "";
}
|
C
|
//shapes.h - header file containing shape info for ncurses tetris program
#define ABOVE -1
#define BELOW 1
#define RIGHT 1
#define LEFT -1
#define INLINE 0
typedef struct state {
int oldstate;
int newstate;
} board;
int shapes[144] = //shape maps, grouped as units of 3, doublets indicating position relative to element 0 of the shape. 4 sets/shape correspond to possible rotations.
{
ABOVE, INLINE, // ##
ABOVE, LEFT, // ##
INLINE, LEFT, //
ABOVE, INLINE, //
ABOVE, LEFT, //
INLINE, LEFT, // SQUARE IS A SPECIAL CASE: REMAINS THE SAME.
ABOVE, INLINE, //
ABOVE, LEFT, //
INLINE, LEFT, //
ABOVE, INLINE, //
ABOVE, LEFT, //
INLINE, LEFT,
ABOVE, INLINE, // #
BELOW, INLINE, // 0
BELOW, RIGHT, // ##
INLINE, RIGHT, //
INLINE, LEFT, // #0#
BELOW, LEFT, // #
BELOW, INLINE, // ##
ABOVE, INLINE, // 0
ABOVE, LEFT, // #
INLINE, LEFT, // #
INLINE, RIGHT, // #0#
ABOVE, RIGHT //
, //ELL
ABOVE, LEFT, // #
INLINE, LEFT, // #0
BELOW, INLINE, // #
ABOVE, RIGHT, // ##
ABOVE, INLINE, // #0
INLINE, LEFT, //
BELOW, RIGHT, // #
INLINE, RIGHT, // 0#
ABOVE, INLINE, // #
BELOW, LEFT, //
BELOW, INLINE, // 0#
INLINE, RIGHT // ##
, //ESS
-2, INLINE, // LINE IS A SPECIAL CASE - HAS TWO PERMUTATIONS:
ABOVE, INLINE, //
BELOW, INLINE, // #
INLINE, 2, // #
INLINE, RIGHT, // 0
INLINE, LEFT, // #
-2, INLINE, //
ABOVE, INLINE, // #0##
BELOW, INLINE, //
INLINE, 2, //
INLINE, RIGHT, //
INLINE, LEFT //
, //LINE
ABOVE, RIGHT, // #
INLINE, RIGHT, // 0#
BELOW, INLINE, // #
BELOW, RIGHT, //
BELOW, INLINE, // #0
INLINE, LEFT, // ##
BELOW, LEFT, // #
INLINE, LEFT, // #0
ABOVE, INLINE, // #
ABOVE, LEFT, // ##
ABOVE, INLINE, // 0#
INLINE, RIGHT //
, //ZED
INLINE, LEFT, // #
INLINE, RIGHT, // #0#
ABOVE, INLINE, //
ABOVE, INLINE, // #
BELOW, INLINE, // 0#
INLINE, RIGHT, // #
INLINE, RIGHT, //
INLINE, LEFT, // #0#
BELOW, INLINE, // #
BELOW, INLINE, // #
ABOVE, INLINE, // #0
INLINE, LEFT // #
//TEE
};
|
C
|
#include<stdio.h>
#include<math.h>
int x[20], ansNum;
int main()
{
int n,i,j;
void NQueen(int k,int n);
printf("\n\nEnter the number of Queen for n Queen Problem: ");
scanf("%d",&n);
NQueen(1,n);
printf("\n\n");
return 0;
}
void print(int n)
{
int i,j;
printf("\n\nAnswer %d: \n", ++ansNum);
printf("(");
for(i=1;i<=n;i++)
{
if(i!=n)
printf("%d, ", x[i]);
else
printf("%d", x[i]);
}
printf(")");
}
int place(int k,int column)
{
int i;
for(i=1;i<=k-1;++i)
{
if((x[i]==column) || (abs(x[i]-column)==abs(i-k)))
return 0;
}
return 1;
}
void NQueen(int k,int n)
{
int column;
for(column=1;column<=n;++column)
{
if(place(k,column))
{
x[k]=column;
if(k==n)
print(n);
else
NQueen(k+1,n);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.