language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include<stdio.h>
#include<stdlib.h>
void main()
{
float a,b,c;
char o;
printf("enter a,o,b \n");
scanf("%f%s%f",&a,&o,&b);
switch(0)
{
case '+':z=a+b;
printf("res=%f",z);
break;
case '-':z=a-b;
printf("res=%f",z);
break;
case '*':z=a*b;
printf("res=%f",z);
break;
case '/':z=a/b;
printf("res=%f",z);
break;
default :printf("invalid option ");
}
|
C
|
#include <stdio.h>
static int assert_fail(const char* s, unsigned l)
{
printf("assertion failed in line %u: '%s'\n", l, s);
return 0;
}
#define ASSERT(expr) ((expr) ? 1 : assert_fail(#expr,__LINE__))
int test(int r) {
#if !defined(__i386__) && !defined(__x86_64__)
#if !defined(BYTE_ORDER) || !defined(LITTLE_ENDIAN)
return r;
#else
if (BYTE_ORDER != LITTLE_ENDIAN) return r;
#endif
#endif
/* little endian */
union { long l; unsigned char c[sizeof(long)]; } u;
u.l = 0; u.c[0] = 0x80;
r &= ASSERT(u.l == 128);
u.l = 0; u.c[sizeof(long)-1] = 0x80;
r &= ASSERT(u.l < 0);
return r;
}
int main() {
return test(1) != 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
char letterArray[100];
int letterArrLength;
int numWords;
/*I decided to make an array that stores all of the chars, spaces and newlines
included. letterArrLength stores the number of all chars in the array*/
void makeWordList (char *fileName){
/*makeWordList does two things: initializes the array with all 0's, and
copies all of the characters from the file, to the letterArray*/
int j;
for (j=0; j< sizeof(letterArray)/sizeof(int); j++){
letterArray[j] = 0;
//Here, all the elements in letterArray are set to zero.
}
FILE *inputFile = fopen(fileName, "r");
char ch;
int i = 0;
do {
ch = fgetc (inputFile);
if(ch != EOF){
letterArray[i] = ch;
i++;
}
} while (ch != EOF);
/*In the above loop, all chars, including spaces and newlines, are places in
the array*/
letterArrLength = i;
//letterArrLength is set to the last value of i which is the size of the array
fclose (inputFile);
}
/*
void printWordList(char** wordList){
//printWordList was used as a tool to print out the wordLists for testing
int i=0;
int j=0;
while(wordList[i][j] != '\0'){
while(wordList[i][j] != '\0'){
printf("%c", wordList[i][j]);
j++;
}
printf(" %c", wordList[i][j+1] );
j = 0;
i++;
printf("\n");
}
}*/
char **getWordList (){
/*getWordList uses malloc to allocate memory for the 2D array known as the
words. It also places every char from letterArray into the 2D array*/
char** words = (char**)malloc(sizeof(char*) * 10);
int j, i;
for(j=0; j<10; j++){
words[j] = (char*)malloc(sizeof(char*) * 10);
}
//The memory is allocated. I decided to have a 10x10 buffer.
for(i=0; i<10; i++){
for(j=0; j<10; j++){
words[i][j] = '\0';
}
}
/*All of the elements are set to \0 to make it easy for later functions to
know when the string ends on each word*/
i = 0;
j = 0;
int n = 0;
int lineNumber = '1';
while(n<letterArrLength){
if(letterArray[n] == ' '){
words[i][j+1] = lineNumber;
/*The lineNumber is stored on the same row as the word itsself. However,
there is a \0 separating the word from the lineNumber. In the array it
looks like this: 'n', 'a', 'h', '1', '\0', '3', '\0', '\0', ...*/
i++;
j=0;
} else if (letterArray[n] == '\n') {
words[i][j+1] = (char)( (int)lineNumber++ );
//The lineNumber increments every time the array has a newline.
i++;
j=0;
} else {
words[i][j] = letterArray[n];
j++;
}
n++;
}
numWords = i;
/*i equals to the number of rows in the 2D array. Therefore it is also
equivalent to the number of words. It is stored in the global variable.*/
return words;
}
int getNumWords (){
return numWords;
//returns from the global variable.
}
void freeWordList(char** wordList){
//Must free every time getWordList is called.
int i;
for(i=0; i<10; i++){
free(wordList[i]);
}
free(wordList);
}
void compareFiles (char *fileName1, char* fileName2)
{
char** wordList1;
char** wordList2;
makeWordList(fileName1);
wordList1 = getWordList();
int wordList1len = getNumWords();
makeWordList(fileName2);
wordList2 = getWordList();
int wordList2len = getNumWords();
int size;
if(wordList1len > wordList2len){
size = wordList1len;
} else {
size = wordList2len;
}
//The size is the number of words in the largest list.
int i;
char* word1;
char* word2;
char lineNumber1;
char lineNumber2;
for(i=0; i<size; i++){
/*This for loop compares every word in the lists, determines if they are
the same, different, or if a list is exhuasted*/
printf("Word #%d: ", i);
word1 = wordList1[i];
lineNumber1 = wordList1[i][strlen(word1)+1];
word2 = wordList2[i];
lineNumber2 = wordList2[i][strlen(word2)+1];
/*Since every lineNumber is stored with the word, I can collect it at the
start of the loop for use in the output.*/
if( strcmp(word1, word2) == 0){
printf("same in each file");
printf("\nOn Line %c In File %s: %s\n",
lineNumber1, fileName1, wordList1[i]);
printf("On Line %c In File %s: %s\n",
lineNumber2, fileName2, wordList2[i]);
/*This if statement shows if the words are the same.*/
} else if (i>wordList1len-1 || i>wordList2len-1) {
if(i>wordList1len-1){
printf("\nFile %s Exhuasted", fileName1);
printf("\nOn Line %c In File %s: %s\n",
lineNumber2, fileName2, wordList2[i]);
} else {
printf("\nOn Line %c In File %s: %s\n",
lineNumber1, fileName1, wordList1[i]);
printf("File %s Exhuasted\n", fileName2);
}
/*If either of the lists are past their lengths, then the output will
say so.*/
} else {
printf("\nOn Line %c In File %s: %s\n",
lineNumber1, fileName1, wordList1[i]);
printf("On Line %c In File %s: %s\n",
lineNumber2, fileName2, wordList2[i]);
}
/*The lineNumber is shown for each word in the list.*/
}
freeWordList(wordList1);
freeWordList(wordList2);
}
|
C
|
# include <stdio.h>
# include <stdlib.h>
struct block
{
int data;
struct block *left,*right;
}*root=NULL;
void insert(int ele);
void find(int ele,struct block **par,struct block **loc);
void delete_node(int ele);
void delete_leaf_node(struct block *par,struct block *loc);
void delete_child_node_ltorrt(struct block *par,struct block *loc);
void delete_child_node(struct block *par,struct block *loc);
void inorder(struct block*);
void preorder(struct block*);
void postorder(struct block*);
void main()
{
int ch,status=1,ele;
while(status==1)
{
printf("\n1.Insert,2.Delete,3.Inorder,4.Preorder,5.Postorder,6.EXIT");
scanf("\n%d",&ch);
switch(ch)
{
case 1:
{
printf("\nEnter ele:");
scanf("%d",&ele);
insert(ele);
break;
}
case 2:
{
printf("\nEnter ele:");
scanf("%d",&ele);
delete_node(ele);
break;
}
case 3:
{
if(root==NULL)
{
printf("\nTree is empty");
}
else
{
printf("\nInorder traversal:");
inorder(root);
}
break;
}
case 4:
{
if(root==NULL)
{
printf("\nTree is empty");
}
else
{
printf("\nPreorder traversal:");
preorder(root);
}
break;
}
case 5:
{
if(root==NULL)
{
printf("\nTree is empty");
}
else
{
printf("\nPostorder traversal:");
postorder(root);
}
break;
}
case 6:
{
status=0;
break;
}
default:
printf("\nSry,invalid choice!");
}
}
}
void insert(int ele)
{
struct block *par,*loc;
find(ele,&par,&loc);
if(loc!=NULL)
{
printf("\n%d already present",ele);
return;
}
struct block *temp=(struct block*)malloc(sizeof(struct block*));
temp->data=ele;
temp->left=NULL;
temp->right=NULL;
if(par==NULL)
{
root=temp;
printf("\n%d successfully inserted to BST",root->data);
return;
}
else
{
if(ele<par->data)
par->left=temp;
else
par->right=temp;
}
printf("\n%d successfully inserted to BST",ele);
}
void find(int ele,struct block **par,struct block **loc)
{
struct block *i,*i_s_par;
if(root==NULL)
{
*par=NULL;
*loc=NULL;
return;
}
if(root->data==ele)
{
*loc=root;
*par=NULL;
return;
}
if(ele<root->data)
i=root->left;
else
i=root->right;
i_s_par=root;
while(i!=NULL)
{
if(i->data==ele)
{
*loc=i;
*par=i_s_par;
return;
}
i_s_par=i;
if(ele>i->data)
i=i->right;
else
i=i->left;
}
*loc=NULL;
*par=i_s_par;
}
void delete_node(int ele)
{
struct block *par,*loc;
struct block *temp=(struct block*)malloc(sizeof(struct block*));
if(root==NULL)
{
printf("\nEmpty tree:");
return;
}
find(ele,&par,&loc);
if(loc==NULL)
{
printf("\n%d not in bst",ele);
return;
}
if(loc->left==NULL && loc->right==NULL)
{
delete_leaf_node(par,loc);
}
else if((loc->left!=NULL && loc->right==NULL)|| (loc->left==NULL && loc->right!=NULL))
{
delete_child_node_ltorrt(par,loc);
}
else
{
delete_child_node(par,loc);
}
temp->data=loc->data;
free(loc);
printf("\n%d deleted from BST",temp->data);
}
void delete_leaf_node(struct block *par,struct block *loc)
{
if(par==NULL)
{
root=NULL;
return;
}
else
{
if(par->left==loc)
par->left=NULL;
else
par->right=NULL;
}
}
void delete_child_node_ltorrt(struct block *par,struct block *loc)
{
struct block *temp;
if(loc->left!=NULL)
temp=loc->left;
else
temp=loc->right;
if(par==NULL)
root=temp;
else
{
if(par->left==loc)
par->left=temp;
else
par->right=temp;
}
}
void delete_child_node(struct block *par,struct block *loc)
{
struct block *i,*i_s_par,*parsuc,*suc;
i=loc->right;
i_s_par=loc;
while(i->left!=NULL)
{
i_s_par=i;
i=i->left;
}
suc=i;
parsuc=i_s_par;
if(suc->left==NULL && suc->right==NULL)
delete_leaf_node(parsuc,suc);
else
delete_child_node_ltorrt(parsuc,suc);
if(par==NULL)
root=suc;
else
{
if(par->left==loc)
par->left=suc;
else
par->right=suc;
}
suc->left=loc->left;
suc->right=loc->right;
}
void inorder(struct block *root)
{
if(root==NULL)
return;
inorder(root->left);
printf("\n%d",root->data);
inorder(root->right);
}
void preorder(struct block *root)
{
if(root==NULL)
return;
printf("\n%d",root->data);
preorder(root->left);
preorder(root->right);
}
void postorder(struct block *root)
{
if(root==NULL)
return;
postorder(root->left);
postorder(root->right);
printf("\n%d",root->data);
}
|
C
|
#ifndef PEOPLE_H_INCLUDED
#define PEOPLE_H_INCLUDED
struct S_Persona{
int id;
char nombre[32];
char apellido[32];
int edad;
};
typedef struct S_Persona Persona;
int parseData(char* fileName,Persona* arrayPersonas);
#endif //PEOPLE_H_INCLUDED
/** \brief Reseva espacio en meomoria para una nueva persona y la inicializa
*
* \param int age Edad de la persona
* \param int something Otros datos
* \return Person* Retorna un puntero a la persona o NULL en caso de error
*
*/
Persona* person_new ();
/** \brief Setea la edad de una persona recibida como parametro
* \param Person* this Puntero a la persona
* \param int age Edad de la persona
* \return void
*
*/
void person_setAge(Persona* this, int age) ;
/** \brief Obtiene la edad de una persona recibida como parametro
* \param Person* this Puntero a la persona
* \return int age Edad de la persona
*
*/
int person_getAge(Persona* this);
/** \brief Libera el espacio ocupado por una persona recibida como parametro
* \param Person* this Puntero a la persona
* \return void
*
*/
void person_free(Persona * this);
void person_setId(Persona* this, int id);
|
C
|
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
string answer[10];
int main()
{
for (int i = 0; i < 10; i++)
{
char text = get_char("Enter character: ");
answer[i] = text;
}
printf("%s\n", answer);
}
|
C
|
/*Median of sorted arrays*/
#include<stdio.h>
#include<malloc.h>
void getSortedArray(int arr[], int arr2[], int len){
printf("Enter the first array elements");
for (int i = 0; i < len; i++)
scanf("%d", &arr[i]);
printf("Enter the second array elements");
for (int i = 0; i < len; i++)
scanf("%d", &arr2[i]);
return;
}
int max(int x, int y){
return x > y ? x : y;
}
int min(int x, int y){
return x > y ? y : x;
}
int median(int arr[], int n)
{
if (n % 2 == 0)
return (arr[n / 2] + arr[n / 2 - 1]) / 2;
else
return arr[n / 2];
}
int getMedian(int ar1[], int ar2[], int n)
{
int m1; /* For median of ar1 */
int m2; /* For median of ar2 */
if (n <= 0)
return -1;
if (n == 1)
return (ar1[0] + ar2[0]) / 2;
if (n == 2)
return (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1])) / 2;
m1 = median(ar1, n); /* get the median of the first array */
m2 = median(ar2, n); /* get the median of the second array */
/* If medians are equal then return either m1 or m2 */
if (m1 == m2)
return m1;
/* if m1 < m2 then median must exist in ar1[m1....] and ar2[....m2] */
if (m1 < m2)
{
if (n % 2 == 0)
return getMedian(ar1 + n / 2 - 1, ar2, n - n / 2 + 1);
else
return getMedian(ar1 + n / 2, ar2, n - n / 2);
}
/* if m1 > m2 then median must exist in ar1[....m1] and ar2[m2...] */
else
{
if (n % 2 == 0)
return getMedian(ar2 + n / 2 - 1, ar1, n - n / 2 + 1);
else
return getMedian(ar2 + n / 2, ar1, n - n / 2);
}
}
int main() {
int len;
printf("Enter the length of the array");
scanf("%d", &len);
int *sortedArray1 = malloc(sizeof(int) * len);
int *sortedArray2 = malloc(sizeof(int) * len);
getSortedArray(sortedArray1, sortedArray2, len);
printf("\n\n%d",getMedian(sortedArray1, sortedArray2, len));
}
|
C
|
#include <stdio.h>
int main() {
char ch;
char* p;
char* q;
ch ='A';
p = &ch;
q = p;
*q = 'Z';
printf ("ch ִ : ch ==> %c \n\n", ch);
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "strutil.h"
#define FIN_STRING '\0'
/* ------------ Funciónes auxiliares a split ------------ */
// Función auxiliar para el cálculo del largo de un cadenas
// Recibe un cadenas y devuelve su largo sin contar el caracter
// de fin de cadena ('\0')
int str_largo( const char* cadenas ){
int contador = 0;
while( cadenas[contador] != FIN_STRING )
contador++;
return contador;
}
// Función auxiliar de copia de un cadenas
// Recibe un cadenas destino, donde se copiará una cantidad largo
// del cadenas que se reciba de origen
void str_copy( char* destino , const char* origen , int largo ){
for( int i = 0 ; i < largo ; i++ )
destino[i] = origen[i];
}
// Devuelve la cantidad de separadores en la cadena a separar,
// si la cadena no debe ser separada devuelve 1.
int split_identificar_cantidad( const char* cadena , char separador ){
int cant_separar = 1;
int contador = 0;
while( cadena[contador] != FIN_STRING ){
if( cadena[contador] == separador )
cant_separar++;
contador++;
}
return cant_separar;
}
// Devuelve un vector dinámico con la posición de cada
// separador de una cadena a separar
int* split_identificar_posiciones( const char* cadena , char separador , int cant_separar){
int* posiciones = malloc( sizeof(int) * (cant_separar +1) );
int contador = 0;
int pos_encontradas = 1;
posiciones[0] = 0;
while( cadena[contador] != FIN_STRING ){
if( cadena[contador] == separador ){
posiciones[pos_encontradas] = contador+1;
pos_encontradas++;
}
contador++;
}
posiciones[cant_separar] = contador+1;
return posiciones;
}
/* ============ Función split ============ */
// Recibe una cadena y un caracter separador
// Devuelve un array de cadenas cada una formada por cada parte
// de la cadena principal recibida que estuviera separada del resto
// de la cadena por el caracter separador
char** split( const char* cadena , char separador ){
if( !cadena ) return NULL;
int cant_separar = split_identificar_cantidad( cadena , separador );
int* posiciones_separar = split_identificar_posiciones( cadena , separador , cant_separar);
char** arr_cadenas = malloc( sizeof(char*)* (cant_separar +1) );
int largo_actual;
for( size_t i = 0 ; i < cant_separar ; i++ ){
largo_actual = posiciones_separar[i+1] - posiciones_separar[i];
arr_cadenas[i] = malloc( sizeof(char) * largo_actual );
str_copy( arr_cadenas[i] , &cadena[posiciones_separar[i]] , largo_actual );
arr_cadenas[i][largo_actual-1] = FIN_STRING;
}
arr_cadenas[cant_separar] = NULL;
free( posiciones_separar );
return arr_cadenas;
}
/* ============ Función join ============ */
// Recibe un array de cadenas y un caracter separador
// Devuelve una cadena alocada en memoria dinámica con las cadenas
// del array concatenadas separadas por el caracter separador
char* join( char** arr_cadenas , char separador ){
if( !arr_cadenas ) return NULL;
int cont = 0;
while( arr_cadenas[cont] != NULL )
cont++;
int* largo_cadenas = malloc( sizeof(int) * (cont+1) );
int largo_total = 0;
cont = 0;
largo_cadenas[0] = 0;
while( arr_cadenas[cont] != NULL ){
largo_cadenas[cont+1] = str_largo( arr_cadenas[cont] )+1;
largo_total += largo_cadenas[cont+1];
cont++;
}
char* cadena = malloc( sizeof(char) * (largo_total+1) );
cont = 0;
int pos_actual = 0;
while( arr_cadenas[cont] != NULL ){
pos_actual += largo_cadenas[cont];
str_copy( &cadena[pos_actual] , arr_cadenas[cont] , largo_cadenas[cont+1] );
cadena[pos_actual+largo_cadenas[cont+1]-1] = separador;
cont++;
}
if( largo_total > 0 )
cadena[largo_total-1] = FIN_STRING;
else
cadena[0] = FIN_STRING;
free( largo_cadenas );
return cadena;
}
/* ============ Función free_strv ============ */
// Libera el espacio de memoria asignado a un array de strings char**
void free_strv( char** arr_cadenas ){
if( !arr_cadenas ) return;
int contador = 0;
while( arr_cadenas[contador] != NULL ){
free( arr_cadenas[contador] );
contador++;
}
free( arr_cadenas );
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct Node
{
int val;
struct Node* left;
struct Node* right;
int bal;
};
struct BinTree
{
struct Node* root;
int size;
};
int getRand();
void seed();
struct BinTree* createTree();
struct Node* createNode(int v);
void addNode(struct BinTree* bt, int v);
void setNodeVals(struct BinTree* bt);
struct Node* findNode(struct BinTree* bt, int key);
struct Node* findNode_(struct Node* n, int key);
void deleteNode(struct BinTree* bt, int key);
void inOrderPrint(struct Node* root);
struct Node* inOrderSucc(struct BinTree* bt, struct Node* node);
|
C
|
/*
数组名称演示
*/
#include<stdio.h>
int main()
{
int arr[5]={};
int arr1[2][3]={};
// printf("arr是%p,&arr[0]是%p\n",arr,&arr[0]);
// printf("arr1是%p,arr1[0]是%p,&arr1[0][0]是%p\n",arr1,arr1[0],&arr1[0][0]);
printf("arr1是%p,&arr1[1][0]是%p\n",arr1,&arr1[1][0]);
return 0;
}
|
C
|
int searchInsert0(int *nums, int numsSize, int target) {
int left = 0;
int right = numsSize - 1;
int flag;
while (1) {
flag = left + (right - left) / 2;
if (nums[flag] == target) {
return flag;
}
if (flag == left ||
flag ==
right) { // 这有问题,结束的条件想清除,就是有相邻的两个数,一定会到小的数里面,可能是大的数,也可能没有。
if (nums[left] < target) {
return right;
} else {
return left;
}
}
if (nums[flag] > target) {
right = flag - 1;
} else {
left = flag + 1;
}
}
}
int searchInsert(int *nums, int numsSize, int target) {
int left = 0;
int right = numsSize - 1;
int flag;
while (1) {
flag = left + (right - left) / 2;
if (nums[flag] == target) {
return flag;
}
if (flag == left) {
if (nums[left] < target) {
if (nums[right] < target) {
return right + 1;
}
return right;
}
return left;
}
if (nums[flag] > target) {
right = flag - 1;
} else {
left = flag + 1;
}
}
}
// 官方就是要好,1. 用>>去除。2. 判断结束条件更优
int s_searchInsert(int *nums, int numsSize, int target) {
int left = 0, right = numsSize - 1, ans = numsSize;
while (left <= right) {
int mid = ((right - left) >> 1) + left;
if (target <= nums[mid]) {
ans = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return ans;
}
|
C
|
/* Name: Lucius Gao
* CNET: luciusgao2001
* CS 152, Winter 2020
* bst.h
*/
#ifndef BST_H
#define BST_H
typedef struct _node{
void* data;
struct _node* left;
struct _node* right;
}node;
typedef struct{
node* root;
int (*cmp)(const void* x, const void* y);
}bst;
/* ******* BST ******** */
/* These functions are what programmers using the BST would use */
/* bst_new:
* Purpose: create a new bst, initialize its root to be NULL
* inputs:
* int (*cmp)(const void* x, const void* y) a pointer to a comparing
* function
* return value:
* a bst pointer
*/
bst* bst_new(int (*cmp)(const void* x, const void* y));
/* bst_insert:
* purpose: insert a new node to the bst
* inputs:
* bst* b: a pointer to the root of the bst
* void *data: a node holding data to be inserted into the bst
* return value:
* none, just changes the bst
*/
void bst_insert(bst* b, void* data);
/* bst_search
* purpose: search for a node wih data in a bst
*.inputs:
* bst *b: a pointer pointing to the root of the bst
* void *data: the data to be found
* return value:
* the data in the node if found
*/
void* bst_search(bst* b, void* data);
/* inorder_traversal
* purpose: traverse a subtree with root in ascending order, apply func
* to the data of each node.
* inputs:
* node *root: a pointer to the head of the bst
* a function to be applied to the bst
* return values:
* none, just applies to function to the
*/
void bst_inorder_traversal(bst* b, void(*func)(void* data));
/* bst_free
* purpose:free the bst with
* inputs:
* bst* b: the root of the bst to be freed
* return values:
* none, just frees the bst
*/
void bst_free(bst* b);
/* bst_delete:
* purpose: delete a node containing data from the bst
* inputs:
* bst* b: a pointer pointing to the root of the bst
* void *data: the data value in the bst to be deleted
* return value:
* none
*/
void bst_delete(bst* b, void* data);
/* ******* Node ****** */
/* These functions are only in the .h file so you can
* call them for testing purposes. Normally,they would
* not be in the .h because they aren't intended to be
* called from outside bst.c
*/
/* node_new:
* purpose: malloc a new node and assign the data pointer to its data field
* inputs:
* void *data: a void pointer pointing to the input
* return:
* a pointer pointing to the node;
*/
node* node_new(void* data);
/* node_insert:
* purpose: Insert a node to to a subtree with a root node as parameter
* Insertion is in sorted order.
* inputs:
* node *root: a pointer pointing to the root of the tree
* void *data: a new value to be added into the tree
* comparison function: a function that compares the data with the data
* already in the tree
* return value:
* the new root of the modified subtree.
*/
node* node_insert(node* root, void* data,
int (*cmp)(const void* x, const void* y));
/* node_delete:
* purpose: delete a node from a subtree with a given root node the
* comparison function to search the node and delete it when a matching
* node is found. This function only deletes the first occurrence of the
* node, i.e, if multiple nodes contain the data we are looking for, only
* the first node we found is deleted.
* inputs:
* node* root: a pointer pointing to the root node
* void* data: the data in the node
* a comparison function
* return value:
* the new root node after deletion.
*/
node* node_delete(node* root, void* data,
int (*cmp)(const void* x, const void* y));
/* node_search:
* purpose: search for a node containing data in a subtree with a given
* root node. Use recursion to search that node.
* inputs:
* node* root: a pointer pointing to the root
* void *data: the data value to be searched up
* comparison function
* return value:
* the first occurrence of node.
*/
void* node_search(node* root, void* data,
int (*cmp)(const void* x, const void* y));
/* inorder_traversal
* purpose: traverse a subtree with root in ascending order, apply func
* to the data of each node.
* inputs:
* node *root: a pointer to the head of the bst
* a function to be applied to the bst
* return values:
* none, just applies to function to the
*/
void inorder_traversal(node* root, void(*func)(void* data));
#endif
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/input.h>
#include <string.h>
#include <stdio.h>
#include <pthread.h>
#include "./interrupts.h"
peripherals_t peripherals;
void (*keyboard_fn)() = NULL;
void (*mouse_fn)() = NULL;
void * keyboard_thread() {
const char *dev = "/dev/input/by-path/platform-i8042-serio-0-event-kbd";
struct input_event ev;
ssize_t n;
int fd;
fd = open(dev, O_RDONLY);
if (fd == -1) {
fprintf(stderr, "Cannot open %s: %s.\n", dev, strerror(errno));
return NULL;
}
while (1) {
n = read(fd, &ev, sizeof ev);
if (n == (ssize_t) - 1) {
if (errno == EINTR) {
continue;
} else {
break;
}
} else if (n != sizeof ev) {
errno = EIO;
break;
}
if (ev.type == EV_KEY && ev.value >= 0 && ev.value <= 2) {
peripherals.keyboard_type = ev.value;
peripherals.keyboard_code = ev.code;
if (keyboard_fn != NULL) {
keyboard_fn();
}
}
}
fflush(stdout);
fprintf(stderr, "%s.\n", strerror(errno));
}
void * mouse_thread() {
int fd, bytes;
unsigned char data[3];
const char *pDevice = "/dev/input/mice";
// Open Mouse
fd = open(pDevice, O_RDWR);
if (fd == -1) {
printf("ERROR Opening %s\n", pDevice);
return NULL;
}
int left, middle, right;
signed char x, y;
while (1) {
// Read Mouse
bytes = read(fd, data, sizeof(data));
if (bytes > 0) {
peripherals.mouse_left = data[0] & 0x1;
peripherals.mouse_right = data[0] & 0x2;
peripherals.mouse_middle = data[0] & 0x4;
peripherals.mouse_x = data[1];
peripherals.mouse_y = data[2];
if (mouse_fn != NULL) {
mouse_fn();
}
}
}
}
pthread_t keyboard_th;
pthread_t mouse_th;
int interrupts_init() {
if (pthread_create(&keyboard_th, NULL, &keyboard_thread, NULL) != 0) {
return 1;
}
if (pthread_create(&mouse_th, NULL, &mouse_thread, NULL) != 0) {
perror("pthread_create mouse");
return 1;
}
return 0;
}
void interrupts_set(isr_t type, void (*fn)()) {
switch (type) {
case KEYBOARD_ISR:
keyboard_fn = fn;
break;
case MOUSE_ISR:
mouse_fn = fn;
break;
default:
break;
}
}
int interrupts_close() {
if (pthread_join(keyboard_th, NULL)) {
perror("pthread_join keyboard");
return 2;
}
if (pthread_join(mouse_th, NULL)) {
perror("pthread_join mouse");
return 2;
}
return 0;
}
|
C
|
#include "emu.h"
int SCSILengthFromUINT8( UINT8 *length )
{
if( *length == 0 )
{
return 256;
}
return *length;
}
int SCSILengthFromUINT16( UINT8 *length )
{
return ( *(length) << 8 ) | *(length + 1 );
}
|
C
|
//AlonLLL.h
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#define BOOLEAN unsigned short
#define TRUE 1
#define FALSE 0
#define ZERO 0
#define ONE 1
#define TWO 2
#define THREE 3
#define FOUR 4
#define FIVE 5
#define SIX 6
#define SEVEN 7
#define EIGHT 8
#define NINE 9
#define TEN 10
#include <stdio.h>
#include <malloc.h>
#include "AlonStrings.h"
typedef struct LLLChar {
char info;
LLLChar* nextAddress;
} LLLChar;
typedef struct LLLString {
char* info;
LLLString* nextAddress;
} LLLString;
typedef struct LLLInt {
int info;
LLLInt* nextAddress;
} LLLInt;
//----------------------------------------------------------------------
// LLLChar
//----------------------------------------------------------------------
void initLLLChar(LLLChar** manager);
void pushLLLChar(LLLChar** manager);
void popLLLChar(LLLChar** manager);
void insertAfterLLLChar(LLLChar* ptrAddAfter);
void deleteAfterLLLChar(LLLChar* ptrDeleteAfter);
void deleteSymbolFromSecondNodeLLLChar(LLLChar* deleteAfterPtr, char symbol);
void deleteSymbolFromManagerLLLChar(LLLChar** manager, char symbol);
void deleteSymbolFromLLLChar(LLLChar** manager, char symbol);
void deleteDuplicateFromLLLChar(LLLChar* ptrDeleteNext);
LLLChar* longestLLLCharWord(LLLChar* manager);
//----------------------------------------------------------------------
// LLLInt
//----------------------------------------------------------------------
void sumNodesLLLInt(LLLInt* manager, int* ptrVector);
//----------------------------------------------------------------------
// LLLString
//----------------------------------------------------------------------
int longestStringPlaceLLLString(LLLString* manager);
|
C
|
int main(int argc, const char * argv[]) {
char c;
int contVocali = 0;
int contCaratteriStrani = 0;
printf("Inserisci 5 lettere seguiti dall'invio: ");
//fflush(stdin); //WIN
//fpurge(stdin); //MAC
scanf(" %c",&c);
if ((c<'A') || ((c>'Z') && (c<'a')) || (c>'z'))
contCaratteriStrani++;
if ((c=='a') || (c=='e') || (c=='i') || (c=='o') || (c=='u')
|| (c=='A') || (c=='E') || (c=='I') || (c=='O') || (c=='U'))
contVocali++; //contVocali = contVocali+1;
scanf(" %c",&c);
if ((c<'A') || ((c>'Z') && (c<'a')) || (c>'z'))
contCaratteriStrani++;
if ((c=='a') || (c=='e') || (c=='i') || (c=='o') || (c=='u')
|| (c=='A') || (c=='E') || (c=='I') || (c=='O') || (c=='U'))
contVocali++; //contVocali = contVocali+1;
scanf(" %c",&c);
if ((c<'A') || ((c>'Z') && (c<'a')) || (c>'z'))
contCaratteriStrani++;
if ((c=='a') || (c=='e') || (c=='i') || (c=='o') || (c=='u')
|| (c=='A') || (c=='E') || (c=='I') || (c=='O') || (c=='U'))
contVocali++; //contVocali = contVocali+1;
scanf(" %c",&c);
if ((c<'A') || ((c>'Z') && (c<'a')) || (c>'z'))
contCaratteriStrani++;
if ((c=='a') || (c=='e') || (c=='i') || (c=='o') || (c=='u')
|| (c=='A') || (c=='E') || (c=='I') || (c=='O') || (c=='U'))
contVocali++; //contVocali = contVocali+1;
scanf(" %c",&c);
if ((c<'A') || ((c>'Z') && (c<'a')) || (c>'z'))
contCaratteriStrani++;
if ((c=='a') || (c=='e') || (c=='i') || (c=='o') || (c=='u')
|| (c=='A') || (c=='E') || (c=='I') || (c=='O') || (c=='U'))
contVocali++; //contVocali = contVocali+1;
printf("Il numero di vocali inserite è: %d\n",contVocali);
printf("I caratteri strani sono: %d\n", contCaratteriStrani);
return 0;
}
|
C
|
#include "bl_leds.h"
static LED_t LEDS[NUM_LEDS] = LEDS_ARRAY_INIT;
uint32_t Leds_GetLeds(void) {
uint32_t ledsVal = 0;
for (uint32_t i = 0, mask = 0x1; i < NUM_LEDS; i++, mask <<= 1) {
if (GPIO_PinOutGet(LEDS[i].port, LEDS[i].pin))
ledsVal |= mask;
}
return ledsVal;
}
void Leds_SetLed(uint32_t led) {
if (led < NUM_LEDS) {
GPIO_PinOutSet(LEDS[led].port, LEDS[led].pin);
}
}
void Leds_ClearLed(uint32_t led) {
if (led < NUM_LEDS) {
GPIO_PinOutClear(LEDS[led].port, LEDS[led].pin);
}
}
void Leds_SetLeds(uint32_t leds) {
for (uint32_t i = 0, mask = 0x1; i < NUM_LEDS; i++, mask <<= 1 ) {
if (leds & mask) {
GPIO_PinOutSet(LEDS[i].port, LEDS[i].pin);
} else {
GPIO_PinOutClear(LEDS[i].port, LEDS[i].pin);
}
}
}
void Leds_Init(void) {
/* Enable clocks */
CMU_ClockEnable(cmuClock_HFPER, true); /* High frequency peripheral clock */
CMU_ClockEnable(cmuClock_GPIO, true); /* General purpose input/output clock. */
/* Setup GPIO Pins for leds */
for (int i = 0; i < NUM_LEDS; i++) {
GPIO_PinModeSet(LEDS[i].port, LEDS[i].pin, gpioModePushPull, 0);
}
}
|
C
|
// UEFI From Scratch Tutorials - ThatOSDev ( 2021 )
// https://github.com/ThatOSDev/UEFI-Tuts
#include "efi.h"
#include "ErrorCodes.h"
#include "tosdfont.h"
#include "efilibs.h"
EFI_STATUS efi_main(EFI_HANDLE IH, EFI_SYSTEM_TABLE *ST)
{
ImageHandle = IH;
SystemTable = ST;
ResetScreen();
InitializeGOP();
InitializeFILESYSTEM();
SetCursorPosition(50, 50);
SetFontSpacing(2);
SetFontSize(8);
printf("Welcome to the UEFI From Scratch Tutorials\r\n");
readFile(u"ThatOS64\\loader.bin");
SetGraphicsColor(ORANGE);
SetCursorPosition(190, 230);
SetFontSpacing(2);
SetFontSize(7);
printf("Jumping to the loader.");
UINT8* loader = (UINT8*)OSBuffer_Handle;
int j = 3456;
/*
UINTN MemoryMapSize = 0;
EFI_MEMORY_DESCRIPTOR *MemoryMap;
UINTN MapKey;
UINTN DescriptorSize;
UINT32 DescriptorVersion;
SystemTable->BootServices->GetMemoryMap(&MemoryMapSize, MemoryMap, &MapKey, &DescriptorSize, &DescriptorVersion);
MemoryMapSize += 2 * DescriptorSize;
SystemTable->BootServices->AllocatePool(2, MemoryMapSize, (void **)&MemoryMap);
SystemTable->BootServices->GetMemoryMap(&MemoryMapSize, MemoryMap, &MapKey, &DescriptorSize, &DescriptorVersion);
SystemTable->BootServices->ExitBootServices(ImageHandle, MapKey);
*/
int (*KernelBinFile)(int, char*) = ((__attribute__((ms_abi)) int (*)(int, char*) ) &loader[262]);
int g = KernelBinFile(j, 0);
UINT16 tmp[8];
itoa(g, tmp, 10);
Print(L"\r\n\r\nThe returned number is : ");
SetColor(EFI_LIGHTMAGENTA);
Print(tmp);
SetGraphicsColor(GRAY);
SetFontSpacing(1);
SetFontSize(6);
SetCursorPosition(100, 500);
printf("Q to quit | R to Reboot");
while(1)
{
Delay1();
EFI_STATUS Status = CheckKey();
if(Status == EFI_SUCCESS)
{
if(GetKey('q') == 1)
{
SHUTDOWN();
break;
}
if(GetKey('r') == 1)
{
COLD_REBOOT();
break;
}
}
}
// We should not make it to this point.
COLD_REBOOT();
// We should not make it to this point.
return EFI_SUCCESS;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <math.h>
#include "eratosthenes.h"
int main(int argc, char *argv[]) {
// Turning off sigpipe
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
perror("signal");
exit(1);
}
if (argc != 2){
fprintf(stderr, "Usage:\n\tpfact n\n");
exit(1);
}
int factor1 = 0;
int factor2 = 0;
int n;
int ret_value;
int m;
if ((n = strtol(argv[1],NULL,10)) == 0){
fprintf(stderr, "Usage:\n\tpfact n\n");
exit(1);
}
else if (n <= 0){
fprintf(stderr, "Usage:\n\tpfact n\n");
exit(1);
}
int fd[2];
if (pipe(fd) == -1){
exit(2);
}
int fds[2];
int * fds_pointer = fds;
if (((ret_value = fork()) < 0)){
exit(2);
}
else if (ret_value == 0){
close(fd[1]);
if (read(fd[0],&m,sizeof(m)) < 0){
exit(2);
}
else {
while (m <= sqrt(n)) {
if (n % m == 0){
if (factor1 == 0){
factor1 = m;
if ((n / factor1) % factor1 == 0){
if (factor1 * factor1 == n){
printf("%d %d %d\n", n, factor1, factor1);
close(fd[0]);
exit(0);
}
else {
printf("%d is not the product of two primes\n", n);
close(fd[0]);
exit(0);
}
}
}
else { //where factor 1 is already found
printf("%d is not the product of two primes\n", n);
close(fd[0]);
exit(0);
}
}
if (make_stage(m,fd[0],&fds_pointer) > 0){
int status2;
if (wait(&status2) != -1){
if (WIFEXITED(status2)){
if(WEXITSTATUS(status2) == -1){
exit(-1);
}
exit(WEXITSTATUS(status2)+1);
}
}
}
else {
if(read(fds[0],&m,sizeof(m)) < 0){
exit(2);
}
else {
dup2(fds[0],fd[0]);
}
}
}
} // when m > sqrt(n)
if (n == 2 || n == 3){ // hardcording value values 2 and 3 because they are a special case
printf("%d is prime\n", n);
close(fd[0]);
close(fd[1]);
exit(0);
}
while((read(fds[0],&m,sizeof(m))) > 0){
if (factor1 * m == n){
factor2 = m;
printf("%d %d %d\n", n, factor1, factor2);
close(fd[0]);
exit(0);
}
if (factor1 == 0){
if (factor2 == 0){
printf("%d is prime\n", n);
close(fd[0]);
exit(0);
}
}
printf("%d is not the product of two primes\n", n);
exit(0);
}
}
else {
close(fd[0]);
for (int i = 2;i<=n;i++){
if (write(fd[1],&i,sizeof(i)) == -1){
exit(2);
}
}
int status;
close(fd[1]);
if (wait(&status) != -1){
if (WIFEXITED(status)){
printf("Number of filters = %d\n", WEXITSTATUS(status));
}
exit(0);
}
else {
exit(-1);
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include "matrix.h"
void handlerError (CEXCEPTION_T EXPT);
int dialog (const char *msgs[], int n)
{
int choice;
do {
for (int i = 0; i < n; ++i)
puts(msgs[i]);
printf("> ");
choice = getchar() - '0';
while (getchar() != '\n');
if (choice < 0 || choice >= n)
printf("You're wrong. Try again!\n");
} while (choice < 0 || choice >= n);
return choice;
}
const char *MENU[] = {"0. Exit",
"1. integer numbers",
"2. real numbers"};
const int MENU_SIZE = sizeof(MENU) / sizeof(MENU[0]);
const char *MENU_INT[] = {"0. back",
"1. create matrix",
"2. sum matrices",
"3. multi matrices",
"4. transpose matrix",
"5. add linear combination"};
const int MENU_INT_SIZE = sizeof(MENU_INT) / sizeof(MENU_INT[0]);
int main ()
{
int a[3][3] = {1, 2, 3,
4, 5, 6,
7, 8, 9};
int a1[3][4] = {1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12};
float c[3][3] = {1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0};
float c1[3][4] = {1.0, 2.0, 3.0, 4.0,
2.0, 3.0, 4.0, 5.0,
3.0, 4.0, 5.0, 6.0};
/*int b[3][1] = {1,
2,
3};
int c[1][3] = {1, 2, 3};
int coef[1] = {3};
int n[1] = {2};*/
Matrix A = {a, 3, 3, sizeof(int), sumInt, multiInt};
Matrix A1 = {a1, 3, 4, sizeof(int), sumInt, multiInt};
Matrix C = {c, 3, 3, sizeof(float), sumReal, multiReal};
Matrix C1 = {c1, 3, 4, sizeof(float), sumReal, multiReal};
/*Matrix B = {b, 3, 1, sizeof(int), sumInt, multiInt};
Matrix C = {c, 1, 3, sizeof(int), sumInt, multiInt};*/
CEXCEPTION_T EXCEPTION;
int menu;
do {
menu = dialog(MENU, MENU_SIZE);
switch (menu) {
case 0:
break;
case 1: {
int menu_int;
do {
menu_int = dialog(MENU_INT, MENU_INT_SIZE);
switch (menu_int) {
Matrix x1, x2;
case 0:
break;
case 1: {
int c;
printf("use examples?\n0.no\n1.yes\n");
scanf("%d", &c);
getchar();
if (c) {
x1 = A;
printIntMatrix(&x1);
x2 = A1;
printIntMatrix(&x2);
} else {
Try{
x1 = enterIntMatrix();
x2 = enterIntMatrix();
} Catch(EXCEPTION) {
handlerError(EXCEPTION);
}
}
}
break;
case 2: {
int c;
printf("use examples?\n0.no\n1.yes\n");
scanf("%d", &c);
getchar();
if (c) {
x1 = A;
printIntMatrix(&x1);
x2 = transpose(&A);
printIntMatrix(&x2);
}
Try {
Matrix ANS = sumMatrix(&x1, &x2);
printIntMatrix(&ANS);
} Catch(EXCEPTION) {
handlerError(EXCEPTION);
}
}
break;
case 3: {
Try {
Matrix ANS = multiMatrix(&x1, &x2);
printIntMatrix(&ANS);
} Catch(EXCEPTION) {
handlerError(EXCEPTION);
}
}
break;
case 4: {
Try {
Matrix ANS = transpose(&x1);
printIntMatrix(&ANS);
ANS = transpose(&x2);
printIntMatrix(&ANS);
} Catch(EXCEPTION) {
handlerError(EXCEPTION);
}
}
break;
case 5: {
int c;
printf("what matrix use?\n0. 1\n1. 2\n");
scanf("%d", &c);
getchar();
Matrix ANS;
if (c) {
ANS = x2;
} else {
ANS = x1;
}
int change_row, number_rows;
printf("change row number: ");
scanf("%d", &change_row);
getchar();
printf("how mary rows do you add? ");
scanf("%d", &number_rows);
getchar();
//printf("1\n");
//int rows[number_rows];
int *rows = (int*) malloc(number_rows * (sizeof(int)));
//printf("1\n");
//int coefficients[number_rows];
int *coefficients = (int*) malloc(number_rows * (sizeof(int)));
//printf("1\n");
printf("add rows: ");
//getchar(); getchar();
for (int i = 0; i < number_rows; i++) {
scanf("%d", &rows[i]);
}
printf("enter coefficients ");
for (int i = 0; i < number_rows; i++) {
scanf("%d", &coefficients[i]);
}
Try {
linearCombinationRow(&ANS, number_rows, change_row, rows, coefficients);
printIntMatrix(&ANS);
} Catch(EXCEPTION) {
handlerError(EXCEPTION);
}
}
break;
}
} while (menu_int);
}
break;
case 2: {
int menu_int;
do {
menu_int = dialog(MENU_INT, MENU_INT_SIZE);
switch (menu_int) {
Matrix x1, x2;
case 0:
break;
case 1: {
int c;
printf("use examples?\n0.no\n1.yes\n");
scanf("%d", &c);
getchar();
if (c) {
x1 = C;
printRealMatrix(&x1);
x2 = C1;
printRealMatrix(&x2);
} else {
Try{
x1 = enterRealMatrix();
x2 = enterRealMatrix();
} Catch(EXCEPTION) {
handlerError(EXCEPTION);
}
}
}
break;
case 2: {
int c;
printf("use examples?\n0.no\n1.yes\n");
scanf("%d", &c);
getchar();
if (c) {
x1 = C;
printRealMatrix(&x1);
x2 = transpose(&C);
printRealMatrix(&x2);
}
Try {
Matrix ANS = sumMatrix(&x1, &x2);
printRealMatrix(&ANS);
} Catch(EXCEPTION) {
handlerError(EXCEPTION);
}
}
break;
case 3: {
Try {
Matrix ANS = multiMatrix(&x1, &x2);
printRealMatrix(&ANS);
} Catch(EXCEPTION) {
handlerError(EXCEPTION);
}
}
break;
case 4: {
Try {
Matrix ANS = transpose(&x1);
printRealMatrix(&ANS);
ANS = transpose(&x2);
printRealMatrix(&ANS);
} Catch(EXCEPTION) {
handlerError(EXCEPTION);
}
}
break;
case 5: {
int c;
printf("what matrix use?\n0. 1\n1. 2\n");
scanf("%d", &c);
getchar();
Matrix ANS;
if (c) {
ANS = x2;
} else {
ANS = x1;
}
int change_row, number_rows;
printf("change row number: ");
scanf("%d", &change_row);
getchar();
printf("how mary rows do you add? ");
scanf("%d", &number_rows);
getchar();
//printf("1\n");
//int rows[number_rows];
int *rows = (int*) malloc(number_rows * (sizeof(int)));
//printf("1\n");
//int coefficients[number_rows];
float *coefficients = (float*) malloc(number_rows * (sizeof(float)));
//printf("1\n");
printf("add rows: ");
//getchar(); getchar();
for (int i = 0; i < number_rows; i++) {
scanf("%d", &rows[i]);
}
printf("enter coefficients ");
for (int i = 0; i < number_rows; i++) {
scanf("%f", &coefficients[i]);
}
Try {
linearCombinationRow(&ANS, number_rows, change_row, rows, coefficients);
printRealMatrix(&ANS);
} Catch(EXCEPTION) {
handlerError(EXCEPTION);
}
}
break;
}
} while (menu_int);
}
}
} while (menu);
return 0;
}
void handlerError (CEXCEPTION_T EXPT)
{
switch (EXPT) {
case NULL_POINTER:
printf("points to a null pointer!");
break;
case WRONG_ELEMENT_SIZE:
printf("Element length less than or equal to 0!");
break;
case WRONG_DIMENSION:
printf("Array length is less than or equal to 0!");
break;
case NO_SUMMAT:
printf("No sum function!");
break;
case NO_MULTI:
printf("No multi function!");
break;
case DIFFERENT_ELEMENT_SIZE:
printf("Different element length!");
break;
case DIFF_SUM:
printf("Different sum functions!");
break;
case DIFF_MULTI:
printf("Different multi functions!");
break;
case OVERFLOW_EL:
printf("Variable overflow has occurred!");
break;
case WRONG_SHAPE:
printf("Impossible to use matrices of different shape");
break;
default:
printf("Unknown error %d", EXPT);
break;
}
printf("\n");
}
|
C
|
#include <string.h>
#include <stdio.h>
char * ft_strcat (char *s1, char *s2);
int main () {
char str1[100] = "Hello";
char str2[] = " world";
puts("Before call 'ft_strcat' funcion.");
printf("str1 = \"%s\"\n", str1);
printf("str2 = \"%s\"\n", str2);
ft_strcat(str1, str2);
puts("-------------------------------");
puts("After call 'ft_strcat' funcion.");
printf("str1 = \"%s\"\n", str1);
printf("str2 = \"%s\"\n", str2);
return 0;
}
|
C
|
#include"save.h"
int pStu_Save(pStu pHead,FILE *fd)
{
fd=fopen("stu.txt","w+");
if(fd==NULL)
{
printf("fopen error\n");
exit(-1);
}
pStu p=pHead;
while(p->next!=NULL)
{
fwrite(p->next,sizeof(sStu),1,fd);
p=p->next;
}
printf("保存成功\n");
fclose(fd);
return 0;
}
|
C
|
/*
** my_strcat.c for my_strcat in /home/maxime/Rendus/24-03-16/sitruk_m/my_strcat
**
** Made by MAXIME Sitruk
** Login <sitruk_m@etna-alternance.net>
**
** Started on Wed Mar 23 20:04:35 2016 MAXIME Sitruk
** Last update Fri Mar 25 12:40:18 2016 MAXIME Sitruk
*/
int my_strlen(char *str);
char *my_strcat(char *str1, char *str2)
{
int i;
int s1;
i = 0;
s1 = my_strlen(str1);
while (str2[i] != '\0')
{
str1[s1 + i] = str2[i];
i = i + 1;
}
str1[s1 + i] = '\0';
return (str1);
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
/* netbd.h es necesitada por la estructura hostent guiño */
#define PORT 3550
/* El Puerto Abierto del nodo remoto */
#define PORT2 3555 /* Puerto Abierto para recibir resultados*/
#define BACKLOG 2 /* El número de conexiones permitidas */
#define MAXDATASIZE 22
/* El número máximo de datos en bytes */
int main(int argc, char *argv[])
{
int fd,fd2, numbytes;
/* ficheros descriptores */
char buf[MAXDATASIZE];
/* en donde es almacenará el texto recibido */
char jug[MAXDATASIZE];
char res[MAXDATASIZE];
struct hostent *he;
/* estructura que recibirá información sobre el nodo remoto */
struct sockaddr_in server, client;
int sin_size;
/* información sobre la dirección del servidor */
if (argc !=3) {
/* esto es porque nuestro programa sólo necesitará un
argumento, (la IP) */
printf("Uso: %s <Dirección IP>\n",argv[0]);
exit(-1);
}
if ((he=gethostbyname(argv[1]))==NULL){
/* llamada a gethostbyname() */
printf("gethostbyname() error\n");
exit(-1);
}
if ((fd=socket(AF_INET, SOCK_STREAM, 0))==-1){
/* llamada a socket() */
printf("socket() error\n");
exit(-1);
}
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
/* htons() es necesaria nuevamente ;-o */
server.sin_addr = *((struct in_addr *)he->h_addr);
/*he->h_addr pasa la información de ``*he'' a "h_addr" */
bzero(&(server.sin_zero),8);
if(connect(fd, (struct sockaddr *)&server,
sizeof(struct sockaddr))==-1){
/* llamada a connect() */
printf("connect() error\n");
exit(-1);
}
if ((numbytes=recv(fd,buf,MAXDATASIZE,0)) == -1){
/* llamada a recv() */
printf("Error en recv() \n");
exit(-1);
}
buf[numbytes]='\0';
printf("%s\n",buf);
/* muestra el mensaje de bienvenida del servidor =) */
send(fd,argv[2],22,0);
if ((numbytes=recv(fd,jug,MAXDATASIZE,0)) == -1)
{
/* llamada a recv() */
printf("Error en recv JUG() \n");
exit(-1);
}
jug[numbytes]='\0';
printf("%s\n",jug);
close(fd); /* cerramos fd =) */
printf("esperando resultados...\n");
if ((fd2=socket(AF_INET, SOCK_STREAM, 0)) == -1 ) {
printf("error en socket()\n");
exit(-1);
}
client.sin_family = AF_INET;
client.sin_port = htons(PORT2);
/* ¿Recuerdas a htons() de la sección "Conversiones"? =) */
client.sin_addr.s_addr = INADDR_ANY;
/* INADDR_ANY coloca nuestra dirección IP automáticamente */
bzero(&(client.sin_zero),8);
/* escribimos ceros en el reto de la estructura */
/* A continuación la llamada a bind() */
if(bind(fd,(struct sockaddr*)&client,
sizeof(struct sockaddr))==-1) {
printf("error en bind() \n");
exit(-1);
}
if(listen(fd2,BACKLOG) == -1) { /* llamada a listen() */
printf("error en listen()\n");
exit(-1);
}
if ((fd = accept(fd,(struct sockaddr *)&server,
&sin_size))==-1) {
printf("error en accept()\n");
exit(-1);
}
if ((numbytes=recv(fd,res,MAXDATASIZE,0)) == -1)
{
/* llamada a recv() */
printf("Error en recv RES() \n");
exit(-1);
}
close(fd); /*Cierra la conexión con el servidor*/
res[numbytes]='\0';
printf("%s\n",res);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "des.h"
#include "test_functions.h"
void test_dim5(int seed, int n_times)
{
int dim = 5;
FILE* error_file = fopen("error_dim5.txt", "w");
fprintf(error_file, "Name;N;Best;Worst;Mean;Median;Standard Deviation\n");
FILE* times_file = fopen("times_dim5.txt", "w");
fprintf(times_file, "Name;N;Best;Worst;Mean;Median;Standard Deviation\n");
test_Ackeleya(error_file, times_file, n_times, seed, dim);
test_Rastrigin(error_file, times_file, n_times, seed, dim);
test_Shubert(error_file, times_file, n_times, seed);
test_Shekel(error_file, times_file, n_times, seed);
test_Griewank(error_file, times_file, n_times, seed, dim);
test_Perm(error_file, times_file, n_times, seed, dim);
test_rotated(error_file, times_file, n_times, seed, dim);
test_Zakharov(error_file, times_file, n_times, seed, dim);
test_simple_quadratic(error_file, times_file, n_times, seed);
test_sin_cos(error_file, times_file, n_times, seed);
fclose(error_file);
fclose(times_file);
}
void test_dim10(int seed, int n_times)
{
int dim = 10;
FILE* error_file = fopen("error_dim10.txt", "w");
fprintf(error_file, "Name;N;Best;Worst;Mean;Median;Standard Deviation\n");
FILE* times_file = fopen("times_dim10.txt", "w");
fprintf(times_file, "Name;N;Best;Worst;Mean;Median;Standard Deviation\n");
test_Ackeleya(error_file, times_file, n_times, seed, dim);
test_Rastrigin(error_file, times_file, n_times, seed, dim);
test_Shubert(error_file, times_file, n_times, seed);
test_Shekel(error_file, times_file, n_times, seed);
test_Griewank(error_file, times_file, n_times, seed, dim);
test_Perm(error_file, times_file, n_times, seed, dim);
test_rotated(error_file, times_file, n_times, seed, dim);
test_Zakharov(error_file, times_file, n_times, seed, dim);
test_simple_quadratic(error_file, times_file, n_times, seed);
test_sin_cos(error_file, times_file, n_times, seed);
fclose(error_file);
fclose(times_file);
}
void test_dim20(int seed, int n_times)
{
int dim = 20;
FILE* error_file = fopen("error_dim20.txt", "w");
fprintf(error_file, "Name;N;Best;Worst;Mean;Median;Standard Deviation\n");
FILE* times_file = fopen("times_dim20.txt", "w");
fprintf(times_file, "Name;N;Best;Worst;Mean;Median;Standard Deviation\n");
test_Ackeleya(error_file, times_file, n_times, seed, dim);
test_Rastrigin(error_file, times_file, n_times, seed, dim);
test_Shubert(error_file, times_file, n_times, seed);
test_Shekel(error_file, times_file, n_times, seed);
test_Griewank(error_file, times_file, n_times, seed, dim);
test_Perm(error_file, times_file, n_times, seed, dim);
test_rotated(error_file, times_file, n_times, seed, dim);
test_Zakharov(error_file, times_file, n_times, seed, dim);
test_simple_quadratic(error_file, times_file, n_times, seed);
test_sin_cos(error_file, times_file, n_times, seed);
fclose(error_file);
fclose(times_file);
}
int main()
{
int seed = 1234;
int n_times = 20;
printf("Testing dim 5...\n");
test_dim5(seed, n_times);
printf("Testing dim 10...\n");
test_dim10(seed, n_times);
printf("Testing dim 20...\n");
test_dim20(seed, n_times);
}
|
C
|
/*
** true if val1 -> int ptr or int array and val2 not ptr or array
*/
dbltest(val1, val2)
int val1[], val2[];
{
if (val1[2] != CINT)
return (0);
if (val2[2])
return (0);
return (1);
}
/*
** determine type of binary operation
*/
result(lval, lval2)
int lval[], lval2[];
{
if ((lval[2] != 0) & (lval2[2] != 0)) {
lval[2] = 0;
}
else if (lval2[2]) {
lval[0] = lval2[0];
lval[1] = lval2[1];
lval[2] = lval2[2];
}
}
step(oper, lval)
int lval[];
int (*oper)();
{
if (lval[1]) {
if (lval[5]) {
push();
rvalue(lval);
(*oper)(lval[2] >> 2);
pop();
store(lval);
return;
}
else {
move();
lval[5] = 1;
}
}
rvalue(lval);
(*oper)(lval[2] >> 2);
store(lval);
}
store(lval)
int lval[];
{
if (lval[1])
putstk(lval);
else
putmem(lval);
}
rvalue(lval)
int lval[];
{
if ((lval[0] != 0) & (lval[1] == 0))
getmem(lval);
else
indirect(lval);
}
test(label, parens)
int label, parens;
{
int lval[8];
char *before, *start;
if (parens)
needtoken("(");
while (1) {
setstage(&before, &start);
if (heir1(lval))
rvalue(lval);
if (match(","))
clearstage(before, start);
else
break;
}
if (parens)
needtoken(")");
if (lval[3]) {
clearstage(before, 0);
if (lval[4])
return;
jump(label);
return;
}
if (lval[7]) {
oper = lval[6];
if ((oper == eq) | (oper == ule))
zerojump(eq0, label, lval);
else if ((oper == ne) | (oper == ugt))
zerojump(ne0, label, lval);
else if (oper == gt)
zerojump(gt0, label, lval);
else if (oper == ge)
zerojump(ge0, label, lval);
else if (oper == uge)
clearstage(lval[7], 0);
else if (oper == lt)
zerojump(lt0, label, lval);
else if (oper == ult)
zerojump(ult0, label, lval);
else if (oper == le)
zerojump(le0, label, lval);
else
testjump(label);
}
else
testjump(label);
clearstage(before, start);
}
constexpr(val)
int *val;
{
int const;
char *before, *start;
setstage(&before, &start);
expression(&const, val);
clearstage(before, 0);
if (const == 0)
error("must be constant expression");
return (const);
}
const(val)
int val;
{
immed();
outdec(val);
nl();
}
const2(val)
int val;
{
immed2();
outdec(val);
nl();
}
constant(lval)
int lval[];
{
lval = lval + 3;
*lval = 1;
if (number(++lval))
immed();
else if (pstr(lval))
immed();
else if (qstr(lval)) {
*(lval - 1) = 0;
immed();
printlabel(litlab);
outbyte('+');
}
else
return (0);
outdec(*lval);
nl();
return (1);
}
number(val)
int val[];
{
int k, minus;
k = minus = 0;
while (1) {
if (match("+"))
;
else if (match("-"))
minus = 1;
else
break;
}
if (numeric(ch) == 0)
return (0);
while (numeric(ch))
k = k * 10 + (inbyte() - '0');
if (minus)
k = (-k);
val[0] = k;
return (1);
}
address(ptr)
char *ptr;
{
immed();
outstr(ptr + NAME);
nl();
}
pstr(val)
int val[];
{
int k;
k = 0;
if (match("'") == 0)
return (0);
while (ch != 39)
k = (k & 255) * 256 + (litchar() & 255);
++lptr;
val[0] = k;
return (1);
}
qstr(val)
int val[];
{
char c;
if (match(quote) == 0)
return (0);
val[0] = litptr;
while (ch != '"') {
if (ch == 0)
break;
stowlit(litchar(), 1);
}
gch();
litq[litptr++] = 0;
return (1);
}
stowlit(value, size)
int value, size;
{
if ((litptr + size) >= LITMAX) {
error("literal queue overflow");
abort(ERRCODE);
}
putint(value, litq + litptr, size);
litptr = litptr + size;
}
/*
** return current literal char & bump ptr
*/
litchar() {
int i, oct;
if ((ch != 92) | (nch == 0))
return (gch());
gch();
if (ch == 'n') {
gch();
return (13); /* CR */
}
if (ch == 't') {
gch();
return (9); /* HT */
}
if (ch == 'b') {
gch();
return (8); /* BS */
}
if (ch == 'f') {
gch();
return (12); /* FF */
}
i = 3;
oct = 0;
while (((i--) > 0) & (ch >= '0') & (ch <= '7'))
oct = (oct << 3) + gch() - '0';
if (i == 2)
return (gch());
else
return (oct);
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include "log_view_stats.h"
#include "log_name_tree.h"
#include "log_utils.h"
#include "log_heap.h"
#include "statsmessage.pb-c.h"
char *RCODE[RCODE_MAX_NUM] = {
"NOERROR",
"FORMATERR",
"SERVFAIL",
"NXDOMAIN",
"NOTIMP",
"REFUSED",
"OTHER"
};
char *RTYPE[RTYPE_MAX_NUM] = {
"A",
"MX",
"AAAA",
"CNAME",
"NS",
"SOA",
"TXT",
"SPF"
"SRV",
"DNAME",
"NAPTR",
"OTHER",
};
int rtype_index(const char *rtype)
{
int i = 0 ;
for( ; i < RTYPE_MAX_NUM; i++)
{
if (strcmp(rtype, RTYPE[i])== 0)
return i;
}
return RTYPE_MAX_NUM-1;
}
int rcode_index(const char *rcode)
{
int i = 0 ;
for( ; i < RCODE_MAX_NUM; i++)
{
if (strcmp(rcode, RCODE[i])== 0)
return i;
}
return RCODE_MAX_NUM -1;
}
view_stats_t *view_stats_create(const char *view_name)
{
if (strlen(view_name) > MAX_VIEW_LENGTH )
return NULL;
view_stats_t *vs = malloc(sizeof(view_stats_t));
if (NULL == vs)
return NULL;
vs->name_tree = name_tree_create();
if (!vs->name_tree)
{
fprintf(stderr, "Error: create name tree\n");
return NULL;
}
vs->ip_tree = name_tree_create();
if (!vs->ip_tree)
{
fprintf(stderr, "Error: create ip tree\n");
return NULL;
}
vs->qps = 0.0;
vs->success_rate = 1.0;
vs->count = 0;
vs->last_count = 0;
strcpy(vs->name, view_name);
int i;
for( i = 0; i < RCODE_MAX_NUM ; i++)
vs->rcode[i] = 0;
for( i = 0; i < RTYPE_MAX_NUM; i++)
vs->rtype[i] = 0;
}
uint64_t view_stats_get_size(view_stats_t *vs)
{
uint32_t initsize = sizeof(view_stats_t);
uint32_t nametree_size = name_tree_get_size(vs->name_tree);
uint32_t iptree_size = name_tree_get_size(vs->ip_tree);
return initsize + nametree_size + iptree_size;
}
void view_stats_set_memsize(view_stats_t *vs, uint64_t expect_size){
uint64_t current_size = view_stats_get_size(vs);
printf("current_size %u, name node %u, ip node %u\n", current_size, vs->name_tree->count, vs->ip_tree->count);
while (expect_size < current_size) {
printf("delete name tree node due to memory bigger than expect\n");
node_value_t *node = lru_list_remove_tail(vs->name_tree->lru);
if (node == NULL) {
break;
}
name_tree_delete(vs->name_tree, node->fqdn, NULL);
current_size = view_stats_get_size(vs);
}
while (expect_size < current_size) {
printf("delete ip tree node due to memory bigger than expect\n");
node_value_t *node = lru_list_remove_tail(vs->ip_tree->lru);
if (node == NULL) {
break;
}
name_tree_delete(vs->ip_tree, node->fqdn, NULL);
current_size = view_stats_get_size(vs);
}
}
void view_stats_destory(view_stats_t *vs)
{
ASSERT(vs, "empty pointer when destory view stats\n");
name_tree_destroy(vs->name_tree);
name_tree_destroy(vs->ip_tree);
free(vs);
}
void view_stats_insert_name(view_stats_t *vs, const char *name)
{
ASSERT(vs && name, "view stats or name is NULL when insert\n");
name_tree_insert(vs->name_tree, name);
}
void view_stats_insert_ip(view_stats_t *vs, const char *ip)
{
ASSERT(vs && ip, "view stats or name is NULL when insert\n");
name_tree_insert(vs->ip_tree, ip);
}
void view_stats_rcode_increment(view_stats_t *vs, int rcode)
{
ASSERT(vs, "view stats is NULL when insert\n");
if (rcode > RCODE_MAX_NUM || rcode < 0)
return;
vs->rcode[rcode]++;
}
void view_stats_rtype_increment(view_stats_t *vs, int rtype)
{
ASSERT(vs , "view stats is NULL when insert\n");
if (rtype > RTYPE_MAX_NUM || rtype < 0)
return;
vs->rtype[rtype]++;
}
int min(int a, int b)
{
return a < b ? a : b;
}
int max(int a, int b)
{
return a > b ? a : b;
}
unsigned int _view_stats_result(name_tree_t *tree, char *key, int topn, char **buff)
{
heap_t *copy_heap = heap_copy(tree->heap);
if (NULL == copy_heap)
{
printf("empty heap\n");
return 0;
}
heap_sort(copy_heap);
int i;
StatsReply reply = STATS_REPLY__INIT;
reply.key = key;
int _min = min(topn, copy_heap->len);
reply.n_name = _min;
reply.n_count = _min;
char **pdata = malloc(sizeof (char *) * _min);
memset(pdata, 0, sizeof(char *)*_min);
int32_t *pcount = malloc(sizeof (int32_t) * _min);
for(i = 0; i < reply.n_name; i++)
{
node_value_t *nv = (node_value_t *)(copy_heap->heap[i]);
/*
* new memory and copy if need absolutely right domain
pdata[i] = malloc(sizeof(char)* (strlen(nv->fqdn) + 1));
memcpy(pdata[i], nv->fqdn, (strlen(nv->fqdn) + 1));
printf("malloc: addr of %d ptr is %p\n", i, pdata[i]);
*/
pdata[i] = nv->fqdn;
pcount[i]= nv->count;
}
reply.name = pdata;
reply.count = pcount;
unsigned int len = stats_reply__get_packed_size(&reply);
char *result_ptr = malloc(sizeof(char) *len);
stats_reply__pack(&reply, result_ptr);
heap_destory(copy_heap);
*buff = result_ptr;
/* free mem if malloced above
for (i=0; i<reply.n_name; i++)
{
printf("free addr of %d ptr is %p\n", i, pdata[i]);
if (pdata[i] != NULL)
free(pdata[i]);
}
*/
free(pcount);
free(pdata);
return len;
}
unsigned int view_stats_name_topn(view_stats_t *vs, int topn, char **buff)
{
ASSERT(vs && vs->name_tree, "view stats or name tree is NULL");
return _view_stats_result(vs->name_tree, "domaintopn", topn, buff);
}
unsigned int view_stats_ip_topn(view_stats_t *vs, int topn, char **buff)
{
ASSERT(vs && vs->ip_tree, "view stats or ip tree is NULL");
return _view_stats_result(vs->ip_tree, "iptopn", topn, buff);
}
unsigned int _view_stats_result1(int *array, char *key, char **buff)
{
StatsReply reply = STATS_REPLY__INIT;
reply.key = key;
char **p_name = NULL;
int need_length = 0;
if (strcmp(key, "rcode") == 0)
{
p_name = RCODE;
need_length = RCODE_MAX_NUM;
}
else
{
p_name = RTYPE;
need_length = RTYPE_MAX_NUM;
}
int i = 0;
int k = 0;
char **pdata = malloc(sizeof (char *) * need_length);
int32_t *pcount = malloc(sizeof (int32_t) * need_length);
for (; i < need_length; i++)
{
if (array[i] == 0)
continue;
pdata[k] = p_name[i];
pcount[k]= array[i];
k++;
}
reply.n_name = k;
reply.n_count = k;
reply.name = pdata;
reply.count = pcount;
unsigned int len = stats_reply__get_packed_size(&reply);
char *result_ptr = malloc(sizeof(char) *len);
stats_reply__pack(&reply, result_ptr);
*buff = result_ptr;
free(pcount);
free(pdata);
return len;
}
unsigned int view_stats_get_rcode(view_stats_t *vs, char **buff)
{
return _view_stats_result1(vs->rcode, "rcode", buff);
}
unsigned int view_stats_get_rtype(view_stats_t *vs, char **buff)
{
return _view_stats_result1(vs->rtype, "rtype", buff);
}
unsigned int _view_stats_result2(float value, char *key, char **buff)
{
StatsReply reply = STATS_REPLY__INIT;
reply.key = key;
reply.value = value;
char tempbuf[16];
sprintf(tempbuf, "%f", value);
reply.maybe = tempbuf;
unsigned int len = stats_reply__get_packed_size(&reply);
char *result_ptr = malloc(sizeof(char) *len);
stats_reply__pack(&reply, result_ptr);
*buff = result_ptr;
return len;
}
unsigned int view_stats_get_qps(view_stats_t *vs, char **buff)
{
return _view_stats_result2(vs->qps, "qps", buff);
}
unsigned int view_stats_get_success_rate(view_stats_t *vs, char **buff)
{
return _view_stats_result2(vs->success_rate, "success_rate", buff);
}
|
C
|
#include <stdio.h>
static int setbits(int x, int p, int n, int y);
int main(void)
{
int x = 0x0, y = 0xFF;
printf("%0#x\n", setbits(x, 8, 3, y));
return 0;
}
static int setbits(int x, int p, int n, int y)
{
x &= ~(~(~0 << n) << p - n);
return x |= (~(~0 << n) & y) << p - n;
}
|
C
|
/**
* This implementation uses a doubly linked free list, which is addressed by global pointers 'head' and 'tail.'
* The free list is grown by appending in 'free'
* malloc uses helper functions to attempt to find a free block of valid size using a first fit algorithm,
* if a block large enough is not found malloc will call a set of functions that call sbrk
* to allocate apprpriate new space on the heap.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
/* single word (4) or double word (8) alignment */
#define ALIGNMENT 8
/* rounds up to the nearest multiple of ALIGNMENT */
#define ALIGN(size) (((size) + (ALIGNMENT-1)) & ~0x7)
#define SIZE_T_SIZE (ALIGN(sizeof(size_t)))
//block metadata
typedef struct block_head block_head;
struct block_head{
size_t size;
block_head *next;
block_head *prev;
int free; //1 if free 0 if allocated
};
/**
* globals
* */
void *head; //head of block list
void *tail;
// int malloc_count;
/**
* Helper functions
* */
/**
* Testing functions
* */
/**
* For testing purposes: prints text representation of block with size and allocated status
**/
void printlist(){
block_head *itr = head;
printf("\n");
while(itr){
printf("[%d] %d->",itr->free, itr->size);
itr = itr->next;
}
printf("\n");
}
/**
* searches free list and returns block with appropriate size
* **/
block_head *search_free(size_t size){
// printf("search free\n");
block_head *itr = (block_head*)head;
//first fit
while(itr){
// printf("%d, %d: %d\n", itr->free, itr->size, size);
if((itr->size>=size)){
return itr;
}
itr = itr->next;
}
// printf("/search free\n");
return NULL;
// //best fit
// int dif = -1;
// int newdif = -1;
// block_head *bestfit = NULL;
// while(itr){
// newdif = (itr->size) - size;
// if(newdif>=0 && newdif<dif){
// dif = newdif;
// bestfit = itr;
// }
// itr = itr->next;
// }
// return bestfit;
}
/**
* increase heap size, maintaining 8 byte alignment
* returns pointer to beginning of newly allocated heap area
* **/
block_head *inc_heap(size_t size){
// printf("inc heap\n");
block_head *block;
size_t brksize = ALIGN(size); //get aligned size to addr
brksize += sizeof(block_head);
block = sbrk(brksize);
block->free = 0; //malloc'd
block->size = size;
return block;
}
/**
* removes block from free list
* **/
void remove_block(block_head* remove){
// printf("remove_block\n");
if(!remove){
printf("ERROR****: null ptr passed to remove_block");
exit(EXIT_FAILURE);
}
if(remove==head){head=((block_head*)head)->next;}
if(remove==tail){tail=((block_head*)tail)->prev;}
if(remove->next){remove->next->prev=remove->prev;}
if(remove->prev){remove->prev->next=remove->next;}
// printf("/remove_block\n");
}
/**
* coalesces adjacent blocks into large free block
* runs in n^2 time where n = number of blocks in list
* **/
void coalesce(){
// printf("coalescing block\n ***");
// printlist();
//for block i in list
block_head *itrx = (block_head*)head;
while(itrx){
//for block j in list
block_head *itry = (block_head*)head;
while(itry){
if(itry==itrx){
itry = itry->next;
continue;
}
unsigned long mem_dif;
if((unsigned long)itrx>(unsigned long)itry){ //y is first, create large block at y
mem_dif = ((unsigned long)(itrx) - (unsigned long)(itry));
if(mem_dif <= (itry->size)+8+sizeof(block_head)){ //extra 8 bytes is for potential size alignment
remove_block(itrx);
itry->size = (itry->size) + (itrx->size);
return;
}
}else{
mem_dif = ((unsigned long)(itry) - (unsigned long)(itrx));
if(mem_dif <= (itrx->size)+8+sizeof(block_head)){
remove_block(itry);
itrx->size = (itry->size) + (itrx->size);
return;
}
}
// printf("itry size: %d\n", itry->size);
itry=itry->next;
}
// printf("itrx size: %d\n", itrx->size);
itrx = itrx->next;
}
// printlist();
}
//"overload" for check to allow checking of specified range
int check_bounds(void *start, void *end){
if(!start){
printf("check: start node null\n");
return -1;
}
int ret = 1;
block_head *itr = (block_head*)start;
block_head *fin = (block_head*)end;
while(itr && itr!=fin){
//check blocks are marked as free
if(itr->free!=1){
printf("MEM CHECK ERROR****: Block at ddress %p is not marked as free\n", itr);
ret = -1;
}
//check address is in heap range
if(!((void*)itr)<sbrk(0)){
printf("MEM CHECK ERROR****: Address %p lies outside the heap\n", itr);
ret = -1;
}
//check block is valid
if(!(0<itr->size && itr->size<10000)){ //since all blocks in trace files are <10,000
printf("MEM CHECK ERROR****: Block at address %p is invalid\n", itr);
ret = -1;
}
itr = itr->next;
}
printf("Heap consistency check completed. See any above errors\n");
return ret;
}
/**
* heap consistency checker
* checks from param start to param end; check(void) will call (head, tail) to check whole list
* assumes params can be cast to valid block pointers or NULL
* returns 1 on success -1 on error
**/
int check(){
return check_bounds(head, tail);
}
/**
* memory management functions:
* */
/*
* init - initialize the malloc package.
*/
int init(void){
// printf("init\n");
head = (block_head*)NULL;
tail = (block_head*)NULL;
// printf("/init\n");
return 0;
}
/*
* malloc - allocates block of size 'size' in free block or new heap space
* returns pointer to newly allocated payload
*/
void *malloc(size_t size){
// printf("malloc\n");
block_head *block;
block = search_free(size);
if(!block){ //no block found - append to list
block = inc_heap(size);
}else{
// printf("found free, %d\n", block->size);
remove_block(block); //remove from free list
}
// printlist();
return (block+1);
}
/*
* free - frees payload pointed at by param 'ptr'
* appends new block to end of free list
* calls coalesce after new block has been inserted
*/
void free(void *ptr){
// printf("free\n");
if(!ptr){
printf("ERROR** null ptr passed to free");
return;
}
block_head *block = (block_head*)ptr-1;
// printf("freeing size %d\n", block->size);
block->free = 1;
block->next = NULL;
block->prev = tail;
if(!head){
head = block;
tail = block;
}else{
if(tail){((block_head*)tail)->next = block;}
tail = block;
}
// coalesce();
// printlist();
}
void *realloc(void *ptr, size_t size){
block_head *newblock = malloc(size);
block_head *oldblock = (block_head*)ptr-1;
if (newblock == NULL || oldblock == NULL){
return NULL;
}
if(size < oldblock->size){
memcpy(newblock, ptr, ALIGN(size));
}else{
memcpy(newblock, ptr, ALIGN(oldblock->size));
}
free(ptr);
return newblock;
}
|
C
|
/*
** EPITECH PROJECT, 2018
** client.c
** File description:
** client.c
*/
#include "../../include/client.h"
char **split_to_tab(char **cmd, char *str, char c)
{
int i = 0;
int u = 0;
int v = 0;
while (str[i] != '\0' && str[i] != c)
i++;
u = strlen(str);
cmd[0] = malloc(sizeof(char) * (i + 1));
cmd[1] = malloc(sizeof(char) * u);
while (v != i) {
cmd[0][v] = *str;
v++;
str++;
}
cmd[0][v] = '\0';
str++;
cmd[1] = str;
if (*str == '\n' || *str == '\r' || *str == '\0')
cmd[1][0] = '\0';
return (cmd);
}
int manage_cmd(client_t *client)
{
char *cmd;
char **param_full;
char *param;
cmd = xgetline(0);
param_full = malloc(sizeof(char *) * 2);
param_full = split_to_tab(param_full, cmd, ' ');
param = strdup(param_full[1]);
if (strcasecmp(param_full[0], "/server") == 0) {
fct_server(param, client);
return (0);
}
else if (param_full[1])
dprintf(client->fd_client
, "%s:%s", param_full[0], param_full[1]);
else
dprintf(client->fd_client, "%s", param_full[0]);
return (0);
}
int read_serv(client_t *client, fd_set *readfd)
{
char *serv_info;
(void)readfd;
printf("lol\n");
serv_info = xgetline(client->fd_client);
printf("loll\n");
printf("->%s\n", serv_info);
return (0);
}
int main(void)
{
fd_set readfd;
int fdmax;
client_t client;
client.fd_client = 0;
client.co_status = 0;
while (1) {
printf("->");
fflush(NULL);
FD_ZERO(&readfd);
FD_SET(0, &readfd);
fdmax = client.fd_client + 1;
select(fdmax, &readfd, NULL, NULL, NULL);
if (FD_ISSET(0, &readfd))
manage_cmd(&client);
FD_SET(client.fd_client, &readfd);
if (FD_ISSET(client.fd_client, &readfd)) {
read_serv(&client, &readfd);
}
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#define DEBUG
#define bool int
#define true 1
#define false 0
int num[10];
char input[11];
bool CheckValidity(void)
{
char tmp[11];
int slus=0,i = 0,k=0;
long double temp;
memset(tmp, 11, sizeof(char));
memset(num, 11, sizeof(int));
for (i = 0; i < sizeof(input); i++)
{
if (slus==1)
k=i-1;
else
k=i;
switch(input[i]) {
case '0' : num[k]=0;break;
case '1' : num[k]=1;break;
case '2' : num[k]=2;break;
case '3' : num[k]=3;break;
case '4' : num[k]=4;break;
case '5' : num[k]=5;break;
case '6' : num[k]=6;break;
case '7' : num[k]=7;break;
case '8' : num[k]=8;break;
case '9' : num[k]=9;break;
case '/' : {
if ((((num[0]==5)&&(num[1]<=3))||(num[0]<=4))&&(num[0]>=1) )
num[k]=0;
else {
slus = 1;
}
}break;
};
}
for (i=0;i<10;i++)
{
switch(num[i]) {
case 1:tmp[i]='1';break;
case 2:tmp[i]='2';break;
case 3 :tmp[i]='3';break;
case 4:tmp[i]='4';break;
case 5:tmp[i]='5';break;
case 6:tmp[i]='6';break;
case 7:tmp[i]='7';break;
case 8:tmp[i]='8';break;
case 9:tmp[i]='9';break;
case 0:tmp[i]='0';break;
};
}
sscanf(tmp, "%Lf", &temp);
#ifdef DEBUG
printf("Fuck: %s", tmp);
printf("Read int: %.0Lf ", temp);
printf("Num: %d%d%d%d%d%d%d%d%d%d",num[0],num[1],num[2],num[3],num[4],num[5],num[6],num[7],num[8],num[9]);
#endif
if ( (int) temp % 11 == 0)
return true;
else
return false;
return false;
}
int IsBoy()
{
int i=input[2];
if ( (i>=1)&&(i<=12))
return 0;
else if ((i>=51)&&(i<=62))
return 1;
else
return 2;
return 2;
}
int main()
{
memset(input, 11, sizeof(char));
do {
fgets(input, 11, stdin);
if (CheckValidity())
switch (IsBoy()) {
case 0 : printf("Boy\n");break;
case 1: printf("Girl\n");break;
case 2: printf("Invalid\n");break;
}
else
printf("Invalid\n");
} while (strcmp(input, "end\n" ) != 0);
return 0;
}
|
C
|
/*
*
* 15. Faça um programa que leia o comprimento, a altura e a espessura de um sólido cúbico, calcule e imprima o volume do mesmo.
* Os valores de entrada podem não ser inteiros.
*
*
*/
#include <?????.h>
int ????()
{
????? comprimento = ????;
????? ?????? = ????;
????? espessura = ????;
????? ?????? = ????;
??????("Informe o comprimento do solido cubico: ");
?????("??", ?comprimento);
??????("Informe a altura do solido cubico: ");
?????("??", ?altura);
printf("Informe a espessura do solido cubico: ");
scanf("??", ?espessura);
?????? = comprimento ? ?????? ? espessura;
printf("O volume do solido cubico e: ??", ??????);
?????? 0;
}
|
C
|
#include <stdio.h>
#define FUNDLEN 50
struct funds {
char bank[FUNDLEN];
double bankfund;
char save[FUNDLEN];
double savefund;
};
double sum(struct funds moolah); /* argument is a structure */
int main(void)
{
struct funds stan = {
"Garlic-Melon Bank",
4032.27,
"Lucky's Saving and Loan",
8543.94
};
printf("Stan has a total of $%.2f.\n", sum(stan));
return 0;
}
double sum(struct funds moolah)
{
return (moolah.bankfund + moolah.savefund);
}
|
C
|
/*Write a C program to input basic salary of an
employee and calculate its Gross salary
according to following:
Basic Salary <= 10000 : HRA = 20%, DA = 80%
Basic Salary <= 20000 : HRA = 25%, DA = 90%
Basic Salary > 20000 : HRA = 30%, DA = 95%
*/
#include<stdio.h>
void main()
{
float basic,hra,da,gross;
printf("\n Enter basic salary ");
scanf("%f",&basic);
if(basic>=20000)
{
gross=(225*basic)/100;
printf("\nGross salary is %.2f",gross);
}
else if((basic>=10000)&&(basic<20000))
{
gross=(215*basic)/100;
printf("\nGross salary is %.2f",gross);
}
else
{
gross=(200*basic)/100;
printf("\nGross salary is %.2f",gross);
}
}
|
C
|
/*
============================================================================
Name : testAsyncSocket.c
Author : vincent
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <memory.h>
#include <unistd.h>
#include <assert.h>
#include "hiredis.h"
#include "async.h"
#include "ae.h"
#include "easy_async.h"
#include "zmalloc.h"
/* Put event loop in the global scope, so it can be explicitly stopped */
static aeEventLoop *loop;
static void __redisSetError(redisContext *c, int type, const char *str) {
size_t len;
c->err = type;
if (str != NULL) {
len = strlen(str);
len = len < (sizeof(c->errstr)-1) ? len : (sizeof(c->errstr)-1);
memcpy(c->errstr,str,len);
c->errstr[len] = '\0';
} else {
/* Only REDIS_ERR_IO may lack a description! */
assert(type == REDIS_ERR_IO);
strerror_r(errno,c->errstr,sizeof(c->errstr));
}
}
void getCallback(redisAsyncContext *c, void *r, void *privdata) {
printf("argv[%s]\n", (char*)privdata);
/* Disconnect after receiving the reply to GET */
redisAsyncDisconnect(c);
}
/* Use this function to handle a read event on the descriptor. It will try
* and read some bytes from the socket and feed them to the reply parser.
*
* After this function is called, you may use redisContextReadReply to
* see if there is a reply available. */
int easyBufferRead(redisContext *c) {
char buf[1024*16]={0};
int nread;
/* Return early when the context has seen an error. */
if (c->err)
return REDIS_ERR;
nread = read(c->fd,buf,sizeof(buf));
if (nread == -1) {
if ((errno == EAGAIN && !(c->flags & REDIS_BLOCK)) || (errno == EINTR)) {
/* Try again later */
} else {
__redisSetError(c,REDIS_ERR_IO,NULL);
return REDIS_ERR;
}
} else if (nread == 0) {
__redisSetError(c,REDIS_ERR_EOF,"Server closed the connection");
return REDIS_ERR;
} else {
printf("buf == %s \n",buf+2);
}
return REDIS_OK;
}
/* Write the output buffer to the socket.
*
* Returns REDIS_OK when the buffer is empty, or (a part of) the buffer was
* succesfully written to the socket. When the buffer is empty after the
* write operation, "done" is set to 1 (if given).
*
* Returns REDIS_ERR if an error occured trying to write and sets
* c->errstr to hold the appropriate error string.
*/
int easyBufferWrite(redisContext *c, int *done) {
int nwritten;
/* Return early when the context has seen an error. */
if (c->err)
return REDIS_ERR;
if (sdslen(c->obuf) > 0) {
nwritten = write(c->fd,c->obuf,sdslen(c->obuf));
if (nwritten == -1) {
if ((errno == EAGAIN && !(c->flags & REDIS_BLOCK)) || (errno == EINTR)) {
/* Try again later */
} else {
__redisSetError(c,REDIS_ERR_IO,NULL);
return REDIS_ERR;
}
} else if (nwritten > 0) {
if (nwritten == (signed)sdslen(c->obuf)) {
sdsfree(c->obuf);
c->obuf = sdsempty();
} else {
sdsrange(c->obuf,nwritten,-1);
}
}
}
if (done != NULL) *done = (sdslen(c->obuf) == 0);
return REDIS_OK;
}
void connectCallback(const redisAsyncContext *c, int status) {
printf("connectCallback status=== %d\n",status);
if (status != REDIS_OK) {
printf("Error: %s\n", c->errstr);
aeStop(loop);
return;
}
printf("Connected...\n");
}
void disconnectCallback(const redisAsyncContext *c, int status) {
printf("disconnectCallback status=== %d\n",status);
if (status != REDIS_OK) {
printf("Error: %s\n", c->errstr);
aeStop(loop);
return;
}
printf("Disconnected...\n");
aeStop(loop);
}
int main (int argc, char **argv) {
signal(SIGPIPE, SIG_IGN);
redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 8888);
if (c->err) {
/* Let *c leak for now... */
printf("Error: %s\n", c->errstr);
return 1;
}
easy_buffer_callback * buff_callback;
buff_callback =(easy_buffer_callback *) zmalloc(sizeof(*buff_callback));
buff_callback->read_callback = easyBufferRead;
buff_callback->write_callback = easyBufferWrite;
c->data = buff_callback;
loop = aeCreateEventLoop(64);
easyAeAttach(loop, c);
redisAsyncSetConnectCallback(c,connectCallback);
redisAsyncSetDisconnectCallback(c,disconnectCallback);
aeMain(loop);
return 0;
}
|
C
|
#include "binary_trees.h"
/**
* binary_tree_insert_right - inserts a node as the left-child of another node
* @parent: a pointer to the node to insert the left-child in
* @value: the value to store in the new node
* Return: pointer to the created node or NULL on failure or if parent is NULL
*/
binary_tree_t *binary_tree_insert_right(binary_tree_t *parent, int value)
{
binary_tree_t *newnode = NULL;
if (parent == NULL)
return (NULL);
newnode = malloc(sizeof(binary_tree_t));
if (newnode == NULL)
return (NULL);
newnode->left = NULL;
newnode->n = value;
if (parent->right != NULL)
{
parent->right->parent = newnode;
}
newnode->right = parent->right;
parent->right = newnode;
newnode->parent = parent;
return (newnode);
}
|
C
|
#include <SDL.h>
#include "system/stacktrace.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "math/pi.h"
#include "system/line_stream.h"
#include "system/log.h"
#include "system/lt.h"
#include "system/nth_alloc.h"
#include "wavy_rect.h"
#define WAVE_PILLAR_WIDTH 10.0f
struct Wavy_rect
{
Lt *lt;
Rect rect;
Color color;
float angle;
};
Wavy_rect *create_wavy_rect(Rect rect, Color color)
{
Lt *lt = create_lt();
Wavy_rect *wavy_rect = PUSH_LT(lt, nth_calloc(1, sizeof(Wavy_rect)), free);
if (wavy_rect == NULL) {
RETURN_LT(lt, NULL);
}
wavy_rect->rect = rect;
wavy_rect->color = color;
wavy_rect->angle = 0.0f;
wavy_rect->lt = lt;
return wavy_rect;
}
void destroy_wavy_rect(Wavy_rect *wavy_rect)
{
trace_assert(wavy_rect);
RETURN_LT0(wavy_rect->lt);
}
int wavy_rect_render(const Wavy_rect *wavy_rect,
const Camera *camera)
{
trace_assert(wavy_rect);
trace_assert(camera);
srand(42);
for (float wave_scanner = 0;
wave_scanner < wavy_rect->rect.w;
wave_scanner += WAVE_PILLAR_WIDTH) {
const float s = (float) (rand() % 50) * 0.1f;
if (camera_fill_rect(
camera,
rect(
wavy_rect->rect.x + wave_scanner,
wavy_rect->rect.y + s * sinf(wavy_rect->angle + wave_scanner / WAVE_PILLAR_WIDTH),
WAVE_PILLAR_WIDTH * 1.20f,
wavy_rect->rect.h),
wavy_rect->color) < 0) {
return -1;
}
}
srand((unsigned int) time(NULL));
return 0;
}
int wavy_rect_update(Wavy_rect *wavy_rect,
float delta_time)
{
trace_assert(wavy_rect);
wavy_rect->angle = fmodf(wavy_rect->angle + 2.0f * delta_time, 2 * PI);
return 0;
}
Rect wavy_rect_hitbox(const Wavy_rect *wavy_rect)
{
return wavy_rect->rect;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct link
{
char data;
struct link *next;
}LINK;
LINK *node()
{
LINK *head=NULL,*p,*rear;
char ch;
head=(LINK*)malloc(sizeof(LINK));
printf("input ch till ch!=@\n");
ch=getchar();
rear=p=head;
while(ch!='@')
{
p=(LINK*)malloc(sizeof(LINK));
p->data=ch;
rear->next=p;
rear=p;
ch=getchar();
}
rear->next=NULL;
return head;
}
LINK* insert(LINK *s,LINK *t,char ch)
{
LINK *p,*q,*l;
p=t;
q=t->next;
if(q==NULL) return s;
p=q;
q=q->next;
while(q)
{
if(p->data==ch)
break;
p=q;
q=q->next;
}
if(q==NULL){
p->next=s->next;
return t;
}
l=s;
while(l->next)
{
l=l->next;
}
p->next=s->next;
l->next=q;
return t;
}
int main()
{
LINK *h1=NULL,*h2=NULL,*head=NULL,*p;
h1=node();
getchar();
h2=node();
getchar();
char ch;
printf("input ch:");
ch=getchar();
head=insert(h1,h2,ch);
p=head->next;
while(p){
putchar(p->data);
p=p->next;
}
return 0;
}
|
C
|
// Licensed under the MIT license.
// See the LICENSE file in the project root for more information.
#include "point.h"
#pragma once
// Windows APIs are C style and use the __stdcall calling convention (the callee cleans the stack).
// The standard C calling convention is __cdecl (the caller cleans the stack, allows variable argument lists).
extern "C" __declspec (dllexport) int DoubleCDeclImplicit(int value);
extern "C" __declspec (dllexport) int __cdecl DoubleCDeclExplicit(int value);
extern "C" __declspec (dllexport) int __stdcall DoubleStdCall(int value);
extern "C" __declspec (dllexport) int __stdcall Double(int value);
extern "C" __declspec (dllexport) int __stdcall Sum(int* values, int count);
extern "C" __declspec (dllexport) int AddCDecl(int a, int b);
extern "C" __declspec (dllexport) int __stdcall CharToIntW(wchar_t value);
extern "C" __declspec (dllexport) void* __stdcall StringPass(wchar_t* value, int count);
extern "C" __declspec (dllexport) errno_t __stdcall CopyString(wchar_t* source, wchar_t* destination, int destinationLength);
extern "C" __declspec (dllexport) void* __stdcall DoubleByRef(int* value);
extern "C" __declspec (dllexport) BOOL __stdcall Invert(BOOL value);
extern "C" __declspec (dllexport) void* __stdcall InvertByRef(BOOL* value);
extern "C" __declspec (dllexport) void* __stdcall GetMeaning(int* value);
extern "C" __declspec (dllexport) void __stdcall SwapPoint(Point* point);
extern "C" __declspec (dllexport) void __stdcall SwapPoints(Point* points, int count);
extern "C" __declspec (dllexport) void* __stdcall IntsPointer(int* values);
extern "C" __declspec (dllexport) void* __stdcall PointsPointer(Point* points);
extern "C" __declspec (dllexport) void __stdcall FlipPointers(void** first, void** second);
extern "C" __declspec (dllexport) void* __stdcall VoidReturn();
extern "C" __declspec (dllexport) void __stdcall VoidPass(void* handle);
|
C
|
/******************************************************************************
*
* Filename: $line.c
* Created on: $Date: Mar 25, 2014 (6:00:07 PM)
* Revision: $1
* Author: $GadgEon
*
* Description: $This file contains functions to to draw graphics on lcd
*
* Copyright (C) 2014 GadgEon System Pvt Ltd - http://www.gadgeon.com
*
*****************************************************************************/
#include "line.h"
volatile uint_8 Flip_Status = 1;
extern void draw_pixel(uint_16, uint_16, uint_8);
extern void draw_line_vertical(uint_8, uint_16, uint_16, uint_8);
void draw_line_horizontal(uint_8 X1, uint_8 X2, uint_16 Y, uint_8 pixel);
void draw_dithered_line_horizontal(uint_8 X1, uint_8 X2, uint_16 Y, uint_8 pixel);
void Rect_fill_with_horizontal_lines(uint_8 X1, uint_16 Y1, uint_8 X2, uint_16 Y2, uint_8 pixel);
//void Rect_fill_with_dithered_lines(uint_8 X1, uint_16 Y1, uint_8 X2, uint_16 Y2, uint_8 pixel);
/*-----------------------------------------------------------------------------
* Function: Draw_Pixel
* Brief: Draw a pixel on specified X Y coordinate of Frame buffer
* Parameter: X,Y coordinate and pixel colour
* Return: None
-----------------------------------------------------------------------------*/
void draw_pixel(uint_16 X, uint_16 Y, uint_8 pixel)
{
uint_16 byte_index = 0;
uint_8 buffer_data = 0, pixel_offset = 0;
if ((X < X_MIN) || (X > X_MAX) || (Y < Y_MIN) || (Y > Y_MAX))
{
return;
}
/*Byte location in the global LCD buffer*/
if (Flip_Status == 0)
{
byte_index = ((X - 1) * LINE_BYTES) + ((Y_MAX - (Y - 1)) >> 3);
/*Pixel offset in the Byte */
pixel_offset = ((Y - 1) & 0x07);
if (Y && !pixel_offset)
byte_index--;
}
else
{
byte_index = ((X_MAX - X) * LINE_BYTES) + ((Y - 1) >> 3);
/*Pixel offset in the Byte */
pixel_offset = (8 - ((Y - 1) & 0x07)) & 0x07;
if (Y && !pixel_offset)
byte_index--;
}
/*Extracting the byte from frame buffer */
buffer_data = frame_buff[byte_index];
/*Clearing and adding new pixel to byte */
buffer_data &= ~(0x01 << pixel_offset);
buffer_data |= (pixel << pixel_offset);
/*Updating new byte to frame buffer*/
frame_buff[byte_index] = buffer_data;
}
/*-----------------------------------------------------------------------------
* Function: Draw_Line_V
* Brief: Draw vertical line on Frame buffer
* Parameter: X,Y coordinate and pixel colour
* Return: None
-----------------------------------------------------------------------------*/
void draw_line_vertical(uint_8 X, uint_16 Y1, uint_16 Y2, uint_8 pixel)
{
uint_8 pixel_mask1, pixel_mask2, buffer_data;
uint_16 Y1_address, Y2_address, byte_index;
if (Flip_Status == 1)
{
uint_16 temp = Y1;
if((Y2>Y_MAX)&&(Y1>Y_MAX)&&(X>X_MAX))
{
printf("draw_line_vertical Error...\n");
while(1)
{
}
}
Y1 = (Y_MAX+1) - Y2;
Y2 = (Y_MAX+1) - temp;
X = (X_MAX+1) - X;
}
pixel_mask1 = 0xFF >> (0x07 - ((Y2 - 1) & 0x07));
pixel_mask2 = (0xFF << ((Y1 - 1) & 0x07));
Y1_address = ((Y_MAX - (Y1)) >> 3); //Y1>>3;
Y2_address = ((Y_MAX - (Y2)) >> 3); //Y2>>3;
byte_index = (X - 1) * LINE_BYTES + Y2_address;
buffer_data = frame_buff[byte_index];
if (Y1_address != Y2_address)
{
if (!pixel)
// buffer_data ^= pixel_mask1;
buffer_data &=pixel_mask1;
else
buffer_data |= pixel_mask1;
frame_buff[byte_index++] = buffer_data;
Y2_address++;
while (Y1_address > Y2_address)
{
if (pixel)
frame_buff[byte_index++] = 0xFF;
else
frame_buff[byte_index++] = 0x00;
Y2_address++;
}
buffer_data = frame_buff[byte_index];
if (!pixel)
buffer_data &= pixel_mask2;
else
buffer_data |= pixel_mask2;
frame_buff[byte_index] = buffer_data;
}
else
{
pixel_mask1 &= pixel_mask2;
if (!pixel)
buffer_data &= pixel_mask1;
else
buffer_data |= pixel_mask1;
frame_buff[byte_index] = buffer_data;
}
}
/*-----------------------------------------------------------------------------
* Function: Draw_Line_H
* Brief: Draw Horizontal line on Frame buffer
* Parameter: X,Y coordinate and pixel colour
* Return: None
-----------------------------------------------------------------------------*/
void draw_line_horizontal(uint_8 X1, uint_8 X2, uint_16 Y, uint_8 pixel)
{
uint_16 x_index;
/*Swap the X coordinates if X1 is greater than X2 */
if (X1 > X2)
{
X1 = X1 + X2;
X2 = X1 - X2;
X1 = X1 - X2;
}
/* Draw continues pixel to make a line*/
for (x_index = X1; x_index <= X2; x_index++)
draw_pixel(x_index, Y, pixel);
}
/*-----------------------------------------------------------------------------
* Function: draw_dithered_line_horizontal
* Brief: Draw Dithered Horizontal line on Frame buffer
* Parameter: X,Y coordinate and pixel colour
* Return: None
-----------------------------------------------------------------------------*/
void draw_dithered_line_horizontal(uint_8 X1, uint_8 X2, uint_16 Y, uint_8 pixel)
{
uint_16 x_index;
/*Swap the X coordinates if X1 is greater than X2 */
if (X1 > X2)
{
X1 = X1 + X2;
X2 = X1 - X2;
X1 = X1 - X2;
}
/* Draw continues pixel to make a line*/
for (x_index = X1; x_index <= X2; x_index++)
{
draw_pixel(x_index, Y, pixel);
pixel ^= 1;
}
}
/*-----------------------------------------------------------------------------
* Function: Rect_fill_with_horizontal_lines
* Brief: Fill a rectangle with dithered lines on Frame buffer
* Parameter: X,Y coordinate and pixel colour
* Return: None
-----------------------------------------------------------------------------*/
void Rect_fill_with_horizontal_lines(uint_8 X1, uint_16 Y1, uint_8 X2, uint_16 Y2, uint_8 pixel)
{
if (Y1 > Y2)
{
Y1 = Y1 + Y2;
Y2 = Y1 - Y2;
Y1 = Y1 - Y2;
}
while(Y1<=Y2)
{
draw_line_horizontal(X1,X2,Y1,pixel);
++Y1;
}
}
void Rect_fill_with_dithered_lines(uint_8 X1, uint_16 Y1, uint_8 X2, uint_16 Y2, uint_8 pixel)
{
if (Y1 > Y2)
{
Y1 = Y1 + Y2;
Y2 = Y1 - Y2;
Y1 = Y1 - Y2;
}
while(Y1<=Y2)
{
draw_dithered_line_horizontal(X1,X2,Y1,pixel);
++Y1;
pixel ^= 1;
}
}
/*-----------------------------------------------------------------------------
* Function: Draw_Rect
* Brief: Draw a Rectangle on Frame buffer
* Parameter: X,Y coordinate and pixel colour
* Return: None
-----------------------------------------------------------------------------*/
void Draw_Rect(uint_16 X1, uint_16 Y1, uint_16 X2, uint_16 Y2, uint_8 pixel)
{
/*Swap the Y coordinates if Y1 is greater than Y2 */
if (Y1 > Y2)
{
Y1 = Y1 + Y2;
Y2 = Y1 - Y2;
Y1 = Y1 - Y2;
}
/*Swap the X coordinates if X1 is greater than X2 */
if (X1 > X2)
{
X1 = X1 + X2;
X2 = X1 - X2;
X1 = X1 - X2;
}
/* Draw Horizontal Top line*/
draw_line_horizontal(X1, X2, Y1, pixel);
/* Draw Horizontal Bottom line*/
draw_line_horizontal(X1, X2, Y2, pixel);
/* Draw Vertical Left line*/
draw_line_vertical(X1, Y1, Y2, pixel);
/* Draw Vertical Right line*/
draw_line_vertical(X2, Y1, Y2, pixel);
}
/*-----------------------------------------------------------------------------
* Function: Rect_Fill
* Brief: Fill the rectangle with specified colour
* Parameter: X,Y coordinate and pixel colour
* Return: None
-----------------------------------------------------------------------------*/
void Rect_Fill(uint_8 X1, uint_16 Y1, uint_8 X2, uint_16 Y2, uint_8 pixel)
{
/*Swap the Y coordinates if Y1 is greater than Y2 */
if (Y1 > Y2)
{
Y1 = Y1 + Y2;
Y2 = Y1 - Y2;
Y1 = Y1 - Y2;
}
/*Swap the X coordinates if X1 is greater than X2 */
if (X1 > X2)
{
X1 = X1 + X2;
X2 = X1 - X2;
X1 = X1 - X2;
}
/*Fill with Vertical Lines*/
do
{
// Draw_Line_H(X1,X2,Y1,pixel);
draw_line_vertical(X1, Y1, Y2, pixel);
// Draw_Line(X1,Y1,X2,Y2,pixel);
} while (X1++ < X2);
}
/*-----------------------------------------------------------------------------
* Function: Draw_Dithered_Line
* Brief: Draw a Dithered Line on Frame buffer
* Parameter: X,Y coordinate and pixel colour
* Return: None
-----------------------------------------------------------------------------*/
void Draw_Dithered_Line(uint_16 X1, uint_16 Y1, uint_16 X2, uint_16 Y2, uint_8 pixel)
{
uint_16 x, y;
int_16 dx, dy;
/*Swap the X coordinates if X1 is greater than X2 */
if (X1 > X2)
{
X1 = X1 + X2;
X2 = X1 - X2;
X1 = X1 - X2;
}
dx = X2 - X1;
dy = Y2 - Y1;
for (x = X1; x <= X2; x++)
{
y = Y1 + (dy) * (x - X1) / (dx);
draw_pixel(x, y, pixel);
pixel ^= 1;
}
}
/*-----------------------------------------------------------------------------
* Function: Draw_Line
* Brief: Draw a Line on Frame buffer
* Parameter: X,Y coordinate and pixel colour
* Return: None
-----------------------------------------------------------------------------*/
void Draw_Line(uint_16 X1, uint_16 Y1, uint_16 X2, uint_16 Y2, uint_8 pixel)
{
uint_16 x, y;
int_16 dx, dy;
/*Swap the X coordinates if X1 is greater than X2 */
if (X1 > X2)
{
X1 = X1 + X2;
X2 = X1 - X2;
X1 = X1 - X2;
}
dx = X2 - X1;
dy = Y2 - Y1;
for (x = X1; x <= X2; x++)
{
y = Y1 + (dy) * (x - X1) / (dx);
draw_pixel(x, y, pixel);
}
}
/*-----------------------------------------------------------------------------
************************* END **********************************
-----------------------------------------------------------------------------*/
|
C
|
/*
* main.c
*
* Created on: Mar 3, 2015
* Author: skynet
*/
#include <stdio.h>
#include "sir.h"
int main()
{
int n;
printf("Introduceti termenii sirului:\n");
n=tip_sir(); //apelam functia tip_sir() care citeste si analizeaza sirul primit de la tastatura; returneaza tipul sirului analizat (un numar de la 1 la 6)
afisare_tip(n); //dupa ce s-a stabilit tipul sirului, apelam functia afisare_tip(), care, cu ajutorul parametrului n (tipul sirului) afiseaza pe ecran mesajul corespunzator tipului respectiv
return 0;
}
|
C
|
#ifndef HW2_UTIL_H
#define HW2_UTIL_H
#include <arpa/inet.h>
#include "msg_header.h"
/* struct for linked lsit */
typedef struct group_node {
uint16_t uid;
struct group_node * next;
} group_node_t;
/**
* @brief Send a file through socket
*
* @param sockfd socket to send to
* @param gid gid for the header
* @param uid uid for the header
* @param filename path of file to write to
*
* @return 0 on success, -1 on failure
*/
int send_file( int sockfd, uint8_t gid, uint16_t uid, char *filename );
/**
* @brief Write data received from socket to file
*
* @param sockfd socket to read from
* @param len number of bytes to read
* @param filename path of file to write to
*
* @return 0 on success, -1 on failure
*/
int receive_to_file( int sockfd, int len, char * filename );
/**
* @brief add an uid to the end of the group list
*
* @param head head of the group list
* @param uid uid to be add to group list
*
* @return 0 on success, -1 on failure
*/
int group_add_tail( group_node_t *head, uint16_t uid );
/* Returns 1 if successful, 0 if not*/
int send_main_header(mainhdr_t* hdr, int fd);
/* User needs to free mainhdr*/
mainhdr_t* fill_username_password(char *username, char *password);
/* User needs to free mainhdr.
* returns NULL if error occurred
*
*/
mainhdr_t* read_main_header(int fd);
/* Returns:
* 0 if connection was closed
* -1 if error occured
* 1 if read was successful
*
*/
int recv_wrapper(int fd, char *buff, int num_bytes);
/* Returns:
* 0 if connection was closed
* -1 if error occured
* 1 if read was successful
*
*/
int send_wrapper(int fd, char*buff, int num_bytes);
/**
* @param dest_uname location of to copy the username to
* @param dest_pw location to copy the password to
* @param payload payload received in the packet
* @param len len of payload, get from the header len field
*
* @return 0 on success, non-zero on failure
*/
int parse_username_pw( char * dest_uname, char * dest_pw, char * payload, int len );
/**
* @brief Function to allocate new packet with mainhdr_t, caller needs to
* free the returned pointer after.
*
* @param cmd cmd field for new header
* @param gid gid field for new header
* @param uid uid field for new header
* @param len payload len for the new header, also how many
* bytes to allocate for the new header
*
* @return malloc'ed header with desire length, NULL on failure
*/
mainhdr_t * create_and_fill_hdr( uint8_t cmd, uint8_t gid, uint16_t uid, uint32_t len );
// http://source-code-share.blogspot.com/2014/07/implementation-of-java-stringsplit.html
int split (char *str, char c, char ***arr);
/**
* @brief Check the header input for invite and invite response message
*
* @param packet header to be ckecked
*
* @return 0 on success, -1 on failure
*/
int check_header_invite( mainhdr_t * packet );
/**
* @brief Check the header input for chatmessage
*
* @param packet header to be ckecked
*
* @return 0 on success, -1 on failure
*/
int check_header_chat( mainhdr_t * packet );
#endif /* HW2_UTIL_H */
|
C
|
#include <stdio.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define NAME "T6PXGV"
#define SIZE 64
int main() {
pid_t _pid;
int _fifo;
int _open;
char _buffer[SIZE];
int _temp;
_pid = fork();
if (_pid == -1) {
perror("fork() Error");
exit(-1);
}
if (_pid == 0) { // child
printf("%d: I'm a child\n", getpid());
_open = open(NAME, O_RDWR);
if (_open == -1) {
perror("open() Error");
exit(-1);
}
strcpy(_buffer, "Urbán Milán T6PXGV\0");
write(_open, _buffer, SIZE);
close(_open);
exit(1);
} else { // parent
printf("%d: I'm a parent [1.]\n", getpid());
_fifo = mkfifo(NAME, 0666);
if (_fifo == -1) {
perror("mkfifo() Error");
exit(-1);
}
close(_fifo);
wait(NULL);
printf("%d: I'm a parent [2.]\n", getpid());
_open = open(NAME, O_RDWR);
if (_open == -1) {
perror("open()");
exit(-1);
}
printf("0\n");
while (read(_fifo, _buffer, SIZE) > 0) {
printf("%s", _buffer); // olvasok
}
printf("\n");
close(_open);
unlink(NAME);
exit(1);
}
return 0;
}
|
C
|
// File Name: a.c
// Author: darkdream
// Created Time: 2013年12月13日 星期五 22时01分26秒
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
int main(){
int n ;
int hs[10] = {0};
scanf("%d",&n);
char str[100];
for(int i =1;i <= 4;i ++)
{
scanf("%s",str);
for(int j =0 ;j <4;j++)
{
if(str[j] != '.')
hs[str[j] -'0'] ++;
}
}
for(int i =1;i <= 9 ;i ++)
{
if(hs[i] > 2*n)
{
printf("NO\n");
return 0;
}
}
printf("YES\n");
return 0 ;
}
|
C
|
/*
Given an array of values,
design and code an algorithm that returns whether there are two duplicates within k indices of each other?
k indices and within plus or minus l (value) of each other? Do all, even the latter, in O(n) running time and O(k) space.
*/
|
C
|
#include <stdio.h>
int main()
{
int t, i;
long long int n, k;
scanf("%d", &t);
for(i = 0; i < t; i++)
{
scanf("%lld", &n);
k = 3 * ((n * (n + 1))/2) - n;
k = k % 1000007;
printf("%lld\n", k);
}
return 0;
}
|
C
|
#include "gamemodes.h"
U64 keytable[MAXTURNS+1]; // use this to check if a the same boardstate has been seen 3 times for drawing, plus 1 for tracking length
void
setKeytable(U64 firstkey)
{
memset(keytable, 0, sizeof(keytable)); // reset the table
keytable[0] = firstkey;
keytable[MAXTURNS+1] = 1;
}
void
isrt()
{
// binary search then memmove and insert
U16 n = keytable[MAXTURNS+1]-1;
U16 m, l = 0, r = n;
U64 x = keytable[r];
while(l<=r) {
m = l + (r - l) / 2;
if (x >= keytable[m] && (x <= keytable[m+1] || keytable[m+1]==0)) { // append
if ((++m)!=n)
memmove(keytable+m+1, keytable+m, (n-m)*8);
keytable[m] = x;
break;
}
if (keytable[m] < x) {
l = m + 1;
} else {
if (m == 0) { // prepend
memmove(keytable+m+1, keytable+m, (n-m)*8);
keytable[m] = x;
break;
}
r = m - 1;
}
}
}
bool
triplication()
{
U8 jmp;
for (U16 i=0; i < (U16) keytable[MAXTURNS+1]-3; i=i+jmp+1) { // check for triples
jmp = 0;
if (keytable[i]==keytable[i+1]) {
jmp++; // we can skip an element we've already checked
if (keytable[i]==keytable[i+2]) {
printf("Key found in 3s: %llu\n", keytable[i]);
return true; // found 3 in a row
}
}
}
return false;
}
void
keytableUpkeep(Boardstate *currBoard)
{
currBoard->key = generateHash(*currBoard);
// sort table
keytable[keytable[MAXTURNS+1]] = currBoard->key; // put at the end of the table
keytable[MAXTURNS+1]++; // increase length
isrt();
}
/*
------------------- END OF KEYTABLE FUNCTIONS -------------------
*/
//TODO get these functions to return something different depending on who wins?
void
localMultiplayer(Boardstate *currBoard)
{
setKeytable(currBoard->key);
puts(currBoard->blackplaying?"\nBlack to play":"\nWhite to play");
prettyPrintBoard(*currBoard);
U8 result = 0;
const U8 strsize = 6; // largest input that will be accepted by stdin
char s[strsize]; // input string
Coord from, to; // movements
while(1) {
from = 0;
to = 0;
readInput(s, strsize);
result = parseInput(s, &from, &to);
if (result==2) break; // quit
if (!result) continue; // if it successfully parsed
if (!movePiece(from, to, true, getPromotion)) continue; // actually move the piece and update currBoard
currBoard->blackplaying=!currBoard->blackplaying; // switch players
if(inCheckMate(*currBoard)) {
prettyPrintBoard(*currBoard);
puts("Checkmate");
break; // end game
}
keytableUpkeep(currBoard);
// Stalemate, 50 moves have passed since a pawn moved/piece was taken, or the same boardstate is seen thrice
if(inStaleMate(*currBoard) || currBoard->halfmove-currBoard->fiftymove==50 || triplication()) {
prettyPrintBoard(*currBoard);
puts("Stalemate");
break; // end game
}
puts(currBoard->blackplaying?"\nBlack to play":"\nWhite to play");
if(inCheck(*currBoard)) puts("Check");
prettyPrintBoard(*currBoard);
}
return;
}
void
localAI(Boardstate *currBoard)
{
setKeytable(currBoard->key);
currBoard->blackplaying?puts("\nBlack to play"):puts("\nWhite to play");
prettyPrintBoard(*currBoard);
U8 result = 0;
const U8 strsize = 6; // largest input that will be accepted by stdin
char s[strsize]; // input string
Coord from, to; // movements
U8 (*promotion)();
char *whiteply = "\nWhite to play";
char *blackply = "\nBlack to play";
if (currBoard->blackplaying) { // to show that the AI is playing
whiteply = "\nAI to play";
} else blackply = "\nAI to play";
for(;;) { // strange things are happening
LOOP: // works ok to me
if(!currBoard->blackplaying) // then white must be playing
{
puts("\a"); // notify that they are to input
readInput(s, strsize);
result = parseInput(s, &from, &to);
if (result==2) break; // quit
promotion = getPromotion;
}
else{ // otherwise let the bot play
result = calculateBestMove(*currBoard, currBoard->blackplaying, 4, &from, &to);
promotion = piecePromotionAI;
}
if (!result) goto LOOP;
result = movePiece(from, to, true, promotion); // record the game and use whichever promotion function fits
if (!result) goto LOOP;
currBoard->blackplaying=!currBoard->blackplaying; // switch players
if(inCheckMate(*currBoard)) {
prettyPrintBoard(*currBoard);
puts("Checkmate");
break; // end game
}
keytableUpkeep(currBoard);
// Stalemate, 50 moves have passed since a pawn moved/piece was taken, or the same boardstate is seen thrice
if(inStaleMate(*currBoard) || currBoard->halfmove-currBoard->fiftymove==50 || triplication()) {
prettyPrintBoard(*currBoard);
puts("Stalemate");
break; // end game
}
puts(currBoard->blackplaying?blackply:whiteply);
if(inCheck(*currBoard)) puts("Check");
prettyPrintBoard(*currBoard);
}
return;
}
|
C
|
#include "param.h"
#define NPSTAT 64
#define NTICKS 500
struct pstat
{
int pid; // PID of each process
char *name; // name of the process
int priority; // current priority level of each process (0-2)
int ticks[3]; // number of ticks each process used the last time it was
// scheduled in each priority queue
// cannot be greater than the time-slice for each queue
int times[3]; // number of times each process was scheduled at each of 3
// priority queues
int queue[NTICKS]; //queue that a RUNNABLE process is sitting in during each tick
int total_ticks; // total number of ticks each RUNNABLE process has
// accumulated in all queues
// this value should be equal to the sum of the 3 values in ticks
int wait_time; // number of ticks each RUNNABLE process waited in the lowest
// priority queue
};
struct pstat pstat_var[NPSTAT];
/*
pid -> DONE. Take from proc stucture
name -> DONE.
priority -> DONE. Update in addToQueue.
ticks -> DONE. Done after timeslice completed in scheduler
times -> DONE. Done after timeslice completed in scheduler
queue -> DONE. Done during each completed tick in updatePstat()
total_ticks -> Done during each completed tick in updatePstat()
wait_time -> Done during each completed tick in updatePstat()
*/
|
C
|
#include <stdio.h>
#include <math.h>
int x,y;
int Tich(int x, int y)
{ int T=0;
if(y == 0 )
return 0;
else T=T+x;
return (T + Tich(x,y-1));
}
int main()
{
printf("Nhap x :");
scanf("%d",&x);
printf("Nhap y:");
scanf("%d",&y);
printf("Ket qua la :%d ",Tich(x,y));
}
|
C
|
//MASM, QEMU
//even = rand()&0xfffffffe;
//odd = rand()|1;
//pipes for communication between threads or via variables
//at the begining one thread the main and it creates other two threads. after the main threads ends the other two must work to print and output in upper case
//three threads that work in three variables, this, next, last
#include <stdio.h>
#include <stdlib.h>
void sort(int *vector, int length);
void writeText(int *vector, char* filename, int length);
void writeBinary(int *vector, char* filename, int length);
int main(int argc, char** argv){
if(argc != 3){
printf("Usage: %s n1 n2\n",argv[0]);
exit(0);
}
int* v1 = malloc(atoi(argv[1]) * sizeof(int*));
int* v2 = malloc(atoi(argv[2]) * sizeof(int*));
for(int i=0; i<atoi(argv[1]); i++){
int r = (rand() % (100-10) + 10)|1 ;
v1[i] = r;
}
for(int i=0; i<atoi(argv[2]); i++){
int r = (rand() % (40) + 10)*2;
v2[i] = r;
}
writeBinary(v1, "fv.b", atoi(argv[1]));
sort(v1, atoi(argv[1]));
sort(v2, atoi(argv[2]));
writeBinary(v1, "fv1.b", atoi(argv[1]));
writeBinary(v2, "fv2.b", atoi(argv[2]));
writeText(v1,"fv1.txt", atoi(argv[1]));
writeText(v2,"fv2.txt", atoi(argv[2]));
}
void sort(int *vector, int length){
for(int i=0;i<length;i++){
for(int k=i+1; k<length;k++){
if(vector[i]>vector[k]){
int tmp = vector[i];
vector[i] = vector[k];
vector[k] = tmp;
}
}
}
}
void writeText(int *vector,char* filename, int length){
FILE *fpw;
if ((fpw = fopen (filename, "w")) == NULL){
fprintf(stderr," error open %s\n", filename);
exit(1);
}
fwrite(vector, length, sizeof(int), fpw);
fclose(fpw);
}
void writeBinary(int *vector, char* filename, int length ){
FILE *fpw;
if ((fpw = fopen (filename, "wb")) == NULL){
fprintf(stderr," error open %s\n", filename);
exit(1);
}
fwrite(vector, length, sizeof(int), fpw);
fclose(fpw);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct BiNode
{
char data; //定义一个数据
struct BiNode *lchild, *rchild; //定义左孩子和右孩子
} BiTNode, *BiTree; //定义结点和二叉树
void CreateBiTree(BiTree *T) //先序遍历的顺序建立二叉链表
{
char ch; //定义一个字符类型变量
scanf("%c", &ch); //输入字符变量
if (ch == '#') //如果输入的字符为"#",就代表空
{
(*T) = NULL;
}
else
{
(*T) = (BiTree)malloc(sizeof(BiTNode)); //定义二叉树指针为*T名字为BiTNode类型char*
(*T)->data = ch; //导入根的值
CreateBiTree(&(*T)->lchild); //导入左子树的值
CreateBiTree(&(*T)->rchild); //导入右子树的值
}
}
void PreTraverse(BiTree T) //先序遍历二叉树的递归算法
{
if (T)
{
printf("%c", T->data); //遍历根
PreTraverse(T->lchild); //遍历左孩子
PreTraverse(T->rchild); //遍历右孩子
}
}
void InOrderTraverse(BiTree T) //中序遍历二叉树的递归算法
{
if (T)
{
InOrderTraverse(T->lchild); //遍历左孩子
printf("%c", T->data); //遍历根
InOrderTraverse(T->rchild); //遍历右孩子
}
}
void PostTraverse(BiTree T) //后序遍历二叉树的递归算法
{
if (T)
{
PostTraverse(T->lchild); //遍历左孩子
PostTraverse(T->rchild); //遍历右孩子
printf("%c", T->data); //遍历根
}
}
//void PreTree(BiTree T,int j)
//{
// if(T)
// {
// printf("%c",T->data);
// for(int i=1;i<=j;i++)
// printf("#");
// printf("\n");
// j--;
// PreTree(T->lchild,j);
// PreTree(T->rchild,j);
// }
//}
int Depth(BiTree T) //求深度
{
int m, n; //定义m,n
if (T == NULL) //如果结点为空,返回
return 0;
else
{
m = Depth(T->lchild); //m代表左孩子的深度
n = Depth(T->rchild); //n代表右孩子的深度
if (m > n) //比较左右孩子深度的大小
return (m + 1); //最终结果取得子树的深度加根,就等于总深度
else
return (n + 1);
}
}
int NodeCount(BiTree T) //求树的结点个数(递归)
{
if (T == NULL) //如果树为空,结束
return 0;
else
return NodeCount(T->lchild) + NodeCount(T->rchild) + 1; //否则,左孩子的总数加右孩子的总数加根
}
void CountLeaf(BiTree T, int *count) //叶子结点个数(度为0)
{
if (T)
{
if ((!T->lchild) && (!T->rchild)) //左子树为空,右子树为空,证明它是叶子
(*count)++; //叶子节点数+1
CountLeaf(T->lchild, count); //如果有左孩子或者右孩子就继续递归
CountLeaf(T->rchild, count);
}
}
//float PostEval(BiTree T)
//{
// float lv,rv,value=0;
// if(T!=NULL)
// {
// if((!T->lchild)&&(!T->rchild))
// return (T->data)-'0';
// else
// {
// lv=PostEval(T->lchild);
// rv=PostEval(T->rchild);
// switch (T->data)
// {
// case '+':value=lv+rv;break;
// case '-':value=lv-rv;break;
// case '*':value=lv*rv;break;
// case '/':value=lv/rv;break;
// }
// return value;
// }
// }
// return 0;
//}
int main()
{
BiTree tree = NULL;
int count, j;
printf("二叉树的遍历及其应用\n");
printf("1.先序建立二叉链表\n");
printf("2.打印中序遍历结果\n");
printf("3.打印先序遍历结果\n");
printf("4.打印后序遍历结果\n");
printf("5.求二叉树的深度\n");
printf("6.求二叉树的结点个数\n");
printf("7.求二叉树的叶子结点个数\n");
// printf("8.求表达式二叉树的值\n");
// printf("9.在屏幕打印二叉树\n");
printf("0.退出\n\n");
int choose = -1;
while (choose != 0)
{
printf("请选择:");
scanf("%d", &choose); //因为scanf这里是整型,所以这里只能识别整型,假如这里输入1'\n',代表的是键盘输入1和回车,但是在输入流里scanf只能接收到1,输入流缓冲区里还有\n。
getchar(); //getchar()在这里使用的是为了将输入流缓冲区里的字符型'\n'取走
switch (choose)
{
case 1:
printf("请输入建立二叉链表的序列:\n");
CreateBiTree(&tree);
printf("\n");
break;
case 2:
printf("先序遍历的结果为:\n");
PreTraverse(tree);
printf("\n\n");
break;
case 3:
printf("中序遍历的结果为:\n");
InOrderTraverse(tree);
printf("\n\n");
break;
case 4:
printf("后序遍历的结果为:\n");
PostTraverse(tree);
printf("\n\n");
break;
case 5:
printf("树的深度为:%d\n\n", Depth(tree));
break;
case 6:
printf("树的结点个数为:%d\n\n", NodeCount(tree));
break;
case 7:
count = 0;
CountLeaf(tree, &count);
printf("叶子结点的个数为:%d\n\n", count);
break;
// case 8:
// printf("表达式二叉树的值是:%f\n\n", PostEval(tree));
// break;
// case 9:
// j = 10;
// printf("二叉树的示意图为:\n");
// PreTree(tree, j);
// printf("\n");
// break;
default:
if (choose != 0)
printf("请输入正确的操作数字\n\n");
}
}
}
|
C
|
// calibr8.c
// Routines for setting MaxDelay and MinDelay based on how fast the computer
// is that's running the program.
// Barbara Carter 1994
#include <stdio.h>
#include "calibr8.h"
#include "prefs.h"
void Calibrate( void )
{
int result=0;
FILE *fileptr;
clrscr();
FrameScreen();
gotoxy(30,8); printf("Initializing...");
result = DoQuickTest();
if (result)
{
fileptr = fopen("DUNHAM.DAT","r");
if (fileptr)
fclose(fileptr);
else
SavePrefsFile();
return;
}
SetOptimumDelay( &MaxDelay, 300 );
SetOptimumDelay( &MinDelay, 5000 );
SavePrefsFile();
}
int DoQuickTest( void )
{
int result=1;
long int number;
number = TimeSlew( MaxDelay, 150 );
if (number>11 || number<7) result=0;
number = TimeSlew( MinDelay, 2500 );
if (number>11 || number<7) result=0;
return( result );
}
void SetOptimumDelay( int *delayLoops, int numLoops )
{
int number=1, loop=0;
while ((number<=0 || number>=36) && loop<100)
{
number = TimeSlew( *delayLoops, numLoops );
loop++;
}
while (number>19 && *delayLoops>1)
{
if (*delayLoops>6) *delayLoops-=5;
else *delayLoops--;
loop=0;
do
{
number = TimeSlew( *delayLoops, numLoops );
loop++;
} while ((number<=0 || number>=36) && loop<100);
}
while (number<17)
{
*delayLoops++;
loop = 0;
do
{
number = TimeSlew( *delayLoops, numLoops );
loop++;
} while ((number<=0 || number>=36) && loop<100);
}
}
long int TimeSlew( int delayLoops, int numLoops )
{
long int ggX=0L, ggY=0L, widen;
int flag;
dX = delayLoops;
dY = delayLoops/2;
while (flag)
{
Xout=0; Yout=0;
if (dX)
{
if ((--x_skip) == 0)
{
X = x_sign;
if (X<0) Xout = XMINUS;
else Xout = X*XPLUS;
dX -= X;
if ((--xsend[i]) == 0)
++i;
x_skip = xskip[i];
}
else X = 0;
}
else X = 0;
if (dY)
{
if ((--y_skip) == 0)
{
Y = y_sign;
if (Y<0) Yout = YMINUS;
else Yout = Y*YPLUS;
dY -= Y;
if ((--ysend[j]) == 0)
++j;
y_skip = yskip[j];
}
else Y = 0;
}
else Y = 0;
outword = NOPULSE - Xout - Yout;
outp( PULSEPORT, outword );
ggX += X;
ggY += Y;
if (WidenPulse)
{
for (widen=0L;widen<WideEnough;widen++) ;
}
if (screen && ShowXY)
{
if (Xout)
{
if (++xloop>2)
{
xloop=0;
gotoxy(38,y_display);
printf("%+9ld ", gX);
if (!dX) printf(" ");
}
}
if (Yout)
{
if (++yloop>2)
{
yloop=0;
gotoxy(38,y_display+1);
printf("%+9ld ", gY);
if (!dY) printf(" ");
}
}
} // if (screen && ShowXY)
if (!(dX || dY)) flag=0; // dX=0 and dY=0 => done slewing
if (abort_slew_flag)
{
quit = 1;
if (i<=x_cruise_index)
{
if (i==x_cruise_index)
dX = x_sign * cumulative[i++];
else
{ dX = x_sign * cumulative[i]; i = 2*x_cruise_index - i; }
}
if (j<=y_cruise_index)
{
if (j==y_cruise_index)
dY = y_sign * cumulative[j++];
else
{ dY = y_sign * cumulative[j]; j = 2*y_cruise_index - j; }
}
abort_slew_flag = 0;
if (ShowXY)
{
gotoxy(46,y_display);
if (dX) printf(" (ramping down)");
else printf(" ");
gotoxy(46,y_display+1);
if (dY) printf(" (ramping down)");
else printf(" ");
}
}
outp( PULSEPORT, NOPULSE );
} // while (flag)
}
|
C
|
/*
(This problem is an interactive problem.)
A row-sorted binary matrix means that all elements are 0 or 1 and each row of the matrix is sorted in non-decreasing order.
Given a row-sorted binary matrix binaryMatrix, return the index (0-indexed) of the leftmost column with a 1 in it.
If such an index does not exist, return -1.
You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface:
BinaryMatrix.get(row, col) returns the element of the matrix at index (row, col) (0-indexed).
BinaryMatrix.dimensions() returns the dimensions of the matrix as a list of 2 elements [rows, cols], which means the matrix is rows x cols.
Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer.
Also, any solutions that attempt to circumvent the judge will result in disqualification.
For custom testing purposes, the input will be the entire binary matrix mat. You will not have access to the binary matrix directly.
Example 1:
Input: mat = [[0,0],[1,1]]
Output: 0
Example 2:
Input: mat = [[0,0],[0,1]]
Output: 1
Example 3:
Input: mat = [[0,0],[0,0]]
Output: -1
Example 4:
Input: mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]]
Output: 1
Constraints:
rows == mat.length
cols == mat[i].length
1 <= rows, cols <= 100
mat[i][j] is either 0 or 1.
mat[i] is sorted in non-decreasing order.
*/
#include "../standardHeaders.h"
/**
* // This is the BinaryMatrix's API interface.
* // You should not implement it, or speculate about its implementation
* struct BinaryMatrix {
* int (*get)(struct BinaryMatrix*, int, int);
* int* (*dimensions)(struct BinaryMatrix*);
* };
*/
int leftMostColumnWithOne(struct BinaryMatrix* matrix) {
int rows = matrix->dimensions(matrix)[0];
int cols = matrix->dimensions(matrix)[1];
int currRow = 0;
int currCol = cols-1;
while((currRow < rows) && (currCol >= 0)) {
if(matrix->get(matrix, currRow, currCol) == 0) {
currRow++;
}
else {
currCol--;
}
}
return (currCol == cols-1) ? -1 : currCol+1;
}
|
C
|
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <conio.h>
#include <windows.h>
void gotoxy(int x, int y) //λyеĵx
{
int xx=0x0b;
HANDLE hOutput;
COORD loc;
loc.X = x;
loc.Y=y;
hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hOutput, loc);
return;
}
int main()
{
srand(time(0));
int i,j,z,l=0,k=0,m,n=8;
char p[]="";
char sh,a[15][41]={0};
for(i=0;i<15;i++)for(j=0;j<40;j+=2)
{a[i][j]=32;a[i][j+1]=32;}
for(i=0;i<40;i+=2)
{a[0][i]=-95;a[0][i+1]=-10;
a[14][i]=-95;a[14][i+1]=-10;}
for(i=0;i<15;i++)
puts(a[i]);
gotoxy(50,5);
printf("ŭС");
gotoxy(50,7);
printf("w");
while(1)
{
Sleep(200);
m++;
m=m%3;
if(!m)
{
for(i=0;i<14;i++)
for(j=0;j<38;j+=2)
{a[i][j]=a[i][j+2];
a[i][j+1]=a[i][j+3];}
k++;
k=k%4;
if(!k)
{
z=rand()%11+1;
for(i=0;i<15;i++)
{
if(z!=i&&i!=z+1&&i!=z+2){a[i][38]=-95;a[i][39]=-10;}
else{a[i][38]=32;a[i][39]=32;}
}
}
else
{
a[0][38]=-95;a[0][39]=-10;a[14][38]=-95;a[14][39]=-10;
for(i=1;i<14;i++)
{a[i][38]=32;a[i][39]=32;}
}
gotoxy(0,0);
for(i=0;i<15;i++)
puts(a[i]);
}
if(kbhit())
{
sh=getch();
l=0;
}
gotoxy(6,n);
puts(" ");
l++;
l=l%3;
if(l==0)sh='s';
switch (sh)
{
case 'w': case 'W': n--;break;
case 's': case 'S': n++;break;
default :;
}
gotoxy(6,n);
if(a[n][6]==-95)break;
puts(p);
}
while(1){printf("GAME OVER");Sleep(100000);}
}
|
C
|
#pragma once
struct Point {
int x;
int y;
int id;//vectorrank
Point() { x = y = 0; id = -1; }
bool operator ==(Point p) { return x == p.x && y == p.y; }
};
long long int Area2(Point p, Point q, Point s) {
return
(long long int)p.x * (long long int)q.y - (long long int)p.y * (long long int)q.x
+ (long long int)q.x * (long long int)s.y - (long long int)q.y * (long long int)s.x
+ (long long int)s.x * (long long int)p.y - (long long int)s.y * (long long int)p.x;
}
//qǷps֮
bool between(Point p, Point q, Point s) {
return
(long long int)(p.x - q.x) * (long long int)(q.x - s.x) +
(long long int)(p.y - q.y) * (long long int)(q.y - s.y) > 0;
}
//spqߣpq֮ʱ, ToLeftжȻΪtrue
//ڴsupportʱĹʹ÷صΪйߵѯĵ
bool ToLeft(Point p, Point q, Point s) {
if (Area2(p, q, s) > 0)return true;
if (Area2(p, q, s) < 0)return false;
return between(p, q, s);
}
bool ToRight(Point p, Point q, Point s) {
if (Area2(p, q, s) > 0)return false;
if (Area2(p, q, s) < 0)return true;
return between(p, q, s);
}
//Triangle ABC in CCW order. Colinear cases are in account
bool InTriangleTest(Point a, Point b, Point c, Point p) {
//ѯ˵غϵʱ
if ((p == c) || (p == a) || (p == b))return false;
else {
return !(ToRight(a, b, p) || ToRight(b, c, p) || ToRight(c, a, p));
}
}
//߶qΪѯ߶Σchainе߶pѰǷཻ
bool IntersectionTest(Point p1, Point p2, Point q1, Point q2) {
int k = (q2.y - q1.y) * (p2.x - p1.x) - (q2.x - q1.x) * (p2.y - p1.y);
int p = (q2.x - q1.x) * (p1.y - q1.y) - (q2.y - q1.y) * (p1.x - q1.x);
int q = (p2.x - p1.x) * (p1.y - q1.y) - (p2.y - p1.y) * (p1.x - q1.x);
if (k == 0) {
//Colinear Case
if (p == 0 && q == 0) {
//Check Range
if ((between(p1, q1, p2) || between(p1, q2, p2)) || between(q1, p1, q2) || between(q1, p2, q2)) {
return true;
}
else return false;
}
//Parallel Case
else {
return false;
}
}
double kp = (double)p / (double)k;
double kq = (double)q / (double)k;
//p˵㣬q˵
if ((kp <= 1 && kp >= 0) && (kq < 1 && kq>0)) {
return true;
}
else return false;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HASHSIZE 128 // 128 ascii characters
static int uniqueCharacterCount;
static int binaryTableCount;
static struct dictionary* hashtable[HASHSIZE];
int readFile(char*);
int addToHashTable(int);
struct dictionary* lookup(int);
unsigned char* lookupNodeCode(int);
unsigned hash(int);
int matchBinaryString(char*, int);
static struct simpleNode* binaryTableIn[HASHSIZE];
static struct node* binaryTableOut[HASHSIZE];
char* checkFileExtension(char*);
struct dictionary // used by hash table to count character frequencies
{
int character;
int count;
struct dictionary *next;
};
struct node
{
int character;
int frequency;
struct node* leftChild;
struct node* rightChild;
unsigned char* binary;
};
typedef struct priorityQueue{
struct node* heap;
int size;
} priorityQueue;
struct simpleNode // used to fill out binaryTableIn[] when extracting .huff file
{
int character;
unsigned char* binary;
};
// =============== Priority Queue Functions ===================
void insert(struct node aNode, struct node* heap, int size) {
int index = size;
struct node tmp;
heap[index] = aNode;
while (heap[index].frequency < heap[(index-1)/2].frequency && index >= 1) {
tmp = heap[index];
heap[index] = heap[(index-1)/2];
heap[(index-1)/2] = tmp;
index /= 2;
}
}
void shiftDown(struct node* heap, int size, int idx) {
int childID = (idx+1)*2-1; // set to left child index
struct node tmp;
for (;;) {
if (childID > size) {
break; // has no child
}
//if rightChild is smaller than leftChild
if (heap[childID].frequency > heap[childID+1].frequency && childID+1 <= size) {
++childID; // leftChild becomes rightChild
}
if (heap[childID].frequency < heap[idx].frequency) {
tmp = heap[childID];
heap[childID] = heap[idx];
heap[idx] = tmp;
idx = childID;
} else {
break;
}
}
}
void enqueue(struct node node, priorityQueue *q) {
insert(node, q->heap, q->size);
++q->size;
}
struct node removeMin(struct node* heap, int size) {
struct node toRemove = heap[0];
heap[0] = heap[size-1];
--size;
shiftDown(heap, size, 0);
return toRemove;
}
struct node dequeue(priorityQueue *q) {
struct node rv = removeMin(q->heap, q->size);
--q->size;
return rv;
}
void initializeQueue(priorityQueue *q, int n) {
q->size = 0;
q->heap = (struct node*)malloc(sizeof(struct node)*(n));
}
// ===========================================
int readFile(char *fileName)
{
int characterCount = 0;
FILE *file_in = fopen(fileName, "rb");
if(!file_in){
fprintf(stderr, "%s does not exist!\n", fileName);
}
int c;
while ((c = fgetc(file_in)) != EOF)
{
if(addToHashTable(c) == 0) characterCount++;
else return -1;
}
fclose(file_in);
return characterCount;
}
int traverseFree(struct node* currentNode) // recursively traverse BST to free nodes
{
if(currentNode->character == '\0')
{
traverseFree(currentNode->leftChild);
traverseFree(currentNode->rightChild);
}
else free(currentNode->binary); // free binary from nodes that have binary data
free(currentNode); // free all nodes
return 0;
}
int traverse(const char* lr, struct node* currentNode, char *b) // recursively traverse BST, assign Huffman codes
{
strcat(b, lr);
if(currentNode->leftChild != NULL)
{
traverse("0", currentNode->leftChild, b);
traverse("1", currentNode->rightChild, b);
}
else
{
currentNode->binary = malloc(sizeof(char*) * strlen(b));
strcpy((char*) currentNode->binary, (const char*) b);
binaryTableOut[binaryTableCount++] = currentNode;
}
if(strlen(b) > 0)
{
b[strlen(b)-1] = '\0';
}
return 0;
}
void huffmanCode(priorityQueue* p)
{
while(p->size > 1) {
struct node *temp = calloc(1, sizeof(struct node));
struct node also = dequeue(p); // dequeue min to left child of temp
temp->leftChild = malloc(sizeof(struct node));
temp->leftChild->leftChild = also.leftChild;
temp->leftChild->rightChild = also.rightChild;
temp->leftChild->frequency = also.frequency;
temp->leftChild->character = also.character;
temp->leftChild->binary = also.binary;
also = dequeue(p); // dequeue min to be right child of temp
temp->rightChild = malloc(sizeof(struct node));
temp->rightChild->leftChild = also.leftChild;
temp->rightChild->rightChild = also.rightChild;
temp->rightChild->character = also.character;
temp->rightChild->frequency = also.frequency;
temp->rightChild->binary = also.binary;
temp->frequency = temp->leftChild->frequency + temp->rightChild->frequency;
temp->character = '\0';
enqueue(*temp, p); // enqueue temp
free(temp);
}
}
int addToHashTable(int character)
{
if(character > 127)
{
return 1; // only want to count them once
}
struct dictionary* temp;
if ((temp = lookup(character)) == NULL) { // not found
unsigned hashval = hash(character);
temp = (struct dictionary *) malloc(sizeof(*temp));
temp->count = 1;
temp->character = character;
temp->next = hashtable[hashval];
hashtable[hashval] = temp;
uniqueCharacterCount++;
}
else
{
temp->count++;
}
return 0;
}
unsigned hash(int s)
{
// form a hash value for string s
unsigned hashval;
hashval = (unsigned) s + 31;
return hashval % HASHSIZE;
}
struct dictionary *lookup(int s)
{
// look for s in hashtab
struct dictionary *np;
for (np = hashtable[hash(s)]; np != NULL; np = np->next)
{
if (s == np->character) return np; // return np if found
}
return np; // return NULL if not found
}
unsigned char* lookupNodeCode(int c)
{
int i;
for(i = 0; i < HASHSIZE; i++)
{
if(binaryTableOut[i]->character == c)
{
return binaryTableOut[i]->binary;
}
}
return NULL;
}
char* checkFileExtension(char* fileNameToCheck)
{
int length = (int) strlen(fileNameToCheck);
char extension[6];
memcpy(extension, &fileNameToCheck[length-5], 5);
extension[5] = '\0';
if(strcmp(extension, ".huff") != 0)
{
return NULL;
}
else
{
char* fileNameNoExtension = calloc(1, sizeof(char) * (length));
memcpy(fileNameNoExtension, &fileNameToCheck[0], ((size_t) length - 5));
return fileNameNoExtension;
}
}
int matchBinaryString(char* stringToMatch, int count)
{
int i;
for(i = 0; i < count; i++)
{
if(strcmp((const char*) binaryTableIn[i]->binary, stringToMatch) == 0)
{
return binaryTableIn[i]->character;
}
}
return -1;
}
void writeOutputFile(char* fileIn, char* fileOut, int totalCharacters)
{
FILE* file_in = fopen(fileIn, "rb");
if(!file_in){
fprintf(stderr, "%s does not exist!\n", fileIn);
exit(1);
}
int size;
fseek(file_in, 0, SEEK_END);
size = (int) ftell(file_in); // get file size
fseek(file_in, 0, SEEK_SET);
if(size == 0){
fprintf(stderr, "You are literally trying to compress a file with zero bytes.\n");
exit(1);
}
unsigned char* fileInBuffer;
fileInBuffer = malloc(sizeof(fileInBuffer) * size);
fread(fileInBuffer, sizeof(fileInBuffer), (size_t) size , file_in); // read bytes into buffer
fclose(file_in);
FILE* writeBinary = fopen(fileOut, "wb");
if(!writeBinary)
{
fprintf(stderr, "Can't create file\n");
exit(1);
}
int i;
for(i = 0; i < uniqueCharacterCount; i++) // write character/Huffman-code data to the .huf file
{
fwrite((char*) &binaryTableOut[i]->character, 1, 1, writeBinary);
fwrite(binaryTableOut[i]->binary, strlen((const char*)binaryTableOut[i]->binary), 1, writeBinary);
fwrite("\0",1,1,writeBinary);
}
fwrite("\x07", 1,1,writeBinary); // marks the end of character/Huffman-code data
fwrite(&uniqueCharacterCount, sizeof(int), 1, writeBinary);
fwrite(&totalCharacters, sizeof(int), 1, writeBinary);
int c, k, byte, byteLen;
byte = 0, byteLen = 0;
for(i = 0; i < size; i++) // loop through characters from fileIn
{
c = fileInBuffer[i];
unsigned char *stringBinary = lookupNodeCode(c); // get binary string for given character
int length = (int) strlen((const char *) stringBinary);
for (k = 0; k < length; k++) // loop through all chars of given binary string
{ // create bit representation. When a byte is made, write it to file & repeat
if (byteLen == 8) {
fputc(byte, writeBinary);
byteLen = 0;
byte = 0;
}
char temp = stringBinary[k];
if (temp - '0' == 0) {
byte <<= 1;
byteLen++;
} else if (temp - '0' == 1) {
byte <<= 1;
byte++;
byteLen++;
}
}
}
for(i = byteLen; i < 8; i++) // append 0s to leftover bits to make one last byte
{
byte <<= 1;
}
fputc(byte, writeBinary);
free(fileInBuffer);
fclose(writeBinary);
}
void readOutputFile(char* fileNameToRead, char* fileNameOutput)
{
size_t size;
unsigned char* buffer;
FILE* fileToRead;
fileToRead = fopen(fileNameToRead, "rb");
fseek(fileToRead, 0, SEEK_END);
size = (size_t) ftell(fileToRead);
fseek(fileToRead, 0, SEEK_SET);
buffer = (unsigned char*) malloc(sizeof(*buffer) * size);
int uniqueCharacterCount = 0;
int totalCharacterCount = 0;
int charactersCounted = 0;
if (fileToRead == NULL)
{
fprintf(stderr, "Error: There was an error reading the file\n");
exit(1);
}
fread(buffer, sizeof(*buffer), size , fileToRead);
fclose(fileToRead);
int i;
char* currentString = (char*) calloc(1, sizeof(char*) * 128);
int charTemp;
int binaryTemp;
int reachedBinary = 0; // false when huffman table data still needs to be read.
FILE* outputFile;
outputFile = fopen(fileNameOutput, "wb");
struct simpleNode *tempSimpleNode;
tempSimpleNode = (struct simpleNode *) calloc(1, sizeof(struct simpleNode));
char* tempBinaryString = calloc(1, HASHSIZE);
char tempBuffer[4];
int tableIndex = 0;
for(i = 0; i < size; i++){
if (reachedBinary == 0)
{
tempSimpleNode->character = buffer[i];
while(buffer[++i] != 0){
char z = (char) buffer[i];
char* c = calloc(1, 2* sizeof(char));
c[0] = z;
c[1] = '\0';
strcat(tempBinaryString, (const char*) c);
free(c);
}
tempSimpleNode->binary = malloc(sizeof(unsigned char*) * strlen(tempBinaryString));
strcpy((char*) tempSimpleNode->binary, (const char*) tempBinaryString);
strcpy(tempBinaryString, "");
binaryTableIn[tableIndex++] = tempSimpleNode;
tempSimpleNode = (struct simpleNode *) calloc(1, sizeof(struct simpleNode));
charTemp = buffer[i + 1];
if (charTemp == 7) {
reachedBinary = 1;
i+=2;
uniqueCharacterCount = *((int *) &buffer[i]);
i+=4;
totalCharacterCount = *((int *) &buffer[i]);
i+=3;
}
}
else{ // binary parsing
int j;
for( j = 7; j >= 0; j--)
{
sprintf(tempBuffer, "%d", (buffer[i] >> j) & 1);
strcat(currentString, tempBuffer);
binaryTemp = matchBinaryString(currentString, uniqueCharacterCount);
if (binaryTemp != -1) {
fputc(binaryTemp, outputFile);
strcpy(currentString, "");
strcpy(tempBuffer, "");
charactersCounted++;
if(charactersCounted >= totalCharacterCount)
{
break;
}
}
}
}
}
i=0;
while(binaryTableIn[i] != NULL)
{
free(binaryTableIn[i]->binary);
free(binaryTableIn[i]);
i++;
}
free(tempSimpleNode->binary);
free(tempSimpleNode);
free(tempBinaryString);
free(currentString);
fclose(outputFile);
free(buffer);
printf("Extracting complete.\n");
}
// ===========================================
int main(int argc, char** argv) {
if(argc > 2) {
char* fileName = argv[2];
if(argv[1][0] == 'c') {
char* binaryString = calloc(1, sizeof(char) * HASHSIZE);
uniqueCharacterCount = 0;
binaryTableCount = 0;
// need to accept various files as input
int totalNumberOfCharacters = readFile(fileName); // read file, create frequency table of characters
if(totalNumberOfCharacters == -1)
{
fprintf(stderr, "Only 7-bit ascii characters are allowed.\n");
exit(1);
}
priorityQueue pq;
initializeQueue(&pq, uniqueCharacterCount);
int i, j;
j = 0;
for (i = 0; i < HASHSIZE; i++) {
if (hashtable[i] != NULL) {
struct node *temp1;
temp1 = (struct node *) malloc(sizeof(*temp1));
temp1->character = hashtable[i]->character;
temp1->frequency = hashtable[i]->count;
temp1->leftChild = NULL;
temp1->rightChild = NULL;
enqueue(*temp1, &pq);
j++;
free(temp1);
free(hashtable[i]);
}
}
huffmanCode(&pq);
if(uniqueCharacterCount == 1) {
pq.heap->binary = malloc(sizeof(char*));
strcpy((char*) pq.heap->binary, (const char*) "0");
binaryTableOut[binaryTableCount++] = pq.heap;
}
else traverse("", pq.heap, binaryString);
int fileNameLength = (int) strlen(fileName);
char* fileOut = malloc(sizeof(char) * (fileNameLength + 6));
strcpy(fileOut, fileName);
strcat(fileOut, ".huff");
printf("Writing %s\n", fileOut);
writeOutputFile(fileName, fileOut, totalNumberOfCharacters);
printf("Writing complete\n");
free(fileOut);
free(binaryString);
traverseFree(&pq.heap[0]);
}
else if(argv[1][0] == 'e'){
char* fileNameOutput = checkFileExtension(argv[2]);
if (fileNameOutput == NULL)
{
fprintf(stderr, "File must be '.huff' to extract.\n");
}
else{
printf("Extracting\n");
readOutputFile(fileName, fileNameOutput);
}
free(fileNameOutput);
}
}
else fprintf(stderr, "type: \n'./huffman c fileNameToCompress.txt'\nor:\n'./huffman e fileNameToExtract.huff\n");
return 0;
} // end main()
|
C
|
#include "full_connection.h"
int transfer_all(int socket, char *buffer, int length, char direction) {
int total, bytes_left, n;
total = 0;
bytes_left = length;
while (total < length) {
if (direction == 's'){//printf("sent: %s\n", buffer);
n = send(socket, buffer + total, bytes_left, 0);//printf("send unblocks on socket\n");
} else{//printf("recv blocks on socket: %d\n", socket);
n = recv(socket, buffer + total, bytes_left, 0);//printf("received: %s\n", buffer);
}
if (n < 1 && length != 0) {
return -1;
}
total += n;
bytes_left -= n;
}
return bytes_left; //should be 0 if all sent/received successfully
}
|
C
|
//
// main.c
// practice
//
// Created by 张雪遥 on 01/01/2018.
// Copyright © 2018 张雪遥. All rights reserved.
//
#include <stdio.h>
#define ARRAY_SIZE 10
void natural_numbers (void) {
int i;
int array[ARRAY_SIZE];
i = 1;
while ( i <= ARRAY_SIZE) {
array[i] = i -1;
printf("array[%d] = %d\n",i,i-1);
i = i +1;
}
// i = 0;
// while ( i < ARRAY_SIZE + 2) {
// array[i] = i - 1;
// printf("array[%d] = %d\n", i, i - 1);
// i = i + 1;
// }
}
int main(int argc, char **argv)
{
natural_numbers();
return 0;
}
|
C
|
#ifndef __SCHEDULER_H__
#define __SCHEDULER_H__
#include <time.h> /* struct tm */
#include <stddef.h> /* size_t */
#include "uid.h"
typedef struct scheduler scheduler_t;
scheduler_t *SchedulerCreate (void); /* time complexity: O(1) */
void SchedulerDestroy (scheduler_t *scheduler); /* time complexity: O(n) */
ilrd_uid_t SchedulerAdd (scheduler_t *scheduler,
int (*action_func)(void *param),
size_t interval_in_sec, void *param);/*
0 - seccses and stop func need to be
1 - error at action_func
2- repited func
action can be either periodical and run each x seconds, or a single instance to be executed
in x seconds.
time complexity: O(n) */
int SchedulerRemove (scheduler_t *scheduler,
ilrd_uid_t uid); /* time complexity: O(n) */
size_t SchedulerSize (const scheduler_t *scheduler); /* time complexity: O(n) */
int SchedulerIsEmpty (const scheduler_t *scheduler); /* time complexity: O(1) */
int SchedulerRun (scheduler_t *scheduler); /* time complexity: O(1) */
void SchedulerStop (scheduler_t *scheduler); /* stops the scheduler, should be
* entered as a task to be scheduled in
* interval seconds
* time complexity: O(1)
*/
void SchedulerClear (scheduler_t *scheduler); /* time complexity: O(n) */
#endif /* __SCHEDULER_H__ */
|
C
|
static int Succ(int Value, Queue Q)
{
if (++Value == Q -> Capacity)
Value = 0;
return Value;
}
void Enqueue(ElementType X, Queue Q)
{
if (IsFull(Q))
Error("Full queue");
else
{
Q -> Size++;
Q -> Rear = Succ(Q -> Rear, Q);
Q -> Array[Q -> Rear] = X;
}
}
|
C
|
#include<stdio.h>
int main()
{
char x;
printf("welcome!!!!");
printf("enter first char of your name");
scanf("%c",&x);
switch(x)
{
case 97:
printf("anka\n");
break;
case 'k':
printf("kalpna\n");
break;
case 'h':
printf("himanshu\n");
break;
case 'r':
printf("ragini\n");
break;
case 'm':
printf("mandheer\n");
break;
case 's':
printf("simple\n");
break;
default:
printf("invalid input");
break;
}
return 0;
}
|
C
|
/******************************************************************************
@Bhavanishankar
Multiplication table
*******************************************************************************/
#include <stdio.h>
int main()
{
int num,i;
printf("########## Multiplication table ##########\n ");
printf("Enter the number \n");
scanf("%d", &num);
printf("###################\n");
for(i=1;i<=20;i++)
printf("%d*%d=%d\n", num,i, num*i);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: anachid <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/16 05:06:06 by anachid #+# #+# */
/* Updated: 2020/08/19 20:05:47 by anachid ### ########.fr */
/* */
/* ************************************************************************** */
long int ft_strlen(char *str)
{
long int i;
i = 0;
while (str[i] != '\0')
i++;
return (i);
}
int ft_check(char *base)
{
int i;
int j;
i = 0;
if (ft_strlen(base) <= 1)
return (0);
while (base[i])
{
if (base[i] < 32 || base[i] > 126 || base[i] == ' ' || base[i] == '\t'
|| base[i] == '\n' || base[i] == '\v' || base[i] == '\f'
|| base[i] == '\r' || base[i] == '-' || base[i] == '+')
return (0);
j = 0;
while (base[j])
{
if (base[i] == base[j] && i != j)
return (0);
j++;
}
i++;
}
return (1);
}
int in_base(char c, char *base)
{
int i;
i = 0;
while (i < ft_strlen(base))
{
if (c == base[i])
return (1);
i++;
}
return (0);
}
int pos(char c, char *base)
{
int i;
i = 0;
while (c != base[i])
i++;
return (i);
}
int ft_atoi_base(char *str, char *base)
{
int long i;
int long res;
int sign;
i = 0;
res = 0;
sign = 1;
if (ft_check(base))
{
while (str[i] && ((str[i] >= 9 && str[i] <= 13) || str[i] == ' '))
i++;
while (str[i] && (str[i] == '-' || str[i] == '+'))
{
if (str[i] == '-')
sign *= -1;
i++;
}
while (str[i] && in_base(str[i], base))
res = res * ft_strlen(base) + pos(str[i++], base);
return (sign * res);
}
return (0);
}
|
C
|
/*
* terminal.h
*
* Created on: Mar 14, 2021
* Author: Mohamed Amin Rezgui
*/
#ifndef TERMINAL_H_
#define TERMINAL_H_
#include <stdio.h>
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#ifdef __GNUC__
/* With GCC, small printf (option LD Linker->Libraries->Small printf
set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/* USER CODE END PTD */
#endif /* TERMINAL_H_ */
|
C
|
// Private
Servo _servo;
int _hal_servo_full_position = 0;
bool _hal_servo_full_direction = SCAN_FULL_STARTING_DIRECTION; // true = right, false = left
int _hal_servo_forward_position = 0;
bool _hal_servo_forward_direction = SCAN_FORWARD_STARTING_DIRECTION; // true = right, false = left
int _hal_servo_left_position = 0;
bool _hal_servo_left_direction = SCAN_LEFT_STARTING_DIRECTION; // true = right, false = left
int _hal_servo_right_position = 0;
bool _hal_servo_right_direction = SCAN_RIGHT_STARTING_DIRECTION; // true = right, false = left
bool _hal_servo_is_scanning_full = false;
void _hal_servo_rotate(int position) {
_servo.write(position);
}
void _hal_servo_scan_full_step() {
int val = (SONAR_MIN + _hal_servo_full_position * SONAR_STEP);
_hal_servo_rotate(val);
_hal_servo_full_position += _hal_servo_full_direction ? 1 : (-1);
if (_hal_servo_full_position >= SONAR_STEPS) {
_hal_servo_full_direction = false;
}
else if (_hal_servo_full_position <= 0) {
_hal_servo_full_direction = true;
}
}
void _hal_servo_scan_full_reset() {
_hal_servo_full_position = ROTATION_FORWARD;
_hal_servo_rotate(_hal_servo_full_position);
_hal_servo_full_direction = SCAN_FULL_STARTING_DIRECTION;
}
void _hal_servo_scan_forward() {
}
void _hal_servo_scan_forward_reset() {
_hal_servo_forward_position = ROTATION_FORWARD;
_hal_servo_rotate(_hal_servo_forward_position);
_hal_servo_forward_direction = SCAN_FORWARD_STARTING_DIRECTION;
}
void _hal_servo_scan_left() {
}
void _hal_servo_scan_left_reset() {
_hal_servo_left_position = ROTATION_LEFT;
_hal_servo_rotate(_hal_servo_left_position);
_hal_servo_left_direction = SCAN_LEFT_STARTING_DIRECTION;
}
void _hal_servo_scan_right() {
}
void _hal_servo_scan_right_reset() {
_hal_servo_right_position = ROTATION_RIGHT;
_hal_servo_rotate(_hal_servo_right_position);
_hal_servo_right_direction = SCAN_RIGHT_STARTING_DIRECTION;
}
// Public - Scanning
void hal_servo_start_scanning(byte scanning) {
if (scanning == SCANNING_ALL) {
WARNING("Only one scanning can be started at a time!")
}
if (scanning == SCANNING_FULL) {
_hal_servo_is_scanning_full = true;
}
}
void hal_servo_stop_scanning(byte scanning) {
if (scanning == SCANNING_FULL || scanning == SCANNING_ALL) {
_hal_servo_is_scanning_full = false;
}
}
boolean hal_servo_is_scanning(byte scanning) {
if (scanning == SCANNING_ALL) {
WARNING("Only one scanning can be tested for scanning at a time!")
}
if (scanning == SCANNING_FULL) {
return _hal_servo_is_scanning_full;
}
return false;
}
// Public - Rotation
void hal_servo_rotate_forward() {
_hal_servo_rotate(ROTATION_FORWARD);
}
void hal_servo_rotate_left() {
_hal_servo_rotate(ROTATION_LEFT);
}
void hal_servo_rotate_right() {
_hal_servo_rotate(ROTATION_RIGHT);
}
void hal_servo_rotate(int position) {
_hal_servo_rotate(position);
}
// Public - Setup & Loop
void setup_hal_servo() {
_servo.attach(SERVO_PIN);
hal_servo_rotate_forward();
hal_servo_stop_scanning(SCANNING_ALL);
}
void hal_servo_loop() {
if (_hal_servo_is_scanning_full) {
_hal_servo_scan_full_step();
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0, cont = 0, soma = 0 , x = 0;
do{
printf("Digite um numero inteiro: ");
scanf("%d", &x);
if (x % 2 != 0){
x += 1;
}
soma = 5 * x + 20;
}while(x == 0);
printf("SOMA = %d", soma);
return 0;
}
|
C
|
#include <stdio.h>
/**
* main - the way you do 11
*
* Return: Always 0
*/
int main(void)
{
int i;
int m;
for (i = '0'; i <= '8'; i++)
for (m = '1'; m <= '9'; m++)
{
if (i < m)
{
if (i != '0' || m != '1')
{
putchar(',');
putchar(' ');
}
putchar(i);
putchar(m);
}
}
putchar('\n');
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
//barnamei ke moadele nomrehaye 20ta dars ro mohasebe va chap mikonad
int main(int argc, char *argv[])
{
float sum = 0 , ave , temp;
for(int i = 0 ; i < 2 ; i++) {
scanf("%f" , &temp);
sum += temp ;
}
ave = sum / 2 ;
printf("moadel = %.2f \n" , ave ) ;
system("PAUSE");
return 0;
}
|
C
|
// RUN: %sea pf -O0 --inline "%s" 2>&1 | OutputCheck %s
// CHECK: ^unsat$
#include <seahorn/seahorn.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#define FOO_TAG 100
#define BAR_TAG 200
static int8_t *g_bgn;
static int8_t *g_end;
static int g_active;
extern int nd(void);
extern int8_t *nd_ptr(void);
typedef struct Foo {
int tag;
int x;
} Foo;
typedef struct Bar {
struct Foo foo;
int y;
} Bar;
void *xmalloc(size_t sz) {
void *p;
p = malloc(sz);
assume(((ptrdiff_t)p) > 0);
return p;
}
Foo *mk_foo(int x) {
Foo *res = (Foo *)xmalloc(sizeof(struct Foo));
res->tag = FOO_TAG;
res->x = x;
if (!g_active && nd()) {
g_active = !g_active;
assume((int8_t *)res == g_bgn);
assume(g_bgn + sizeof(struct Foo) == g_end);
} else {
assume((int8_t *)res > g_end);
}
return res;
}
Bar *mk_bar(int x, int y) {
Bar *res = (Bar *)xmalloc(sizeof(struct Bar));
res->foo.tag = BAR_TAG;
res->foo.x = x;
res->y = y;
assume((int8_t *)res > g_end);
return res;
}
Foo *to_foo(Bar *b) { return (Foo *)b; }
int is_bar(Foo *b) { return b->tag == BAR_TAG; }
int is_foo(Foo *b) { return b->tag == FOO_TAG; }
Bar *to_bar(Foo *b) { return (Bar *)b; }
typedef struct Entry {
void *data;
struct Entry *next;
} Entry;
typedef struct List {
Entry *head;
} List;
Entry *mk_entry(void *data) {
Entry *res = (Entry *)xmalloc(sizeof(struct Entry));
res->data = data;
res->next = NULL;
assume((int8_t *)res > g_end);
return res;
}
List *mk_list() {
List *res = (List *)xmalloc(sizeof(struct List));
res->head = NULL;
assume((int8_t *)res > g_end);
return res;
}
void insert(List *lst, void *data) {
Entry *en = mk_entry(data);
en->next = lst->head;
lst->head = en;
}
int main(void) {
List *lst;
Entry *it;
g_bgn = nd_ptr();
g_end = nd_ptr();
assume(g_bgn > 0);
assume(g_end > g_bgn);
g_active = 0;
lst = mk_list();
insert(lst, mk_foo(2));
insert(lst, mk_bar(3, 4));
insert(lst, mk_foo(5));
unsigned cnt;
cnt = 0;
for (it = lst->head; it != NULL; it = it->next) {
Foo *v = (Foo *)(it->data);
if (is_bar(v)) {
Bar *b;
if (g_active) {
sassert((int8_t *)v != g_bgn);
}
b = to_bar(v);
printf("bar: x=%d, y=%d\n", v->x, b->y);
} else {
printf("foo: x=%d\n", v->x);
}
cnt++;
if (cnt > 3)
break;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
/*CONSTANTES*/
/*
* LARGO: el cliente tiene el pelo largo
* CORTO: el cliente tiene el pelo corto
* SILLAS: número de sillas en la barbería
*/
#define LARGO 'l'
#define CORTO 'c'
#define SILLAS 4
/*COLORES CONSTANTES*/
#define RESET "\x1b[0m"
#define CYAN "\x1b[36m"
#define VERDE "\x1b[32m"
/*VARIABLES GLOBALES*/
/*
* *pelo: array que almacenará el estado de la cabellera de los clientes
* isAtendidos: variable que determinará si todos los clientes han sido atendidos
* sillasLibres: número de sillas disponibles en un momento
* numClient: almacena el número de clientes que recibira la peluquería
*/
char *pelo;
int isAtendidos;
int sillasLibres = SILLAS;
int numClient = 0;
/*SEMAPHORE*/
/*
* *barberoDesp: determina si el barbero se encuentra disponible
* *clientes: estará activo mientras haya clientes en la barbería
* *accesos: controla el acceso a la región crítica (0 y 1, mutex)
* */
sem_t *barberoDesp, *clientes, *accesos;
/*HEADERS*/
//Funciones de comportamiento de los semáforos
/*
* Función que creará los diferentes semáforos para la ejecución
* del programa.
*/
void initSem();
/*
* Función encargada del cierre y destrucción de los semáforos.
*/
void destroySem();
/*
* Función encargada de la inicialización del array pelo.
*
* int numClientes: número de clientes que recibirá la
* barbería.
*/
void initHair(int numClientes);
/*Función asociada al hilo del barbero*/
void *barbero(void *args);
//Funciones para los clientes
/*
* Función que dormirá al cliente entre 1 y 30 segundos en caso
* de no poder sentarse en la barbería
*
* int clien: cliente que no puede sentarse en las sillas.
*/
void pasear(int clien);
/*
* Función que proporcionará un cambio en el array pelo, pasará
* de LARGO a CORTO.
*
* int clien: cliente al que se le corta el pelo
*/
void cortar(int clien);
/*Función que determina el comportamiento del cliente*/
void *cliente(void *args);
int main(int argc, char **argv) {
if(argc == 2){ //El programa debe leer 2 parámetros por línea de comandos
//Determinación de número de clientes de la barbería
sscanf(argv[1],"%d",&numClient);
//Hilo para el barbero y array para los clientes. Se utiliza un array
//para almacenar el número del cliente.
pthread_t barber;
pthread_t clients[numClient];
int cli[numClient];
/*
* Destrucción de los semáforos ante una mala eliminación previa.
* Posteriormente se realiza la apertura.
*/
destroySem();
initSem();
//Inicialización del array pelo
initHair(numClient);
//Creación de hilos y determinación del comportamiento.
pthread_create(&barber, NULL, barbero, NULL);
for(int i = 0; i < numClient; i++){
cli[i] = i;
pthread_create(&clients[i], NULL, cliente, (void*)&cli[i]);
}
//Espera de hilos
for(int i = 0; i < numClient; i++){
pthread_join(clients[i], NULL);
}
/*
* Se realiza un cambio a la variable globar y se desbloquea el
* semáforo clientes ante un posible bloqueo del barbero.
*/
isAtendidos = 1;
sem_post(clientes);
pthread_join(barber, NULL);
//Destrucción de los semáforos y liberación de memoria.
destroySem();
free(pelo);
}else{ //Si el número de argumentos es incorrecto se informa de un error.
fprintf(stderr,"ejecutable [NUM_CLIENTES]\n");
}
}
void initSem(){
//Apertura del semáforo del barbero
if((barberoDesp = sem_open("BARBERO", O_CREAT, 0700, 0)) == SEM_FAILED){
perror("Error sem_open barbero: ");
exit(EXIT_FAILURE);
}
//Apertura del semáforo de clientes
if((clientes = sem_open("CLIENTS", O_CREAT, 0700, 0)) == SEM_FAILED){
perror("Error sem_open clientes: ");
exit(EXIT_FAILURE);
}
/*
* Apertura del semáforo de acceso a la región crítica.
* Inicialmente se permite el acceso.
*/
if((accesos = sem_open("ACCESOS", O_CREAT, 0700, 1)) == SEM_FAILED){
perror("Error sem_open accesos");
exit(EXIT_FAILURE);
}
}
void destroySem(){
//Cierre de los semáforos
sem_close(barberoDesp);
sem_close(clientes);
sem_close(accesos);
//Eliminación de semáforos
sem_unlink("BARBERO");
sem_unlink("CLIENTS");
sem_unlink("ACCESOS");
}
void initHair(int numClientes){
isAtendidos = 0;
//Reserva de memoria e inicialización del array pelo.
pelo = (char *)malloc(numClientes * sizeof(char));
for(int i = 0; i < numClientes; i++){
pelo[i] = 'l';
}
}
void pasear(int clien){
printf("CLIENTE %d: ¡Vaya, parece que no hay sillas! Iré a pasear\n\n",clien);
sleep(rand()%(30-1+1)+1);
}
void cortar(int clien){
sleep(4);
printf(VERDE"CLIENTE %d: El barbero me ha dejado listo\n\n"RESET, clien);
pelo[clien] = CORTO;
}
void *barbero(void *args){
while(!isAtendidos){
//Espera señal del cliente
sem_wait(clientes);
if(!isAtendidos){
printf(CYAN"\nBarbero: hay clientes para atender\n"RESET);
//Se intenta acceder a región crítica
sem_wait(accesos);
//Se libera una silla de la sala de espera
sillasLibres += 1;
//Envía señal de barbero dispuesto a cortar pelo
sem_post(barberoDesp);
//Se libera región crítica
sem_post(accesos);
}
}
pthread_exit(NULL);
}
void *cliente(void *args){
int *cita;
cita = (int *)args;
while(pelo[*cita] == 'l'){
printf("Soy el cliente: %d\n", *cita);
//Se intenta acceder a región crítica
sem_wait(accesos);
if(sillasLibres > 0){
printf("\nVoy a sentarme en una silla. Cliente: %d!\n",*cita);
//El cliente se sienta en la silla
sillasLibres -= 1;
//Aviso a barbero de llegada de clientes
sem_post(clientes);
//Liberación de región crítica
sem_post(accesos);
//Espera para poder cortar el pelo
sem_wait(barberoDesp);
cortar(*cita);
}else{
sem_post(accesos);
pasear(*cita);
}
}
pthread_exit(NULL);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cql.h"
int success = 0,
fails = 0;
void test_section(char *name)
{
int i, len = strlen(name);
printf("\n%s\n",name);
for (i = 0; i < len; i ++)
{
printf("-");
}
printf("\n");
}
void test_assert(char *file, int line, char *test, int cond)
{
printf("%-40s%5s\n", test, cond ? "OK" : "FAIL");
if (cond)
{
success++;
}
else
{
printf(" %s:%d\n",file,line);
fails++;
}
}
#define TEST(test,cond) test_assert(__FILE__,__LINE__,test,cond)
void test_int_parser()
{
struct cql_int_parser_state s;
unsigned char buf[16], *p;
/* test init */
test_section("test init");
cql_int_parser_init_32(&s);
TEST("initial state", s.b.bytes_remaining == 4);
TEST("initial value", s.value == 0);
/* test parse one int byte */
test_section("test int one byte");
cql_int_parser_init_32(&s);
cql_int_parser_process_byte(&s,80);
TEST("final state", s.b.bytes_remaining == 3);
TEST("final value", cql_int_parser_getvalue(&s) == 80);
TEST("not complete", cql_int_parser_complete(&s) == 0);
/* test parse 2 int bytes */
test_section("test int two bytes");
cql_int_parser_init_32(&s);
cql_int_parser_process_byte(&s,0x13);
cql_int_parser_process_byte(&s,0xf2);
TEST("final state", s.b.bytes_remaining == 2);
TEST("final value", cql_int_parser_getvalue(&s) == 0x13f2);
TEST("not complete", cql_int_parser_complete(&s) == 0);
/* test parse 4 int bytes */
test_section("test int four bytes");
cql_int_parser_init_32(&s);
cql_int_parser_process_byte(&s,0xfd);
cql_int_parser_process_byte(&s,0xcc);
cql_int_parser_process_byte(&s,0x12);
cql_int_parser_process_byte(&s,0xf9);
TEST("final state", s.b.bytes_remaining == 0);
TEST("final value", cql_int_parser_getvalue(&s) == 0xfdcc12f9);
TEST("complete", cql_int_parser_complete(&s) == 1);
/* test parse int buffer */
test_section("test int buffer");
*(unsigned long *)buf = htonl(0x89716f34);
cql_int_parser_init_32(&s);
cql_int_parser_process_data(&s,buf,4,&p);
TEST("final state", s.b.bytes_remaining == 0);
TEST("final value", cql_int_parser_getvalue(&s) == 0x89716f34);
TEST("complete", cql_int_parser_complete(&s) == 1);
}
void test_short_parser()
{
struct cql_int_parser_state s;
/* test parse 2 short bytes */
test_section("test int two bytes");
cql_int_parser_init_16(&s);
cql_int_parser_process_byte(&s,0x13);
cql_int_parser_process_byte(&s,0xf2);
TEST("final state", s.b.bytes_remaining == 0);
TEST("final value", cql_int_parser_getvalue(&s) == 0x13f2);
TEST("complete", cql_int_parser_complete(&s) == 1);
}
void test_string_parser()
{
struct cql_string_parser_state s;
unsigned char data[160], *ptr;
int i;
/* test a short string */
test_section("four byte string");
cql_string_parser_init(&s,4);
TEST("using static buffer",s.buf == s.staticbuf);
TEST("initial len",s.b.bytes_remaining == 4);
cql_string_parser_process_byte(&s,'b');
cql_string_parser_process_byte(&s,'a');
TEST("partial len",s.b.bytes_remaining == 2);
cql_string_parser_process_byte(&s,'z');
cql_string_parser_process_byte(&s,'z');
TEST("output value", strcmp(cql_string_parser_getvalue(&s),"bazz") == 0);
TEST("complete", cql_string_parser_complete(&s) == 1);
cql_string_parser_cleanup(&s);
TEST("cleanup",s.buf == s.staticbuf);
/* test a long string */
test_section("long string");
cql_string_parser_init(&s,150);
TEST("using dynamic buffer",s.buf != s.staticbuf && s.buf != NULL);
TEST("initial pointer",s.p == s.buf);
TEST("initial len",s.b.bytes_remaining == 150);
for (i = 0; i < 15; i++)
{
strcpy((char *)data,"abcdefghij");
cql_string_parser_process_data(&s,data,10,&ptr);
TEST("partial len",s.b.bytes_remaining == 150 - 10 * (i+1));
TEST("not complete", cql_string_parser_complete(&s) == ((i+1)==15 ? 1 : 0));
}
*data = 0;
for (i = 0; i < 15; i++)
{
strcat((char *)data,"abcdefghij");
}
TEST("output value", strcmp(cql_string_parser_getvalue(&s),(char *)data) == 0);
TEST("complete", cql_string_parser_complete(&s) == 1);
cql_string_parser_cleanup(&s);
TEST("cleanup",s.buf == NULL);
}
void test_combined_parsers()
{
unsigned char buf[14];
unsigned char *p = buf;
struct cql_int_parser_state ip;
struct cql_string_parser_state sp;
test_section("combined parsers");
/* create a buffer of data with a number followed by a string */
*(short *)buf = htons(12);
memcpy(buf+2,"hello world!",12);
cql_int_parser_init_16(&ip);
cql_int_parser_process_data(&ip,p,14,&p);
TEST("int value",cql_int_parser_getvalue(&ip) == 12);
TEST("pointer position", p == buf+2);
cql_string_parser_init(&sp,12);
cql_string_parser_process_data(&sp,p,12,&p);
TEST("string value",strcmp(cql_string_parser_getvalue(&sp),"hello world!") == 0);
TEST("poiner position", p == buf+14);
}
void test_header_parser()
{
struct cql_header hdr, *parsed_hdr;
struct cql_header_parser p;
unsigned char *d;
d = (unsigned char *)&hdr;
test_section("header parsers");
hdr.cql_version = CQL_VERSION | CQL_REQUEST;
hdr.cql_flags = CQL_FLAG_NONE;
hdr.cql_stream = 1;
hdr.cql_opcode = CQL_OPCODE_QUERY;
hdr.cql_body_length = htonl(1000);
cql_header_parser_init(&p);
TEST("init", p.b.bytes_remaining == sizeof(struct cql_header));
cql_header_parser_process_data(&p,d,5,&d);
TEST("remaining", p.b.bytes_remaining == 3);
cql_header_parser_process_data(&p,d,3,&d);
parsed_hdr = cql_header_parser_getvalue(&p);
TEST("value not null", parsed_hdr != NULL);
TEST("header cql_version", parsed_hdr->cql_version == (CQL_VERSION | CQL_REQUEST));
TEST("header cql_flags", parsed_hdr->cql_flags == CQL_FLAG_NONE);
TEST("header cql_stream", parsed_hdr->cql_stream == 1);
TEST("header cql_opcode", parsed_hdr->cql_opcode == CQL_OPCODE_QUERY);
TEST("header cql_cql_body_length", parsed_hdr->cql_body_length == 1000);
}
void test_header_callback_fn(struct cql_header * hdr, void *ctx)
{
TEST("callback header not null", hdr != NULL);
TEST("callback context not null", ctx != NULL);
TEST("callback header cql_version", hdr->cql_version == (CQL_VERSION | CQL_REQUEST));
*(int *)ctx = 1;
}
void test_result_parser()
{
struct cql_header *hdr, *parsed_hdr;
unsigned char buf[sizeof(struct cql_header) + 8], *d;
struct cql_result_parser p;
int ctx;
hdr = (struct cql_header *)buf;
test_section("result parser on message with no body");
d = buf;
ctx = 0;
hdr->cql_version = CQL_VERSION | CQL_REQUEST;
hdr->cql_flags = CQL_FLAG_NONE;
hdr->cql_stream = 1;
hdr->cql_opcode = CQL_OPCODE_QUERY;
hdr->cql_body_length = 0;
cql_result_parser_init(&p,&ctx);
cql_result_parser_set_callbacks(&p,test_header_callback_fn);
TEST("init state", p.state == CQL_RESULT_IN_HEADER);
TEST("init", p.header_parser.b.bytes_remaining == sizeof(struct cql_header));
cql_result_parser_process_data(&p,d,8,&d);
TEST("pointer", d == buf + 8);
TEST("state", p.state == CQL_RESULT_DONE);
TEST("remaining", p.header_parser.b.bytes_remaining == 0);
TEST("context changed", ctx == 1);
test_section("result parser on message with body");
d = buf;
ctx = 0;
hdr->cql_version = CQL_VERSION | CQL_REQUEST;
hdr->cql_flags = CQL_FLAG_NONE;
hdr->cql_stream = 1;
hdr->cql_opcode = CQL_OPCODE_QUERY;
hdr->cql_body_length = htonl(4);
*(int*)(buf + sizeof(struct cql_header)) = 0xdeadf00d;
cql_result_parser_init(&p,&ctx);
cql_result_parser_set_callbacks(&p,test_header_callback_fn);
TEST("init state", p.state == CQL_RESULT_IN_HEADER);
TEST("init", p.header_parser.b.bytes_remaining == sizeof(struct cql_header));
cql_result_parser_process_data(&p,d,5,&d);
TEST("pointer", d == buf + 5);
TEST("state", p.state == CQL_RESULT_IN_HEADER);
TEST("remaining", p.header_parser.b.bytes_remaining == 3);
TEST("context unchanged", ctx == 0);
cql_result_parser_process_data(&p,d,4,&d);
TEST("pointer", d == buf + 9);
TEST("state", p.state == CQL_RESULT_IN_BODY);
TEST("context changed", ctx == 1);
parsed_hdr = cql_header_parser_getvalue(&p.header_parser);
TEST("value not null", parsed_hdr != NULL);
TEST("header cql_version", parsed_hdr->cql_version == (CQL_VERSION | CQL_REQUEST));
TEST("header cql_flags", parsed_hdr->cql_flags == CQL_FLAG_NONE);
TEST("header cql_stream", parsed_hdr->cql_stream == 1);
TEST("header cql_opcode", parsed_hdr->cql_opcode == CQL_OPCODE_QUERY);
TEST("header cql_cql_body_length", parsed_hdr->cql_body_length == 4);
cql_result_parser_process_data(&p,d,7,&d);
TEST("pointer", d == buf + 12);
TEST("state", p.state == CQL_RESULT_DONE);
}
int main()
{
test_int_parser();
test_short_parser();
test_string_parser();
test_combined_parsers();
test_header_parser();
test_result_parser();
printf("\nsuccess: %d, fail: %d\n",success,fails);
return fails;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct device {int dummy; } ;
typedef int s64 ;
/* Variables and functions */
scalar_t__ PPB_MULT ;
long long TICKS_PER_HOUR ;
int div_s64 (int,long long) ;
int tps65910_rtc_get_calibration (struct device*,int*) ;
__attribute__((used)) static int tps65910_read_offset(struct device *dev, long *offset)
{
int calibration;
s64 tmp;
int ret;
ret = tps65910_rtc_get_calibration(dev, &calibration);
if (ret < 0)
return ret;
/* Convert from RTC calibration register format to ppb format */
tmp = calibration * (s64)PPB_MULT;
if (tmp < 0)
tmp -= TICKS_PER_HOUR / 2LL;
else
tmp += TICKS_PER_HOUR / 2LL;
tmp = div_s64(tmp, TICKS_PER_HOUR);
/* Offset value operates in negative way, so swap sign */
*offset = (long)-tmp;
return 0;
}
|
C
|
#include <stdbool.h>
bool isPowerOfTwo(int n) {
if(n <= 0) return false;
while(n%2 == 0) {
n /= 2;
}
return n == 1;
}
/**
* n = 2 ^ 0 = 1 = 0b0000...0001, and (n-1) = 0 = 0b0000...0000
* n = 2 ^ 1 = 2 = 0b0000...0010, and (n-1) = 1 = 0b0000...0001
* n = 2 ^ 2 = 4 = 0b0000...0100, and (n-1) = 3 = 0b0000...0011
* n = 2 ^ 3 = 8 = 0b0000...1000, and (n-1) = 7 = 0b0000...0111
* ....
* So, (n & (n-1) == 0) when n is power of two.
*/
bool isPowerOfTwo2(int n) {
return n > 0 && ((n & (n-1)) == 0);
}
|
C
|
#include <stdlib.h>
#include "stack.h"
void push(Stack* stack, double value)
{
if( stack->size == stack->capacity )
{
stack->capacity *= 2;
stack->values = (double*)realloc(stack->values, sizeof(double) * stack->capacity);
}
stack->values[stack->size] = value;
stack->size++;
}
double pop(Stack* stack)
{
stack->size--;
double temp = stack->values[stack->size];
return temp;
}
double top(Stack* stack)
{
return stack->values[stack->size-1];
}
void initialize( Stack* stack )
{
stack->capacity = 5;
stack->values = (double)malloc(sizeof(double) * stack.capacity);
stack->size = 0;
}
void cleanUp(Stack* stack)
{
free(stack->capacity);
stack->values = NULL;
free(&stack);
}
|
C
|
#define F_CPU 16000000
#define LCD PORTA
#define RS PA0
#define EN PA2
#define SBI(bit) PORTA |= (1<<bit)
#define CLI(bit) PORTA &= ~(1<<bit)
#include<avr/io.h>
#include<avr/interrupt.h>
#include<util/delay.h>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
char dataBuff[32] = { 0 };
volatile int counter = 0;
int ss,mm,hh;
void initLCD();
void enable();
void lcdCMD(unsigned char cmd);
void lcdData(unsigned char data);
void lcdString(char *str);
void setCursor(uint8_t x, uint8_t y);
void initADC();
int getADCValue();
void initTimer1CTC();
int main()
{
//int adcVal = 0;
DDRC = 0xFF;
PORTC = 0xFF;
DDRA |= (1<<PA3);
initLCD();
initADC();
initTimer1CTC();
lcdCMD(0x14);// Cursor shift,Shift to write
lcdCMD(0x06);//Increment,Accompanies display shift
lcdCMD(0x0C);//Display ON,Cursor ON, Blink ON
lcdCMD(0x01);//Clear Display
lcdCMD(0x80);//Set DDRAM
lcdString("All THE BEST");
setCursor(1,0);
lcdString("Frm JAGANNATH");
_delay_ms(1000);
while(1){
/*lcdCMD(0x01);//Clear Display
adcVal = getADCValue();
sprintf(dataBuff,"ADC=%d",adcVal);
lcdString(dataBuff);
_delay_ms(250);*/
/*if(counter>=1000)
{
counter = 0;
ss++;
}
if(ss >= 60)
{
PORTA |= (1<<PA3);
_delay_ms(200);
PORTA &= ~(1<<PA3);
ss = 0;
mm++;
}
if(mm >= 60)
{
mm = 0;
hh++;
}
sprintf(dataBuff,"%d:%d:%d:%d",hh,mm,ss,counter);
lcdString(dataBuff);
_delay_ms(250);
lcdCMD(0x01);//Clear Display
*/
/* code */
}
return 0;
}
void initLCD()
{
DDRA = 0xFF;
lcdCMD(0x28);//Function set, 2 Lines, Font 5x8 dots
CLI(RS);
enable();
}
void enable()
{
SBI(EN);
_delay_us(200);
CLI(EN);
_delay_us(200);
}
void lcdCMD(unsigned char cmd)
{
LCD = cmd & 0xF0;
CLI(RS);
enable();
cmd = cmd << 4;
LCD = cmd & 0xF0;
CLI(RS);
enable();
}
void lcdData(unsigned char data)
{
LCD = data & 0xF0;
SBI(RS);
enable();
data = data << 4;
LCD = data & 0xF0;
SBI(RS);
enable();
}
void lcdString(char *str)
{
while(*str != 0)
{
lcdData(*str++);
}
}
void setCursor(uint8_t x, uint8_t y)
{
if(x == 0) lcdCMD(0x80|y);//First Line
if(x == 1) lcdCMD(0xC0|y);//Second Line
}
void initADC()
{
ADMUX |= (1<<REFS0);
ADCSRA |= (1<<ADEN) | (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0);
}
int getADCValue()
{
ADCSRA |= (1<<ADSC);
while(!(ADCSRA & (1<<ADIF)));
return ADC;
}
void initTimer1CTC()
{
OCR1A =0xF9;
TCNT1 = 0;
TCCR1B |= (1<<WGM12) | (1<<CS11) | (1<<CS10);
TIMSK |= (1<<OCIE1A);
sei();
}
ISR(TIMER1_COMPA_vect)
{
cli();
PORTC = 0x00;
TCNT1 = 0;
counter++;
sei();
}
|
C
|
#include<stdio.h>
#include"math.h"
main()
{
float a,b,c,p;
float s;
printf("");
scanf("%f%f%f",&a,&b,&c);
p=(a+b+c)/2;
s=p*(p-a)*(p-b)*(p-c);
s=sqrt(s);
printf("s=%f",s);
}
|
C
|
/*
** o.c for HEADER A LA NORME!!! in /home/hervet_g/
**
** Made by geoffrey hervet
** Login <hervet_g@epitech.net>
**
** Started on Sun Mar 25 13:36:49 2012 geoffrey hervet
** Last update Sun Mar 25 13:36:49 2012 geoffrey hervet
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netdb.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include "init.h"
static int init_socket(t_server *serv)
{
struct protoent *pe;
if (NULL == (pe = getprotobyname("TCP")))
{
fprintf(stderr, "Unknown TCP protocole.\n");
return (EXIT_FAILURE);
}
if (-1 == (serv->socket = socket(AF_INET, SOCK_STREAM, pe->p_proto)))
{
perror("Socket fail");
return (EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
static int bind_socket(t_server *srv)
{
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(srv->port);
sin.sin_addr.s_addr = INADDR_ANY;
if (-1 == bind(srv->socket, (struct sockaddr *)&sin, sizeof(sin)))
{
perror("Bind fail");
return (EXIT_FAILURE);
}
if (-1 == listen(srv->socket, 10))
{
perror("listen fail");
return (EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
int init(t_server *srv)
{
if (NULL == (srv->cwd = realpath(".", NULL)))
{
perror("getcwd fail");
return (EXIT_FAILURE);
}
srv->cwd_len = strlen(srv->cwd);
if (EXIT_FAILURE == init_socket(srv) || EXIT_FAILURE == bind_socket(srv))
return (EXIT_FAILURE);
return (EXIT_SUCCESS);
}
|
C
|
#include<stdio.h>
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int a, b;
scanf("%d %d",&a, &b);
if(a % b == 0)
printf("%d\n",0);
else
printf("%d\n",b - a % b);
}
}
|
C
|
/*编程实现书P59 ADTQueue 基本操作9个,用链式存储结构实现;*/
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int QElemType;
typedef int Status;
typedef struct QNode
{
QElemType data;
struct QNode *next;
}QNode, *QueuePtr;
typedef struct
{
QueuePtr front;//队头指针
QueuePtr rear; //队尾指针
}LinkQueue;
//visit函数
void visit(QElemType e){
printf("%d\n", e);
}
//构造一个空队列
Status InitQueue (LinkQueue &Q)
{
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if (!Q.front) exit(OVERFLOW);
Q.front->next = NULL;
return OK;
}
//销毁队列
Status DestoryQueue(LinkQueue &Q){
while(Q.front)
{
Q.rear = Q.front->next;
free(Q.front);
Q.front = Q.rear;
}
return OK;
}
//清空队列
Status ClearQueue(LinkQueue &Q){
while(Q.front)
{
Q.rear = Q.front->next;
free(Q.front);
Q.front = Q.rear;
}
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if (!Q.front) exit(OVERFLOW);
Q.front->next = NULL;
return OK;
}
//判断队列是否为空
Status QueueEmpty(LinkQueue Q){
if (Q.front->next == NULL)
{
return OK;
}
else return ERROR;
}
//返回队列长度
int QueueLength(LinkQueue Q){
QueuePtr p;
int len = 0;
for (p = Q.front->next; p != Q.rear; p = p->next)
{
len++;
}
return len;
}
//用e返回队头元素
Status GetHead(LinkQueue Q, QElemType &e){
QueuePtr p;
if (Q.front->next)
{
p = Q.front->next;
e = p->data;
return OK;
}
else return ERROR;
}
//插入元素e
Status EnQueue(LinkQueue &Q, QElemType e){
QueuePtr p;
p = (QueuePtr)malloc(sizeof(QNode));
if (!p) exit(OVERFLOW);
p->data = e;
p->next = NULL;
Q.rear->next = p;
return OK;
}
//出列
Status DeQueue(LinkQueue &Q, QElemType &e){
QueuePtr p;
if (Q.front == Q.rear) return ERROR;
p = Q.front->next;
e = p->data;
Q.front->next = p->next;
if (Q.rear == p) Q.rear = Q.front;
free(p);
return OK;
}
//遍历队列
Status QueueTraverse(LinkQueue Q){
QueuePtr p;
p = Q.front->next;
while(p)
{
visit(p->data);
p = p->next;
}
return OK;
}
int main(int argc, char const *argv[])
{
LinkQueue qu;
InitQueue(qu);
DestoryQueue(qu);
return 0;
}
|
C
|
#include "vector.h"
#include <malloc.h>
#include <stddef.h>
HTree* newTree(const char value, const uint* const count)
{
HTree* tree = calloc(1, sizeof(HTree));
tree->left = NULL;
tree->right = NULL;
tree->count = *count;
tree->sumbol = value;
return tree;
}
HTree* copyTree(HTree const* const cpyTree)
{
HTree* tree = newTree(cpyTree->sumbol, &cpyTree->count);
tree->left = cpyTree->left;
tree->right = cpyTree->right;
return tree;
}
HTree const* findCode(HTree const* const tree, char const symbol)
{
if (tree->sumbol == symbol)
return tree;
if (tree->left) {
HTree const* temp = findCode(tree->left, symbol);
if (temp)
return temp;
}
if (tree->right) {
HTree const* temp = findCode(tree->right, symbol);
if (temp)
return temp;
}
return NULL;
}
char treeFindSymbol(HTree* const tree, char const* const code, uchar const ind)
{
if (!strcmp(tree->code, code) && tree->count) {
tree->count--;
return tree->sumbol;
}
if (code[ind] == '0') {
if (tree->left) {
char temp = treeFindSymbol(tree->left, code, ind + 1);
if (temp)
return temp;
}
}
if (code[ind] == '1') {
if (tree->right) {
char temp = treeFindSymbol(tree->right, code, ind + 1);
if (temp)
return temp;
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
int main(){
int r, g, b, x, y;
int file;
int xres, yres;
int max_c = 255;
char line[100];
char header[100];
xres = 500;
yres = 500;
file = open("pic.ppm", O_CREAT|O_WRONLY|O_RDONLY);
sprintf(header, "P3 \n %i,%i \n %i \n", xres, yres, max_c);
write(file, header, strlen(header));
for(y = 0;y<yres; y++){
for (x = 0;x<xres; x++){
r = y + 1;
g = (x * x)+ (5 * y);
b = 255;
sprintf(line, "%d %d %d ", r , g, b);
write(file, line, strlen(line));
}
sprintf(line, "%s\n", line);
write(file, line, strlen(line));
}
close(file);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/wait.h>
#include <pthread.h>
#include "utils.h"
#include "structs.h"
#include "img.h"
/*/ Things to do:
- Adaptar la funcion consumer para recibir el pipeline.
- Agregar la obtencion de parametros a la funcion producer.
- Crear Buffer.
- Corregir posibles errores de compilacion (manejo de punteros)
/*/
// Args structs
typedef struct arg_struct_prod {
int bufferSize;
int imageNumber;
} arg_struct_prod;
typedef struct arg_struct_cons {
int bufferSize;
int workload;
int image;
} arg_struct_cons;
// Global variables
int ticket;
int bufferFill;
int currentImageRows;
int globalPixels;
int clssThreshold;
int skipAnalysis;
int busyBuffer;
double kernel[3][3];
Img *globalImgFile;
int* buffer;
int debug;
pthread_mutex_t ticketSelectionMutex;
pthread_mutex_t blackCountingMutex;
pthread_barrier_t fullBufferBarrier;
pthread_barrier_t emptyBufferBarrier;
pthread_barrier_t syncStartBarrier;
void* producer(void* prodArgs)
{
arg_struct_prod* myProdArgs = (arg_struct_prod*) prodArgs;
int i;
char* str;
char* imageName;
int n = 0;
int bfrSize = myProdArgs->bufferSize;
globalImgFile = (Img*) malloc(sizeof(Img));
str = malloc(6 * sizeof(char));
imageName = malloc(12 * sizeof(char));
sprintf(str, "%d", myProdArgs->imageNumber);
strcpy(imageName, "imagen_");
strcat(imageName, str);
strcat(imageName, ".png");
startLecture(globalImgFile, imageName);
currentImageRows = globalImgFile->height;
setAllImgSizes(globalImgFile);
setImage(globalImgFile); //Allocate memory for images being processed
bufferFill = 0;
pthread_barrier_wait(&syncStartBarrier);
busyBuffer = 1;
while(1)
{
for (i = 0; i < bfrSize; i++)
{
buffer[i] = n;
bufferFill++;
if(debug)
printf("Produced %d | bufferFill: %d\n", n, bufferFill);
n++;
if (n == currentImageRows) // Last row of the image
{
if(debug)
printf("Producer out!\n\n");
busyBuffer = 0;
pthread_exit(NULL);
}
}
// This section is executed only if the buffer has been filled and the image still has not been fully read.
busyBuffer = 0;
if(debug)
printf("Buffer filled!\n\n");
if (n == bfrSize)
{
pthread_barrier_wait(&fullBufferBarrier); // Release barrier.
}
pthread_barrier_wait(&emptyBufferBarrier); // Locked until consumers empty buffer.
}
}
void* consumer(void* consArgs)
{
int i;
int localPixels;
arg_struct_cons* myConsArgs = (arg_struct_cons*) consArgs;
int bfrSize = myConsArgs->bufferSize;
int workload = myConsArgs->workload;
int image = myConsArgs->image;
pthread_barrier_wait(&syncStartBarrier);
pthread_barrier_wait(&fullBufferBarrier); // Locked until producer finishes.
for(int work = 0; work < workload; work++)
{
pthread_mutex_lock(&ticketSelectionMutex);
if (bufferFill == 0)
{
if(debug)
printf("Buffer emptied!\n\n");
busyBuffer = 1;
pthread_barrier_wait(&emptyBufferBarrier); // Release barrier
while(busyBuffer == 1);
}
i = ticket;
ticket++;
bufferFill--;
pthread_mutex_unlock(&ticketSelectionMutex);
if(debug)
printf("Consumed %d | bufferFill: %d\n", i, bufferFill);
pConvolution(kernel, globalImgFile, i % (bfrSize));
pRectification(globalImgFile, i % (bfrSize));
pPooling(globalImgFile, kernel, i % (bfrSize));
localPixels = blackPixels(globalImgFile, i % (bfrSize));
pthread_mutex_lock(&blackCountingMutex);
globalPixels = globalPixels + localPixels;
pthread_mutex_unlock(&blackCountingMutex);
}
if((i+1) == currentImageRows)
{
if(skipAnalysis == 1)
{
if(pNearlyBlack(globalImgFile, globalPixels, clssThreshold))
printf("imagen_%d | yes\n", image);
else
printf("imagen_%d | no\n", image);
}
}
}
int main(int argc, char *argv[])
{
int opt;
int flags = 0;
debug = 0;
int imgNumber; // Number of images received.
//int clssThreshold; // Classification threshold.
skipAnalysis = 0; // Boolean. 1 for showing 'nearly black' analysis, 0 for skipping it.
int threads; // Number of threads.
int bufferSize; // Capacity of the buffer for reading section.
int baseWorkload;
int extraWorkload;
int specialWorkload;
char str[128];
while ((opt = getopt(argc, argv, ":h:t:c:m:n:bd")) != -1)
{
switch (opt)
{
// Number of images flag.
case 'c':
if ((imgNumber = validateCFlag(optarg)) == -1)
{
printf("Invalid input in: Number of images (-c)\n");
exit(1);
}
flags++;
break;
// Kernel.
case 'm':
readKernelFile(optarg, kernel);
flags++;
break;
// Classification threshold flag.
case 'n':
if ((clssThreshold = validateNFlag(optarg)) == -1)
{
printf("Invalid input in: Classification threshold (-n)\n");
exit(1);
}
flags++;
break;
// Skipping analysis flag.
case 'b':
skipAnalysis = 1;
break;
// Threads number flag.
case 'h':
if ((threads = validateHFlag(optarg)) == -1)
{
printf("Invalid input in: Number of threads (-h)\n");
exit(1);
}
flags++;
break;
// Buffer capacity flag.
case 't':
if ((bufferSize = validateTFlag(optarg)) == -1)
{
printf("Invalid input in: Buffer capacity (-t)\n");
exit(1);
}
flags++;
break;
case 'd':
debug = 1;
break;
// Missing argument.
case ':':
printf("Option needs an argument\n");
exit(1);
// Unknown flag.
case '?':
printf("Unknown option: %c\n", optopt);
exit(1);
}
}
if (flags != 5)
{
printf("Incorrect number of arguments. Terminating...\n");
exit(1);
}
pthread_t proThread;
pthread_t conThreads[threads];
// Create buffer here
buffer = (int*) malloc(bufferSize * sizeof(int));
// Argument structs here
arg_struct_prod *prodArgs = malloc(sizeof(arg_struct_prod));
prodArgs->bufferSize = bufferSize;
arg_struct_cons *consArgs = malloc(sizeof(arg_struct_cons));
consArgs->bufferSize = bufferSize;
arg_struct_cons *specConsArgs = malloc(sizeof(arg_struct_cons));
specConsArgs->bufferSize = bufferSize;
// Barriers and Mutex settings
pthread_barrier_init(&fullBufferBarrier, NULL, threads+1);
pthread_barrier_init(&emptyBufferBarrier, NULL, 2);
pthread_barrier_init(&syncStartBarrier, NULL, threads+1);
pthread_mutex_init(&ticketSelectionMutex, NULL);
pthread_mutex_init(&blackCountingMutex, NULL);
if (skipAnalysis)
{
printf("Image | nearly black\n");
printf("---------------------------\n");
}
for(int image = 1; image <= imgNumber; image++)
{
bufferFill = -1;
ticket = 0;
globalPixels = 0;
// Producer Argument structure configuration
prodArgs->imageNumber = image;
// Producer thread creation
pthread_create(&proThread, NULL, producer, (void*) prodArgs);
while(bufferFill == -1); // Stop until parameters are retrieved.
// Consumer threads creation
baseWorkload = currentImageRows/threads;
extraWorkload = currentImageRows%threads;
specialWorkload = baseWorkload + extraWorkload;
consArgs->workload = baseWorkload;
specConsArgs->workload = specialWorkload;
consArgs->image = image;
specConsArgs->image = image;
for(int j = 0; j < (threads-1); j++)
{
pthread_create(&conThreads[j], NULL, consumer, (void*) (consArgs));
}
pthread_create(&conThreads[threads-1], NULL, consumer, (void*) (specConsArgs));
pthread_join(proThread, NULL);
for(int c = 0; c < threads; c++)
{
pthread_join(conThreads[c], NULL);
}
}
freeImgMem(globalImgFile);
return 0;
}
|
C
|
/* *********************************************************************** */
/* *********************************************************************** */
/* DATFUNCS Date Functions Library */
/* *********************************************************************** */
/*
File Name : %M%
File Version : %I%
Last Extracted : %D% %T%
Last Updated : %E% %U%
File Description : Converts a 'JDATE' structure to a 'JULIAN'.
Revision History : 1989-11-08 --- Creation.
Michael L. Brock
Copyright Michael L. Brock 1989 - 2018.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
/* *********************************************************************** */
/* *********************************************************************** */
/* *********************************************************************** */
/* Necessary include files . . . */
/* *********************************************************************** */
#include "datfunci.h"
/* *********************************************************************** */
/* *********************************************************************** */
/* *********************************************************************** */
/* BOH
NAME : dattojul
SYNOPSIS : out_julian = dattojul(in_date);
JULIAN out_julian;
const JDATE *in_date;
DESCRIPTION : Converts a structure of type ''JDATE'' to a ''JULIAN''.
PARAMETERS : Parameters to this function are as follow:
(.) ``in_date`` is a pointer to the structure of type
''JDATE'' to be converted to a ''JULIAN''.
RETURNS : The ''JULIAN'' date.
NOTES :
CAVEATS :
SEE ALSO : jultodat
EXAMPLES :
AUTHOR : Michael L. Brock
COPYRIGHT : Copyright 1989 - 2018 Michael L. Brock
OUTPUT INDEX: dattojul
Date Functions:Conversion Functions:dattojul
DATFUNCS Functions:See Date Functions
PUBLISH XREF: dattojul
PUBLISH NAME: dattojul
ENTRY CLASS : Date Functions:Conversion Functions
EOH */
/* *********************************************************************** */
#ifndef NARGS
JULIAN dattojul(const JDATE *in_date)
#else
JULIAN dattojul(in_date)
const JDATE *in_date;
#endif /* #ifndef NARGS */
{
return(ymdtojul(in_date->year, in_date->month, in_date->day));
}
/* *********************************************************************** */
#ifdef TEST_MAIN
#include <memory.h>
#include <stdio.h>
JDATE TestDateList[][2] = {
{ { 1900, 1, 1 }, { 1900, 3, 1 } },
{ { 1988, 1, 1 }, { 1988, 3, 1 } },
{ { 1988, 1, 1 }, { 1989, 1, 1 } },
{ { 1989, 1, 1 }, { 1989, 3, 1 } },
{ { 1989, 1, 1 }, { 1989,12,31 } },
{ { 1989, 1, 1 }, { 1990, 1, 1 } },
{ { 1986,11,15 }, { 2016,11,15 } }
};
COMPAT_FN_DECL(int main, (void));
/* *********************************************************************** */
/* *********************************************************************** */
/* *********************************************************************** */
int main()
{
int count_1;
int count_2;
JULIAN j_list[2];
JDATE temp_date;
fprintf(stderr, "Test routine for function 'dattojul()'\n\n");
for (count_1 = 0; count_1 < (sizeof(TestDateList) /
sizeof(TestDateList[0])); count_1++) {
printf("Days between ");
for (count_2 = 0; count_2 < 2; count_2++) {
printf("%02u/%02u/%04u (%05lu[",
TestDateList[count_1][count_2].month,
TestDateList[count_1][count_2].day,
TestDateList[count_1][count_2].year,
j_list[count_2] = dattojul(&(TestDateList[count_1][count_2])));
jultodat(j_list[count_2], &temp_date);
printf("%s])", (!memcmp((char *) &(TestDateList[count_1][count_2]),
(char *) &temp_date, sizeof(temp_date))) ? "Y" : "N");
printf("%s", (!count_2) ? " and " : " : ");
}
printf("%10ld\n", j_list[1] - j_list[0]);
}
for (count_1 = 0; count_1 < (sizeof(TestDateList) /
sizeof(TestDateList[0])); count_1++) {
for (count_2 = 0; count_2 < 2; count_2++) {
printf("Using 'dattojul()' : ");
printf("%02u/%02u/%04u (%05lu)\n",
TestDateList[count_1][count_2].month,
TestDateList[count_1][count_2].day,
TestDateList[count_1][count_2].year,
j_list[count_2] = dattojul(&(TestDateList[count_1][count_2])));
jultodat(j_list[count_2], &temp_date);
printf(" 'jultodat()' : ");
printf("%02u/%02u/%04u (%05lu)\n\n",
temp_date.month,
temp_date.day,
temp_date.year,
j_list[count_2]);
}
}
return(1);
}
/* *********************************************************************** */
#endif /* #ifdef TEST_MAIN */
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include "image.h"
#define TWOPI 6.2831853
void l1_normalize(image im)
{
for (int c = 0; c < im.c; c++)
{
// loop over the image to calculate the summation of pixel values
float pixel_sum = 0;
for (int x = 0; x < im.w; x++)
{
for (int y = 0; y < im.h; y++)
{
float pixel_value = get_pixel(im, x, y, c);
pixel_sum += pixel_value;
}
}
// loop over the image and normalize each pixel value
for (int x = 0; x < im.w; x++)
{
for (int y = 0; y < im.h; y++)
{
float pixel_value = get_pixel(im, x, y, c);
set_pixel(im, x, y, c, pixel_value / pixel_sum);
}
}
}
}
image make_box_filter(int w)
{
// make a square image w * w with one channel
image filter = make_image(w, w, 1);
// fill the image with uniform entries that sum to 1
for (int i = 0; i < w * w; i++)
filter.data[i] = 1.0;
l1_normalize(filter);
return filter;
}
image convolve_image(image im, image filter, int preserve)
{
// Note that filter's size can'n be even, i.e 1x1, 3x3, 5x5 etc
// filter better have either the same number of channels as im or have 1 channel
assert(im.c == filter.c || filter.c == 1);
// 3 cases:
// 1. filter and im have the same number of channels
// 2. If preserve is set to 1 we should produce an image with the same number of channels as the input
// 3. If the filter only has one channel but im has multiple channels
int numOfChannel;
if (im.c == filter.c)
{
numOfChannel = 1;
if (preserve == 1)
{
numOfChannel = im.c;
}
}
else if (filter.c == 1)
{
numOfChannel = 1;
if (preserve == 1)
{
numOfChannel = 3;
}
}
image convolved = make_image(im.w, im.h, numOfChannel);
float sum, x_im, y_im, filter_pixel, im_pixel;
// loop over every pixel in image
for (int w = 0; w < im.w; w++)
{
for (int h = 0; h < im.h; h++)
{
sum = 0;
for (int c = 0; c < im.c; c++)
{
// set sum to zero when starting to convolve over different channel
if (numOfChannel > 1)
{
sum = 0;
}
// loop over the filter pixels and apply filter to pixel in the center
for (int filter_w = 0; filter_w < filter.w; filter_w++)
{
// to apply to pixel in the center of filter
x_im = w + filter_w - filter.w / 2;
for (int filter_h = 0; filter_h < filter.h; filter_h++)
{
// to apply to pixel in the center of filter
y_im = h + filter_h - filter.h / 2;
// get the center pixel value of the image
im_pixel = get_pixel(im, x_im, y_im, c);
// get the center pixel value of the filter
if (filter.c > 1)
{
filter_pixel = get_pixel(filter, filter_w, filter_h, c);
}
else
{
filter_pixel = get_pixel(filter, filter_w, filter_h, 0);
}
// get the weighted sum over all values resulting from
// convulving the certain pixel with the kernel
sum += im_pixel * filter_pixel;
}
}
// set pixel to new value
if (numOfChannel > 1)
{
set_pixel(convolved, w, h, c, sum);
}
}
if (numOfChannel == 1)
{
set_pixel(convolved, w, h, 0, sum);
}
}
}
return convolved;
}
image make_highpass_filter()
{
image highpass = make_box_filter(3);
highpass.data[0] = 0;
highpass.data[1] = -1;
highpass.data[2] = 0;
highpass.data[3] = -1;
highpass.data[4] = 4;
highpass.data[5] = -1;
highpass.data[6] = 0;
highpass.data[7] = -1;
highpass.data[8] = 0;
return highpass;
}
image make_sharpen_filter()
{
image sharpen = make_box_filter(3);
sharpen.data[0] = 0;
sharpen.data[1] = -1;
sharpen.data[2] = 0;
sharpen.data[3] = -1;
sharpen.data[4] = 5;
sharpen.data[5] = -1;
sharpen.data[6] = 0;
sharpen.data[7] = -1;
sharpen.data[8] = 0;
return sharpen;
}
image make_emboss_filter()
{
image emboss = make_box_filter(3);
emboss.data[0] = -2;
emboss.data[1] = -1;
emboss.data[2] = 0;
emboss.data[3] = -1;
emboss.data[4] = 1;
emboss.data[5] = 1;
emboss.data[6] = 0;
emboss.data[7] = 1;
emboss.data[8] = 2;
return emboss;
}
float gauss_formula(int x, int y, int center, float sigma)
{
/*!
* The probability density function for a 2d gaussian
*/
int sub_x = x - center;
int sub_y = y - center;
return 1. / (TWOPI * sigma * sigma) * exp(-1 * (sub_x * sub_x + sub_y * sub_y) / (2 * sigma * sigma));
}
image make_gaussian_filter(float sigma)
{
/*!
* this func takes a standard deviation value and return
* a filter that smooths using a gaussian with that sigma
*/
// 99% of the probability mass for a gaussian is within +/- 3 standard deviations
// so make the kernel be 6 times the size of sigma
// But also we want an odd number
// so make it be the next highest odd integer from 6x sigma.
int size = ceil(sigma * 6);
size = size % 2 == 0 ? size + 1 : size;
int center = (int)size / 2;
assert(size == center * 2. + 1.);
image kernel = make_image(size, size, 1);
for (int x = 0; x < size; x++)
{
for (int y = 0; y < size; y++)
{
for (int c = 0; c < 1; c++)
{
set_pixel(kernel, x, y, c, gauss_formula(x, y, center, sigma));
}
}
}
// this is a blurring filter so we want all the weights to sum to 1
l1_normalize(kernel);
return kernel;
}
image add_image(image a, image b)
{
// check that the two images have the same size
assert(a.w == b.w && a.h == b.h && a.c == b.c);
// make the new hybrid image
image im = make_image(a.w, a.h, a.c);
// sum
for (int i = 0; i < im.w * im.h * im.c; i++)
{
im.data[i] = a.data[i] + b.data[i];
}
return im;
}
image sub_image(image a, image b)
{
assert(a.w == b.w && a.h == b.h && a.c == b.c);
image im = make_image(a.w, a.h, a.c);
for (int i = 0; i < im.w * im.h * im.c; i++)
{
im.data[i] = a.data[i] - b.data[i];
}
return im;
}
image make_gx_filter()
{
image sobel_filter = make_box_filter(3);
sobel_filter.data[0] = -1;
sobel_filter.data[1] = 0;
sobel_filter.data[2] = 1;
sobel_filter.data[3] = -2;
sobel_filter.data[4] = 0;
sobel_filter.data[5] = 2;
sobel_filter.data[6] = -1;
sobel_filter.data[7] = 0;
sobel_filter.data[8] = 1;
return sobel_filter;
}
image make_gy_filter()
{
image sobel_filter = make_box_filter(3);
sobel_filter.data[0] = -1;
sobel_filter.data[1] = -2;
sobel_filter.data[2] = -1;
sobel_filter.data[3] = 0;
sobel_filter.data[4] = 0;
sobel_filter.data[5] = 0;
sobel_filter.data[6] = 1;
sobel_filter.data[7] = 2;
sobel_filter.data[8] = 1;
return sobel_filter;
}
void feature_normalize(image im)
{
// for comparison
float maxi = -INFINITY;
float mini = +INFINITY;
// find max and min
for (int i = 0; i < im.w * im.h * im.c; i++)
{
maxi = fmax(im.data[i], maxi);
mini = fmin(im.data[i], mini);
}
float range = maxi - mini;
float normalizing_pixel;
for (int w = 0; w < im.w; w++)
{
for (int h = 0; h < im.h; h++)
{
for (int c = 0; c < im.c; c++)
{
float pixel = get_pixel(im, w, h, c);
if (range != 0.)
{
normalizing_pixel = (pixel - mini) / range;
}
else
{
// avoid zero division
normalizing_pixel = 0;
}
set_pixel(im, w, h, c, normalizing_pixel);
}
}
}
}
image *sobel_image(image im)
{
/*!
* return two images, the gradient magnitude and direction
*/
// allocate and zero-initialize array
image *mag_and_direct = calloc(2, sizeof(image));
mag_and_direct[0] = make_image(im.w, im.h, 1);
mag_and_direct[1] = make_image(im.w, im.h, 1);
// make the filters
image sobel_gx = convolve_image(im, make_gx_filter(), 0);
image sobel_gy = convolve_image(im, make_gy_filter(), 0);
for (int w = 0; w < im.w; w++)
{
for (int h = 0; h < im.h; h++)
{
for (int c = 0; c < 1; c++)
{
float x = get_pixel(sobel_gx, w, h, c);
float y = get_pixel(sobel_gy, w, h, c);
// magnitude
set_pixel(mag_and_direct[0], w, h, 0, sqrt(x * x + y * y));
// direction
set_pixel(mag_and_direct[1], w, h, 0, atan2(y, x));
}
}
}
return mag_and_direct;
}
image colorize_sobel(image im)
{
image *mag_and_direct = sobel_image(im);
image colorize_sobel = make_image(im.w, im.h, im.c);
feature_normalize(mag_and_direct[0]);
feature_normalize(mag_and_direct[1]);
float S, V, H;
for (int w = 0; w < im.w; w++)
{
for (int h = 0; h < im.h; h++)
{
// use the magnitude to specify the
// saturation and value of an image
// and the angle to specify the hue
S = get_pixel(mag_and_direct[0], w, h, 0);
V = get_pixel(mag_and_direct[0], w, h, 0);
H = get_pixel(mag_and_direct[1], w, h, 0);
set_pixel(colorize_sobel, w, h, 0, H);
set_pixel(colorize_sobel, w, h, 1, S);
set_pixel(colorize_sobel, w, h, 2, V);
}
}
hsv_to_rgb(colorize_sobel);
return colorize_sobel;
}
|
C
|
//
// main.c
// hello
//
// Created by Gladwin Tirkey on 1/25/19.
// Copyright © 2019 Gladwin Tirkey. All rights reserved.
//
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
#define e 0.001
#define function(x) pow(x,3)-4*x-9
int main(int argc, const char * argv[]) {
// insert code here...
int i;
float a, b, c;
float f0;
printf("Enter a and b \n)");
scanf("%f%f",&a ,&b);
do{
c = (a + b)/2;
f0 = function(c);
if(f0 < 0){
a = c;
}
else{
b = c;
}
i++;
printf("No of iterations %d\n",i);
printf("Root = %f\n",c);
printf("Value of funtion=%f\n",f0);
}while(fabs(b-a)> e);
return 0;
}
|
C
|
#include "UI.h"
char *mainOptionStr[] = {
" "
, " "
, " "
, " "
, " ˻ "
, " "
, " "
};
void gotoxy(Point pos){
COORD Cur;
Cur.X = pos.x;
Cur.Y = pos.y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Cur);
}
int animationSleep(int xPos){
return (xPos - 35)*(xPos - 35)/ 150;
}
//η ̵ϴ Cursor ġ شϴ option .
int cursorPosVerti(Point std, int range, int interval, int state){
int opt = state;
char ch = 0;
Point pos = { std.x, std.y + state*interval };
while (ch != '\r'){
gotoxy(pos);
printf(SHAPE_VERTICURSOR);
ch = _getch();
if (ch == -32){
ch = _getch();
}
if (ch == 72 || ch == 80){
gotoxy(pos);
printf(" ");
}
if (ch == 72 && pos.y > std.y){
pos.y = pos.y - interval;
opt--;
}
else if (ch == 80 && pos.y < std.y + (range-1) * interval){
pos.y = pos.y + interval;
opt++;
}
}
return opt;
}
//η ̵ϴ Cursor ġ شϴ option .
int cursorPosHoriz(Point std, int range, int interval, int state){
int opt = state;
char ch = 0;
Point pos = { std.x + state * interval, std.y };
while (ch != '\r'){
gotoxy(pos);
printf(SHAPE_HORIZCURSOR);
ch = _getch();
if (ch == -32){
ch = _getch();
}
if (ch == 75 || ch == 77){
gotoxy(pos);
printf(" ");
}
if (ch == 75 && pos.x > std.x){
pos.x = pos.x - interval;
opt--;
}
else if (ch == 77 && pos.x < std.x + (range-1)*interval){
pos.x = pos.x + interval;
opt++;
}
}
return opt;
}
void printWithSpace(int num, char *str){
int i;
for (i = 0; i < num; i++){
printf(" ");
}
printf(str);
}
void printCenter(char *str){
int i;
printWithSpace((strlen(WIDTHUP) - strlen(str)) / 2, "");
printf(str);
printf("\n");
}
// .
void mainMenu(int select){
HANDLE hC = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
Point pos = { 0,0 };
int i;
GetConsoleScreenBufferInfo(hC, &csbi);
gotoxy(pos);
printf(WIDTHUP);
printf("\n \n");
printf(WIDTHDOWN);
pos.x = 6; pos.y = 1;
SetConsoleTextAttribute(hC, 14);
for (i = 0; i < 7; i++){
gotoxy(pos);
pos.x = pos.x + HORIZMOVE_START;
printf("%s", mainOptionStr[i]);
}
SetConsoleTextAttribute(hC, 31);
if (select != 0){
pos.x = 6 + (select - 1) * HORIZMOVE_START;
gotoxy(pos);
printf("%s", mainOptionStr[select - 1]);
}
SetConsoleTextAttribute(hC, 7);
pos.x = 6;
pos.y = 4;
gotoxy(pos);
}
//Form Value Data
void printSelectedValue(Point pos, Value *selectedValues[], int selectedValuesSize){
int i;
for (i = 0; i < selectedValuesSize; i++){
gotoxy(pos); printf(FORM_PRINT_SELECTED_VALUES_1, selectedValues[i]->key, selectedValues[i]->name, selectedValues[i]->phone);
pos.y++;
gotoxy(pos); printf(FORM_PRINT_SELECTED_VALUES_2, selectedValues[i]->address);
pos.y += SPACE_BETWEEN_EDIT_EACHVALUES - 1;
}
}
/************************************************************************/
/* Start Message */
/* */
/* Give a message and options to user */
/************************************************************************/
int startMessage(int state){
Point pos = { 9, 4 };
int opt;
system("cls");
mainMenu(0);
/*
printWithSpace(30, "1. \n");
printWithSpace(30, "2. \n");
printWithSpace(30, "3. \n");
printWithSpace(30, "4. \n");
printWithSpace(30, "5. ˻\n");
printWithSpace(30, "6. \n");
printWithSpace(30, "7. \n");
*/
opt = cursorPosHoriz(pos, MENUSIZE_START, HORIZMOVE_START, state);
return opt;
}
/************************************************************************/
/* Wrong Message */
/* */
/* Notice user choose wrong option */
/************************************************************************/
void wrongMessage(){
system("cls");
printf(WIDTHUP);
printf("\n\n");
printCenter("SOMETHING WRONG.\n");
}
void getMessage(){
system("cls");
}
void printMessage(){
system("cls");
mainMenu(1);
printf("й | ̸ | ּ | ȭȣ\n");
}
void registerForm(int state){
//ش Value Data ġ Ŀ Ǿ ̵.
Point pos = { REGISTER_X_POS+INDENT_EACHVALUEDATA, REGISTER_Y_POS
+ state*VERTIMOVE_REGI + SPACE_BETWEEN_REGISTER_EACHVALUEDATA };
gotoxy(pos); printf(ERASE); printf(ERASE); printf(ERASE);
gotoxy(pos);
}
void registerMessage(){
Point pos = { REGISTER_X_POS, REGISTER_Y_POS };
system("cls");
mainMenu(2);
printf("л Էϼ");
gotoxy(pos); printf(REGIMENU_0);
pos.y += VERTIMOVE_REGI; gotoxy(pos); printf(REGIMENU_1);
pos.y += VERTIMOVE_REGI; gotoxy(pos); printf(REGIMENU_2);
pos.y += VERTIMOVE_REGI; gotoxy(pos); printf(REGIMENU_3);
pos.x += INDENT_EACHVALUEDATA; pos.y = REGISTER_Y_POS + SPACE_BETWEEN_REGISTER_EACHVALUEDATA;
gotoxy(pos);
}
int selectValueMessage(Value *selectedValues[], int selectedValuesSize){
int i;
int selectedValueNum;
Point pos = { SUBMENU_MAIN_X_POS + INDENT_EACHVALUES, SUBMENU_MAIN_Y_POS + SPACE_BETWEEN_SEARCH_BAR };
// Value
printSelectedValue(pos, selectedValues, selectedValuesSize);
//Cursor
pos.x = SUBMENU_MAIN_X_POS;
pos.y = SUBMENU_MAIN_Y_POS + SPACE_BETWEEN_SEARCH_BAR;
selectedValueNum = cursorPosVerti(pos, selectedValuesSize, SPACE_BETWEEN_EDIT_EACHVALUES, 0);
// ǵư ERASE.
pos.x = SUBMENU_MAIN_X_POS;
pos.y = SUBMENU_MAIN_Y_POS + SPACE_BETWEEN_SEARCH_BAR;
for (i = 0; i < selectedValuesSize*SPACE_BETWEEN_EDIT_EACHVALUES; i++){
gotoxy(pos);
printf(ERASE); printf(ERASE); printf(ERASE);
pos.y += 1;
}
return selectedValueNum;
}
int deleteMessage(int state){
Point pos = { SUBMENU_TEXT_X_POS, SUBMENU_TEXT_Y_POS };
system("cls");
mainMenu(3);
// (ID, ̸, ȭȣ, )
gotoxy(pos); printf(SUBMENU_1);
pos.y += VERTIMOVE_DELETE;
gotoxy(pos); printf(SUBMENU_2);
pos.y += VERTIMOVE_DELETE;
gotoxy(pos); printf(SUBMENU_3);
pos.y += VERTIMOVE_DELETE;
gotoxy(pos); printf(SUBMENU_4);
//Cursor
pos.x -= SUBMENU_TEXT_X_POS - SUBMENU_CURSOR_X_POS;
pos.y -= (MENUSIZE_DELETE - 1) * VERTIMOVE_DELETE;
state = cursorPosVerti(pos, MENUSIZE_DELETE, VERTIMOVE_DELETE, state);
//
pos.x = SUBMENU_MAIN_X_POS;
pos.y = SUBMENU_MAIN_Y_POS;
gotoxy(pos);
return state;
}
int editValueMessage(void* selectedValue, int state){
Point pos = { SUBMENU_MAIN_X_POS, SUBMENU_MAIN_Y_POS };
//ID
gotoxy(pos); printf(ERASE);
gotoxy(pos); printf(SUBMENU_EDIT_0);
pos.y += SPACE_BETWEEN_EDIT_EACHVALUEDATA;
pos.x += INDENT_EACHVALUEDATA;
gotoxy(pos); printf("%d", ((Value*)selectedValue)->key);
pos.y += VERTIMOVE_EDITMAIN - SPACE_BETWEEN_EDIT_EACHVALUEDATA;
pos.x -= INDENT_EACHVALUEDATA;
//̸
gotoxy(pos); printf(SUBMENU_EDIT_1);
pos.y += SPACE_BETWEEN_EDIT_EACHVALUEDATA;
pos.x += INDENT_EACHVALUEDATA;
gotoxy(pos); printf("%s", ((Value*)selectedValue)->name);
pos.y += VERTIMOVE_EDITMAIN - SPACE_BETWEEN_EDIT_EACHVALUEDATA;
pos.x -= INDENT_EACHVALUEDATA;
//ּ
gotoxy(pos); printf(SUBMENU_EDIT_2);
pos.y += SPACE_BETWEEN_EDIT_EACHVALUEDATA;
pos.x += INDENT_EACHVALUEDATA;
gotoxy(pos); printf("%s", ((Value*)selectedValue)->address);
pos.y += VERTIMOVE_EDITMAIN - SPACE_BETWEEN_EDIT_EACHVALUEDATA;
pos.x -= INDENT_EACHVALUEDATA;
//ȭȣ
gotoxy(pos); printf(SUBMENU_EDIT_3);
pos.y += SPACE_BETWEEN_EDIT_EACHVALUEDATA;
pos.x += INDENT_EACHVALUEDATA;
gotoxy(pos); printf("%s", ((Value*)selectedValue)->phone);
pos.y += VERTIMOVE_EDITMAIN - SPACE_BETWEEN_EDIT_EACHVALUEDATA;
pos.x -= INDENT_EACHVALUEDATA;
//
gotoxy(pos); printf(SUBMENU_EDIT_4);
//Cursor
pos.x -= SPACE_BETWEEN_CURSOR;
pos.y -= (MENUSIZE_EDITMAIN-1) * VERTIMOVE_EDITMAIN;
state = cursorPosVerti(pos, MENUSIZE_EDITMAIN, VERTIMOVE_EDITMAIN, state);
// ö .
pos.x = SUBMENU_MAIN_X_POS;
pos.y = SUBMENU_MAIN_Y_POS;
gotoxy(pos);
return state;
}
void editForm(int state){
//ش Value Data ġ Ŀ Ǿ ̵.
Point pos = { SUBMENU_MAIN_X_POS + INDENT_EACHVALUEDATA, SUBMENU_MAIN_Y_POS
+ (state + 1) * VERTIMOVE_EDITMAIN + SPACE_BETWEEN_EDIT_EACHVALUEDATA };
gotoxy(pos); printf(ERASE); printf(ERASE); printf(ERASE);
gotoxy(pos);
}
int editMessage(int state){
Point pos = { SUBMENU_TEXT_X_POS, SUBMENU_TEXT_Y_POS };
system("cls");
mainMenu(4);
// (ID, ̸, ȭȣ, )
gotoxy(pos); printf(SUBMENU_1);
pos.y += VERTIMOVE_EDIT;
gotoxy(pos); printf(SUBMENU_2);
pos.y += VERTIMOVE_EDIT;
gotoxy(pos); printf(SUBMENU_3);
pos.y += VERTIMOVE_EDIT;
gotoxy(pos); printf(SUBMENU_4);
//Cursor
pos.x -= SUBMENU_TEXT_X_POS - SUBMENU_CURSOR_X_POS;
pos.y -= (MENUSIZE_EDIT - 1) * VERTIMOVE_EDIT;
state = cursorPosVerti(pos, MENUSIZE_EDIT, VERTIMOVE_EDIT, state);
// ø .
pos.x = SUBMENU_MAIN_X_POS;
pos.y = SUBMENU_MAIN_Y_POS;
gotoxy(pos);
return state;
}
void printSearchResult(Value* selectedValues[], int selectedValuesSize){
Point pos = { SUBMENU_MAIN_X_POS, SUBMENU_MAIN_Y_POS + SPACE_BETWEEN_SEARCH_BAR};
printSelectedValue(pos, selectedValues, selectedValuesSize);
getchar();
}
int searchMessage(int state){
Point pos = { SUBMENU_TEXT_X_POS, SUBMENU_TEXT_Y_POS };
system("cls");
mainMenu(5);
// (ID, ̸, ȭȣ, )
gotoxy(pos); printf(SUBMENU_1);
pos.y += VERTIMOVE_SEARCH;
gotoxy(pos); printf(SUBMENU_2);
pos.y += VERTIMOVE_SEARCH;
gotoxy(pos); printf(SUBMENU_3);
pos.y += VERTIMOVE_SEARCH;
gotoxy(pos); printf(SUBMENU_4);
//Cursor
pos.x -= SUBMENU_TEXT_X_POS - SUBMENU_CURSOR_X_POS;
pos.y -= (MENUSIZE_SEARCH - 1) * VERTIMOVE_SEARCH;
state = cursorPosVerti(pos, MENUSIZE_SEARCH, VERTIMOVE_SEARCH, state);
// ø .
pos.x = SUBMENU_MAIN_X_POS;
pos.y = SUBMENU_MAIN_Y_POS;
gotoxy(pos);
return state;
}
void saveMessage(){
HANDLE hC = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hC, &csbi);
Point pos = { 0, 22 };
int i;
mainMenu(6);
SetConsoleTextAttribute(hC, 177);
gotoxy(pos); for (i = 0; i <= strlen(WIDTHUP); i++){
Sleep(animationSleep(i));
printf(" ");
}
pos.x = (strlen(WIDTHUP) - strlen(MESSAGE_SAVE)) / 2; gotoxy(pos); printf(MESSAGE_SAVE);
SetConsoleTextAttribute(hC, 7);
getchar();
}
int quitMessage(){
Point pos = {(strlen(WIDTHUP) - strlen(MESSAGE_END_BEFORE_SAVE))/2, END_Y_POS};
int state;
system("cls");
mainMenu(7);
gotoxy(pos); printf(MESSAGE_END_BEFORE_SAVE);
pos.y += 2;
pos.x = (strlen(WIDTHUP) + SPACE_BETWEEN_END_MENU - strlen(ENDMENU_2) -2) / 2; gotoxy(pos);
printf(ENDMENU_2);
pos.x = strlen(WIDTHUP) / 2 - strlen(ENDMENU_1) - SPACE_BETWEEN_END_MENU / 2; gotoxy(pos);
printf(ENDMENU_1);
pos.y++;
state = cursorPosHoriz(pos, MENUSIZE_END, SPACE_BETWEEN_END_MENU, 0);
return state;
}
void mismatchmMessage(){
HANDLE hC = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hC, &csbi);
Point pos = { 0, 23 };
int i;
SetConsoleTextAttribute(hC, 199);
gotoxy(pos); for (i = 0; i <= strlen(WIDTHUP); i++){
Sleep(animationSleep(i)); printf(" ");
}
pos.x = (strlen(WIDTHUP) - strlen(MESSAGE_MISMATCH)) / 2; gotoxy(pos); printf(MESSAGE_MISMATCH);
SetConsoleTextAttribute(hC, 7);
getchar();
}
void invalidInputMessage(){
printf(MESSAGE_INVALIDINPUT);
getchar();
}
void byeMessage(){
HANDLE hC = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hC, &csbi);
Point pos = { 0, 23 };
int i;
SetConsoleTextAttribute(hC, 241);
gotoxy(pos); for (i = 0; i <= strlen(WIDTHUP); i++){
Sleep( animationSleep(i) );
printf(" ");
}
pos.x = (strlen(WIDTHUP) - strlen(MESSAGE_BYE)) / 2; gotoxy(pos); printf(MESSAGE_BYE);
SetConsoleTextAttribute(hC, 7);
}
void registerFinishMessage(){
HANDLE hC = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hC, &csbi);
Point pos = { 0, 23 };
int i;
SetConsoleTextAttribute(hC, 151);
gotoxy(pos); for (i = 0; i <= strlen(WIDTHUP); i++){
Sleep(animationSleep(i));
printf(" ");
}
pos.x = (strlen(WIDTHUP) - strlen(MESSAGE_REGISTERFINISH)) / 2; gotoxy(pos); printf(MESSAGE_REGISTERFINISH);
SetConsoleTextAttribute(hC, 7);
getchar();
}
void removeFinishMessage(){
HANDLE hC = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hC, &csbi);
Point pos = { 0, 23 };
int i;
SetConsoleTextAttribute(hC, 132);
gotoxy(pos); for (i = 0; i <= strlen(WIDTHUP); i++){
Sleep(animationSleep(i));
printf(" ");
}
pos.x = (strlen(WIDTHUP) - strlen(MESSAGE_REMOVEFINISH)) / 2; gotoxy(pos); printf(MESSAGE_REMOVEFINISH);
SetConsoleTextAttribute(hC, 7);
getchar();
}
|
C
|
#include <linux/debugfs.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#define MAX_LOG_SIZE 10000
MODULE_LICENSE("GPL");
static struct dentry *dir, *inputdir, *ptreedir;
static struct task_struct *curr;
struct process_node {
char *comm; //command
int pid; //pid
struct list_head list; // ptree linked list node for this process
};
static LIST_HEAD(head);
static char *logs;
struct debugfs_blob_wrapper *my_blob;
static void ptree_logging(void) {
struct process_node *entry;
int j = 0;
logs = kmalloc(sizeof(char) * MAX_LOG_SIZE, GFP_KERNEL); // string arr
list_for_each_entry(entry, &head, list) {
j += snprintf(logs + j, 64, "%s (%d)\n", entry -> comm, entry -> pid);
} // logs[j] = logging
my_blob -> data = logs; // save all logs
my_blob -> size = (unsigned long)strlen(logs);
}
static void insert_node(struct task_struct *task) {
struct process_node *node;
node = kmalloc(sizeof(struct process_node), GFP_KERNEL);
if(!node) {
printk("alloc failed\n");
return;
}
node -> comm = task -> comm;
node -> pid = task -> pid;
list_add(&node -> list, &head);
}
static ssize_t write_pid_to_input(struct file *fp,
const char __user *user_buffer,
size_t length,
loff_t *position)
{
pid_t input_pid;
sscanf(user_buffer, "%u", &input_pid);
curr = pid_task(find_get_pid(input_pid), PIDTYPE_PID);
if(curr == NULL) {
printk("This process is not currently running\n");
}
// insert leaf process
insert_node(curr);
while(1) {
// track upward and insert to linked list
curr = curr -> parent;
insert_node(curr);
// if last insert was init(1)
if(curr -> pid == 1) {
break;
}
}
ptree_logging();
//reinitialize linkedlist for next one
list_del_init(&head);
return length;
}
static const struct file_operations dbfs_fops = {
.write = write_pid_to_input,
};
static int __init dbfs_module_init(void)
{
// Implement init module code
//#if 0
dir = debugfs_create_dir("ptree", NULL);
if (!dir) {
printk("Cannot create ptree dir\n");
return -1;
}
inputdir = debugfs_create_file("input", 0222, dir, NULL, &dbfs_fops);
my_blob = (struct debugfs_blob_wrapper *)kmalloc(sizeof(struct debugfs_blob_wrapper), GFP_KERNEL);
ptreedir = debugfs_create_blob("ptree", 0644, dir, my_blob); // Find suitable debugfs API
//#endif
printk("dbfs_ptree module initialize done\n");
return 0;
}
static void __exit dbfs_module_exit(void)
{
// Implement exit module code
// free
kfree(my_blob);
kfree(logs);
// remove
debugfs_remove_recursive(dir);
printk("dbfs_ptree module exit\n");
}
module_init(dbfs_module_init);
module_exit(dbfs_module_exit);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "LinkedList.h"
int main(int argc, char *argv[]){
Boolean isOk;
LinkedList l = createEmptyList();
int value;
isOk = push(&l, 9);
isOk = push(&l, 12);
printAll(l);
isOk = removeFirst(&l, &value);
printf("Remove One\nNew Length: %d\n", getLength(l));
append(&l, 15);
append(&l, 56);
append(&l, 69);
insert(&l, getNode(l,56), 12);
printAll(l);
removeFromKey(&l, 56);
printAll(l);
}
|
C
|
#include"rio.h"
void rio_readinit(rio_t *rp, int fd){
int flags;
rp->fd=fd;
rp->cnt=0;
rp->bufp=rp->buf;
memset(rp->buf, 0, ETH_FRAME_LEN+PROXY_HLEN);
/**
* Use fcntl() to set the flags of the file descriptor to include
* non-blocking.
*/
if(flags=fcntl(rp->fd, F_GETFL, 0)<0){
perror("F_GETFL error");
exit(-1);
}
flags|=O_NONBLOCK;
if(fcntl(rp->fd, F_SETFL, flags)<0){
perror("F_SETFL error");
exit(-1);
}
}
int Wait(int fd, int events){
/**
* poll structure for waiting until the file descriptor is ready.
* Initialization upon declaration of a static variable implies that
* the variable is initialized only once.
*/
static struct pollfd pfd={0, 0, 0};
pfd.fd=fd;
pfd.events=events;
// Loop blocking poll call in case of signal interrupt.
do{
if(poll(&pfd, 1, -1)<0){
if(errno!=EINTR){
perror("poll() error");
return -1;
}
}
}while(errno==EINTR);
return 0;
}
int Lock(int fd, int type){
/**
* flock structures are necessary for file-locking via fcntl().
* Initialization upon declaration of a static variable implies that
* the variable is initialized only once.
*/
static struct flock lock={0, 0, 0, 0, 0};
lock.l_type=type;
// Loop a blocking lock call in case of signal interruption.
do
if(fcntl(fd, F_SETLKW, &lock)<0)
// If fcntl() encounters an error, return error status.
if(errno!=EINTR)
return -1;
while(errno==EINTR);
return 0;
}
ssize_t rio_read(rio_t *rp, void *usrbuf, size_t n){
int cnt;
/**
* Wait indefinitely until the socket is ready for reading.
*
* Returning from Wait() implies that the socket has data to be
* received.
*
* Returning from Lock() implies that the file descriptor is locked
* or unlocked, allowing for exclusive access to file descriptors.
*
* Receive the packet into the buffer.
*
* Wrap locking procedure over error-handling in case fcntl() is
* interrupted by a signal or encounters an error. This error-
* handling code is copied in rio_write().
*/
/*
if(Lock(rp->fd, F_RDLCK)<0)
return -1;
*/
while(rp->cnt<=0){
if(Wait(rp->fd, POLLIN)<0)
return -1;
rp->cnt=read(rp->fd, rp->buf, sizeof(rp->buf));
if(rp->cnt<0){
// signal interrupt case
if(errno!=EINTR&&errno!=EAGAIN){
//Lock(rp->fd, F_UNLCK);
return -1;
}
}
// EOF case
else if(rp->cnt==0){
//Lock(rp->fd, F_UNLCK);
return 0;
}
// no error
else
rp->bufp=rp->buf;
}
/*
if(Lock(rp->fd, F_UNLCK)<0)
return -1;
*/
cnt=n;
// if bytes read were less than demanded
if(rp->cnt<n)
cnt=rp->cnt;
// copy read bytes into memory
memcpy(usrbuf, rp->bufp, cnt);
// decrement count of number of unread bytes
rp->cnt-=cnt;
// Reset buffer pointer to beginning if necessary.
if(rp->cnt<=0)
rp->bufp=rp->buf;
// increment buffer pointer to first unread byte
else
rp->bufp+=cnt;
// return number of bytes read
return cnt;
}
ssize_t rio_readnb(rio_t *rp, void *usrbuf, size_t n){
ssize_t nread;
size_t nleft=n;
void *bufp=usrbuf;
while(nleft>0){
if((nread=rio_read(rp, bufp, nleft))<0){
// signal handler interrupt
if(errno==EINTR)
nread=0;
// read() error
else
return -1;
}
// EOF
else if(nread==0)
break;
// Decrement number of bytes left by number of bytes read.
nleft-=nread;
// Increment buffer pointer by number of bytes read.
bufp+=nread;
}
// return total number of bytes read
return (n-nleft);
}
ssize_t rio_write(rio_t *rp, void *usrbuf, size_t n){
size_t nleft=n;
ssize_t nwritten;
char *bufp=usrbuf;
if(Lock(rp->fd, F_WRLCK)<0)
return -1;
while(nleft>0){
if(Wait(rp->fd, POLLOUT)<0)
return -1;
if((nwritten=write(rp->fd, bufp, nleft))<0){
// interrupted by signal handler
if(errno==EINTR)
nwritten=0;
// interrupted by write()
else{
if(Lock(rp->fd, F_UNLCK)<0)
return -1;
return -1;
}
}
// decrement number of bytes remaining by number of bytes written
nleft-=nwritten;
// increment buffer pointer by number of bytes written
bufp+=nwritten;
}
if(Lock(rp->fd, F_UNLCK)<0)
return -1;
// n will always equal number of bytes finally written
return (n-nleft);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* drawing.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lmittie <lmittie@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/19 17:57:55 by lmittie #+# #+# */
/* Updated: 2019/10/22 18:00:09 by lmittie ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
#include <stdio.h>
float max_step(float x, float y)
{
if (x < 0)
x = x * -1;
if (y < 0)
y = y * -1;
if (x > y)
return (x);
else
return (y);
}
void isometric(float *x, float *y, int z)
{
*x = (*x - *y) * cos(0.5222);
*y = (*x + *y) * sin(0.5222) - z;
}
void zoom(t_coord *crds, float *x1, float *y1, t_fdf *data)
{
crds->x *= data->zoom;
crds->y *= data->zoom;
*x1 *= data->zoom;
*y1 *= data->zoom;
}
void shift(t_coord *crds, float *x1, float *y1)
{
crds->x += 500;
crds->y += 500;
*x1 += 500;
*y1 += 500;
}
void draw_line(t_coord crds, float x1, float y1, t_fdf *data)
{
float x_step;
float y_step;
float max;
int z1;
crds.z = data->map[(int)crds.y][(int)crds.x] * 2;
z1 = data->map[(int)y1][(int)x1] * 2;
zoom(&crds, &x1, &y1, data);
data->color = (crds.z || z1) ? 0xF00000 : 0xFFF000;
isometric(&crds.x, &crds.y, crds.z);
isometric(&x1, &y1, z1);
shift(&crds, &x1, &y1);
x_step = x1 - crds.x;
y_step = y1 - crds.y;
max = max_step(x_step, y_step);
x_step /= max;
y_step /= max;
while ((int)(x1 - crds.x) || (int)(y1 - crds.y))
{
mlx_pixel_put(data->mlx_ptr, data->win_ptr,
crds.x, crds.y, data->color);
crds.x += x_step;
crds.y += y_step;
}
}
static void delete_map(int ***map)
{
int i;
i = 0;
while ((*map)[i] != NULL)
{
free((*map)[i]);
(*map)[i++] = NULL;
}
free(*map);
*map = NULL;
}
void draw(t_fdf *data)
{
t_coord crds;
crds.y = 0;
while (crds.y < data->hight)
{
crds.x = 0;
while (crds.x < data->width)
{
if (crds.x < data->width - 1)
draw_line(crds, crds.x + 1, crds.y, data);
if (crds.y < data->hight - 1)
draw_line(crds, crds.x, crds.y + 1, data);
crds.x++;
}
crds.y++;
}
delete_map(&(data->map));
}
|
C
|
/* experiments in reverting back to previous order */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NR 4
#define NC 12
#define N NC*NR
int main(int argc, char *argv[])
{
int i, j;
/* declarations */
int *a=malloc(N*sizeof(int));
int *b=malloc(N*sizeof(int));
int *c=malloc(N*sizeof(int));
int *d=malloc(N*sizeof(int));
for(i=0;i<N;++i)
a[i]=i;
for(i=0;i<NR;++i)
for(j=0;j<NC;++j)
b[NR*j+i] = a[NC*i+j];
for(i=0;i<NR;++i) {
for(j=0;j<NC;++j) {
c[NC*i+j] = b[NR*j+i];
d[NC*i+j] = NR*j+i;
}
}
for(i=0;i<N;++i)
printf("%i ", b[i]);
printf("\n");
for(i=0;i<N;++i)
printf("%i ", i+b[b[i]]);
printf("\n");
for(i=0;i<N;++i)
printf("%i ", d[i]);
printf("\n");
for(i=0;i<N;++i)
printf("%i ", d[i]-b[b[i]]);
printf("\n");
// so this finally is how it is done
for(i=0;i<N;++i)
b[i] =i;
for(i=0;i<N;++i)
printf("%i ", b[i]);
printf("\n");
free(a);
free(b);
free(c);
free(d);
return 0;
}
|
C
|
main()
{
int year,month,day,a,m[12]={31,28,31,30,31,30,31,31,30,31,30,31},i,sum=0;
scanf("%d %d %d",&year,&month,&day);
if(year%4==0&&year%100!=0)
a=1;
else if(year%100==0&&year%400==0)
a=1;
else
a=0;
if(a==1)
{
m[1]=29;
for(i=0;i<month-1;i++)
sum=sum+m[i];
sum=sum+day;
}
else if(a==0)
{
for(i=0;i<month-1;i++)
sum=sum+m[i];
sum=sum+day;
}
printf("%d\n", sum);
}
|
C
|
/**
* @file Activity_3.h
* @author Rohan Tehalyani
* @brief Modulate PWM output based on Temp. sensor
* @version 0.1
* @date 2021-07-27
*
* @copyright Copyright (c) 2021
*
*/
#ifndef __ACTIVITY_3_H__
#define __ACTIVITY_3_H__
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
/**
* @brief Initialize Timer for PWM operation
*
*/
void PWMInit(void);
/**
* @brief Modulate PWM output duty cycle based on Temperature Sensor value
*
* @param data Temperature Sensor value
*/
void PWMOutput(uint16_t);
/**
* @brief Turn OFF Output of PWM when Heater is off
*
*/
void PWMHeaterOFF(void);
#endif
|
C
|
/* Program to convert base32 encoded string to base64
* Compilation : gcc problem9.c
* Execution : ./a.out
* Ankush Chhabra 1910990144 17-08-2021
* Assignment_3 -> Bits and Bytes
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#define ll long long int
//Function to calculate pow(a,b)
int custompower(int x,int y)
{
int temp;
if(y == 0)
return 1;
temp = custompower(x, y / 2);
if (y % 2 == 0)
return temp * temp;
else
{
if(y > 0)
return x * temp * temp;
else
return (temp * temp) / x;
}
}
//Function to find length of string
int customstrlen(char* s)
{
int size=0;
while(s[size]!='\0')
{
size++;
}
return size;
}
int main() {
int t;
scanf("%d",&t);
while(t--){
// take input of 32 base encoded string
char s[1000];
scanf("%s",s);
// create a string for 64 base
char ans[66];
for(int i=0;i<26;i++)
ans[i]=(char)('A' + i);
int cnt=0;
for(int i=26;i<52;i++)
ans[i]=(char)('a' + cnt++ );
cnt=0;
for(int i=52;i<62;i++)
ans[i]=(char)('a' + cnt++ );
ans[62]='+';
ans[63]='/';
// convert 32 base to decimal base.
ll final=0;
int val=0;
for(int i=customstrlen(s)-1;i>=0;i--)
{
char l='A',r='Z';
if(s[i]>=l && s[i]<=r)
{
final+=(custompower( 32 , val )) * ( (int)( s[i] - 'A' ) );
}
else
{
final+=(custompower( 32 , val )) * ( (int)( s[i] - '2' + 26 ) );
}
val++;
}
char ans2[100];
int low=0;
// convert decimal to 64 base
while(final!=0)
{
int rem=final%64;
ans2[low++]=ans[rem];
final/=64;
}
ans2[low]='\0';
printf("%s\n",ans2);
}
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int i, fat = 1;
for(i=10; i > 1; i--)
{
fat *= i;
}
return 0;
}
|
C
|
#include<stdio.h>
int main(void)
{
int a,b,c,d,e;
printf("enter three-digit NO.:");
scanf("%d",&a);
d=a/100,b=a%10,c=a/10%10;
e=b*100+c*10+d;
printf("%d\n",e );
return 0;
}
|
C
|
#include "../../stdio_common.h"
void runSuccess() {
char buf[100];
FILE* file = VALID_FILE;
if (file != NULL) {
fread(buf, 1, 100, file);
}
}
void runSuccess1() {
char buf[100];
FILE* file = VALID_FILE;
if (file != NULL) {
fread(buf, 1, 50, file);
}
}
void runSuccess2() {
char buf[100];
FILE* file = VALID_FILE;
if (file != NULL) {
fread(buf, 2, 50, file);
}
}
void runFailure() {
char buf[100];
FILE* file = VALID_FILE;
if (file != NULL) {
fread(NULL, 1, 100, file);
}
}
void runFailure1() {
char buf[100];
fread(buf, 1, 100, NULL);
}
void runFailure2() {
char buf[100];
FILE* file = VALID_FILE;
if (file != NULL) {
fread(NULL, 1, 200, file);
}
}
void runFailure3() {
char buf[100];
FILE* file = VALID_FILE;
if (file != NULL) {
fread(NULL, 2, 100, file);
}
}
int f;
void testValues() {
f = 2;
size_t result;
char buf[100];
FILE* file = VALID_FILE;
if (file != NULL) {
result = fread(buf, 1, 100, file);
//@ assert result <= 100;
}
//@ assert f == 2;
//@ assert vacuous: \false;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c, d, x1, x2, x;
printf(" Digite o valor de A: \n");
scanf("%f", &a);
printf(" Digite o valor de B: \n");
scanf("%f", &b);
printf(" Digite o valor de C: \n");
scanf("%f", &c);
if (a!=0)
{
d = (pow(b,2)-4*a*c);
if(d<0)
printf(" No tem soluao! \n");
else if(d==0)
{
x = (-b + sqrt(d))/2*a;
printf("S tem uma soluao e o seu valor e: %.1f \n", x);
}
else if(d>0)
{
x1 = (-b + sqrt(d))/2*a;
x2 = (-b - sqrt(d))/2*a;
printf(" Tem duas soluoes que sao: %.1f e %.1f \n", x1, x2);
}
}
}
|
C
|
/**
* This is the implementation file for
* the queue ADT.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "queue.h"
struct queueNode {
int data;
struct queueNode *next;
};
struct queue {
struct queueNode *head;
struct queueNode *tail;
};
QNode create_node(int data, QNode next) {
QNode new = malloc(sizeof(struct queueNode));
assert(new != NULL);
new->data = data;
new->next = next;
return new;
}
Queue new_queue(void) {
Queue q = malloc(sizeof(struct queue));
assert(q != NULL);
q->head = NULL;
q->tail = NULL;
return q;
}
Queue enqueue(int data, Queue q) {
assert(q != NULL);
QNode node = create_node(data, NULL);
if (q->head == NULL) {
q->head = node;
q->tail = node;
return q;
}
q->tail->next = node;
q->tail = q->tail->next;
return q;
}
Queue dequeue(Queue q) {
assert(q != NULL);
if (q->head == NULL) {
return q;
}
if (q->head == q->tail) {
q->tail = q->tail->next;
}
QNode temp = q->head;
q->head = q->head->next;
free(temp);
return q;
}
void print_queue(Queue q) {
assert(q != NULL);
printf("FRONT | ");
QNode curr = q->head;
while (curr != NULL) {
printf("%d -> ", curr->data);
curr = curr->next;
}
printf("X | BACK\n");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.