language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | /* picoc data type module. This manages a tree of data types and has facilities
* for parsing data types. */
#include "interpreter.h"
/* some basic types */
struct ValueType UberType;
struct ValueType IntType;
struct ValueType ShortType;
struct ValueType CharType;
struct ValueType LongType;
struct ValueType UnsignedIntType;
struct ValueType UnsignedShortType;
struct ValueType UnsignedLongType;
#ifndef NO_FP
struct ValueType FPType;
#endif
struct ValueType VoidType;
struct ValueType TypeType;
struct ValueType FunctionType;
struct ValueType MacroType;
struct ValueType EnumType;
struct ValueType GotoLabelType;
struct ValueType *CharPtrType;
struct ValueType *CharPtrPtrType;
struct ValueType *CharArrayType;
struct ValueType *VoidPtrType;
static int PointerAlignBytes;
static int IntAlignBytes;
/* add a new type to the set of types we know about */
struct ValueType *TypeAdd(struct ParseState *Parser, struct ValueType *ParentType, enum BaseType Base, int ArraySize, const char *Identifier, int Sizeof, int AlignBytes)
{
struct ValueType *NewType = VariableAlloc(Parser, sizeof(struct ValueType), TRUE);
NewType->Base = Base;
NewType->ArraySize = ArraySize;
NewType->Sizeof = Sizeof;
NewType->AlignBytes = AlignBytes;
NewType->Identifier = Identifier;
NewType->Members = NULL;
NewType->FromType = ParentType;
NewType->DerivedTypeList = NULL;
NewType->OnHeap = TRUE;
NewType->Next = ParentType->DerivedTypeList;
ParentType->DerivedTypeList = NewType;
return NewType;
}
/* given a parent type, get a matching derived type and make one if necessary.
* Identifier should be registered with the shared string table. */
struct ValueType *TypeGetMatching(struct ParseState *Parser, struct ValueType *ParentType, enum BaseType Base, int ArraySize, const char *Identifier, int AllowDuplicates)
{
int Sizeof;
int AlignBytes;
struct ValueType *ThisType = ParentType->DerivedTypeList;
while (ThisType != NULL && (ThisType->Base != Base || ThisType->ArraySize != ArraySize || ThisType->Identifier != Identifier))
ThisType = ThisType->Next;
if (ThisType != NULL)
{
if (AllowDuplicates)
return ThisType;
else
ProgramFail(Parser, "data type '%s' is already defined", Identifier);
}
switch (Base)
{
case TypePointer: Sizeof = sizeof(void *); AlignBytes = PointerAlignBytes; break;
case TypeArray: Sizeof = ArraySize * ParentType->Sizeof; AlignBytes = ParentType->AlignBytes; break;
case TypeEnum: Sizeof = sizeof(int); AlignBytes = IntAlignBytes; break;
default: Sizeof = 0; AlignBytes = 0; break; /* structs and unions will get bigger when we add members to them */
}
return TypeAdd(Parser, ParentType, Base, ArraySize, Identifier, Sizeof, AlignBytes);
}
/* stack space used by a value */
int TypeStackSizeValue(struct Value *Val)
{
if (Val != NULL && Val->ValOnStack)
return TypeSizeValue(Val, FALSE);
else
return 0;
}
/* memory used by a value */
int TypeSizeValue(struct Value *Val, int Compact)
{
if (IS_INTEGER_NUMERIC(Val) && !Compact)
return sizeof(ALIGN_TYPE); /* allow some extra room for type extension */
else if (Val->Typ->Base != TypeArray)
return Val->Typ->Sizeof;
else
return Val->Typ->FromType->Sizeof * Val->Typ->ArraySize;
}
/* memory used by a variable given its type and array size */
int TypeSize(struct ValueType *Typ, int ArraySize, int Compact)
{
if (IS_INTEGER_NUMERIC_TYPE(Typ) && !Compact)
return sizeof(ALIGN_TYPE); /* allow some extra room for type extension */
else if (Typ->Base != TypeArray)
return Typ->Sizeof;
else
return Typ->FromType->Sizeof * ArraySize;
}
/* add a base type */
void TypeAddBaseType(struct ValueType *TypeNode, enum BaseType Base, int Sizeof, int AlignBytes)
{
TypeNode->Base = Base;
TypeNode->ArraySize = 0;
TypeNode->Sizeof = Sizeof;
TypeNode->AlignBytes = AlignBytes;
TypeNode->Identifier = StrEmpty;
TypeNode->Members = NULL;
TypeNode->FromType = NULL;
TypeNode->DerivedTypeList = NULL;
TypeNode->OnHeap = FALSE;
TypeNode->Next = UberType.DerivedTypeList;
UberType.DerivedTypeList = TypeNode;
}
/* initialise the type system */
void TypeInit()
{
struct IntAlign { char x; int y; } ia;
struct ShortAlign { char x; short y; } sa;
struct CharAlign { char x; char y; } ca;
struct LongAlign { char x; long y; } la;
#ifndef NO_FP
struct DoubleAlign { char x; double y; } da;
#endif
struct PointerAlign { char x; void *y; } pa;
IntAlignBytes = (char *)&ia.y - &ia.x;
PointerAlignBytes = (char *)&pa.y - &pa.x;
UberType.DerivedTypeList = NULL;
TypeAddBaseType(&IntType, TypeInt, sizeof(int), IntAlignBytes);
TypeAddBaseType(&ShortType, TypeShort, sizeof(short), (char *)&sa.y - &sa.x);
TypeAddBaseType(&CharType, TypeChar, sizeof(unsigned char), (char *)&ca.y - &ca.x);
TypeAddBaseType(&LongType, TypeLong, sizeof(long), (char *)&la.y - &la.x);
TypeAddBaseType(&UnsignedIntType, TypeUnsignedInt, sizeof(unsigned int), IntAlignBytes);
TypeAddBaseType(&UnsignedShortType, TypeUnsignedShort, sizeof(unsigned short), (char *)&sa.y - &sa.x);
TypeAddBaseType(&UnsignedLongType, TypeUnsignedLong, sizeof(unsigned long), (char *)&la.y - &la.x);
TypeAddBaseType(&VoidType, TypeVoid, 0, 1);
TypeAddBaseType(&FunctionType, TypeFunction, sizeof(int), IntAlignBytes);
TypeAddBaseType(&MacroType, TypeMacro, sizeof(int), IntAlignBytes);
TypeAddBaseType(&GotoLabelType, TypeGotoLabel, 0, 1);
#ifndef NO_FP
TypeAddBaseType(&FPType, TypeFP, sizeof(double), (char *)&da.y - &da.x);
TypeAddBaseType(&TypeType, Type_Type, sizeof(double), (char *)&da.y - &da.x); /* must be large enough to cast to a double */
#else
TypeAddBaseType(&TypeType, Type_Type, sizeof(struct ValueType *), PointerAlignBytes);
#endif
CharArrayType = TypeAdd(NULL, &CharType, TypeArray, 0, StrEmpty, sizeof(char), (char *)&ca.y - &ca.x);
CharPtrType = TypeAdd(NULL, &CharType, TypePointer, 0, StrEmpty, sizeof(void *), PointerAlignBytes);
CharPtrPtrType = TypeAdd(NULL, CharPtrType, TypePointer, 0, StrEmpty, sizeof(void *), PointerAlignBytes);
VoidPtrType = TypeAdd(NULL, &VoidType, TypePointer, 0, StrEmpty, sizeof(void *), PointerAlignBytes);
}
/* deallocate heap-allocated types */
void TypeCleanupNode(struct ValueType *Typ)
{
struct ValueType *SubType;
struct ValueType *NextSubType;
/* clean up and free all the sub-nodes */
for (SubType = Typ->DerivedTypeList; SubType != NULL; SubType = NextSubType)
{
NextSubType = SubType->Next;
TypeCleanupNode(SubType);
if (SubType->OnHeap)
{
/* if it's a struct or union deallocate all the member values */
if (SubType->Members != NULL)
{
VariableTableCleanup(SubType->Members);
HeapFreeMem(SubType->Members);
}
/* free this node */
HeapFreeMem(SubType);
}
}
}
void TypeCleanup()
{
TypeCleanupNode(&UberType);
}
/* parse a struct or union declaration */
void TypeParseStruct(struct ParseState *Parser, struct ValueType **Typ, int IsStruct)
{
struct Value *LexValue;
struct ValueType *MemberType;
char *MemberIdentifier;
char *StructIdentifier;
struct Value *MemberValue;
enum LexToken Token;
int AlignBoundary;
Token = LexGetToken(Parser, &LexValue, FALSE);
if (Token == TokenIdentifier)
{
LexGetToken(Parser, &LexValue, TRUE);
StructIdentifier = LexValue->Val->Identifier;
Token = LexGetToken(Parser, NULL, FALSE);
}
else
{
static char TempNameBuf[7] = "^s0000";
StructIdentifier = PlatformMakeTempName(TempNameBuf);
}
*Typ = TypeGetMatching(Parser, &UberType, IsStruct ? TypeStruct : TypeUnion, 0, StructIdentifier, Token != TokenLeftBrace);
Token = LexGetToken(Parser, NULL, FALSE);
if (Token != TokenLeftBrace)
{
/* use the already defined structure */
if ((*Typ)->Members == NULL)
ProgramFail(Parser, "structure '%s' isn't defined", LexValue->Val->Identifier);
return;
}
if (TopStackFrame != NULL)
ProgramFail(Parser, "struct/union definitions can only be globals");
LexGetToken(Parser, NULL, TRUE);
(*Typ)->Members = VariableAlloc(Parser, sizeof(struct Table) + STRUCT_TABLE_SIZE * sizeof(struct TableEntry), TRUE);
(*Typ)->Members->HashTable = (struct TableEntry **)((char *)(*Typ)->Members + sizeof(struct Table));
TableInitTable((*Typ)->Members, (struct TableEntry **)((char *)(*Typ)->Members + sizeof(struct Table)), STRUCT_TABLE_SIZE, TRUE);
do {
TypeParse(Parser, &MemberType, &MemberIdentifier, NULL);
if (MemberType == NULL || MemberIdentifier == NULL)
ProgramFail(Parser, "invalid type in struct");
MemberValue = VariableAllocValueAndData(Parser, sizeof(int), FALSE, NULL, TRUE);
MemberValue->Typ = MemberType;
if (IsStruct)
{
/* allocate this member's location in the struct */
AlignBoundary = MemberValue->Typ->AlignBytes;
if (((*Typ)->Sizeof & (AlignBoundary-1)) != 0)
(*Typ)->Sizeof += AlignBoundary - ((*Typ)->Sizeof & (AlignBoundary-1));
MemberValue->Val->Integer = (*Typ)->Sizeof;
(*Typ)->Sizeof += TypeSizeValue(MemberValue, TRUE);
}
else
{
/* union members always start at 0, make sure it's big enough to hold the largest member */
MemberValue->Val->Integer = 0;
if (MemberValue->Typ->Sizeof > (*Typ)->Sizeof)
(*Typ)->Sizeof = TypeSizeValue(MemberValue, TRUE);
}
/* make sure to align to the size of the largest member's alignment */
if ((*Typ)->AlignBytes < MemberValue->Typ->AlignBytes)
(*Typ)->AlignBytes = MemberValue->Typ->AlignBytes;
/* define it */
if (!TableSet((*Typ)->Members, MemberIdentifier, MemberValue, Parser->FileName, Parser->Line, Parser->CharacterPos))
ProgramFail(Parser, "member '%s' already defined", &MemberIdentifier);
if (LexGetToken(Parser, NULL, TRUE) != TokenSemicolon)
ProgramFail(Parser, "semicolon expected");
} while (LexGetToken(Parser, NULL, FALSE) != TokenRightBrace);
/* now align the structure to the size of its largest member's alignment */
AlignBoundary = (*Typ)->AlignBytes;
if (((*Typ)->Sizeof & (AlignBoundary-1)) != 0)
(*Typ)->Sizeof += AlignBoundary - ((*Typ)->Sizeof & (AlignBoundary-1));
LexGetToken(Parser, NULL, TRUE);
}
/* create a system struct which has no user-visible members */
struct ValueType *TypeCreateOpaqueStruct(struct ParseState *Parser, const char *StructName, int Size)
{
struct ValueType *Typ = TypeGetMatching(Parser, &UberType, TypeStruct, 0, StructName, FALSE);
/* create the (empty) table */
Typ->Members = VariableAlloc(Parser, sizeof(struct Table) + STRUCT_TABLE_SIZE * sizeof(struct TableEntry), TRUE);
Typ->Members->HashTable = (struct TableEntry **)((char *)Typ->Members + sizeof(struct Table));
TableInitTable(Typ->Members, (struct TableEntry **)((char *)Typ->Members + sizeof(struct Table)), STRUCT_TABLE_SIZE, TRUE);
Typ->Sizeof = Size;
return Typ;
}
/* parse an enum declaration */
void TypeParseEnum(struct ParseState *Parser, struct ValueType **Typ)
{
struct Value *LexValue;
struct Value InitValue;
enum LexToken Token;
struct ValueType *EnumType;
int EnumValue = 0;
char *EnumIdentifier;
Token = LexGetToken(Parser, &LexValue, FALSE);
if (Token == TokenIdentifier)
{
LexGetToken(Parser, &LexValue, TRUE);
EnumIdentifier = LexValue->Val->Identifier;
Token = LexGetToken(Parser, NULL, FALSE);
}
else
{
static char TempNameBuf[7] = "^e0000";
EnumIdentifier = PlatformMakeTempName(TempNameBuf);
}
EnumType = TypeGetMatching(Parser, &UberType, TypeEnum, 0, EnumIdentifier, Token != TokenLeftBrace);
*Typ = &IntType;
if (Token != TokenLeftBrace)
{
/* use the already defined enum */
if ((*Typ)->Members == NULL)
ProgramFail(Parser, "enum '%s' isn't defined", EnumIdentifier);
return;
}
if (TopStackFrame != NULL)
ProgramFail(Parser, "enum definitions can only be globals");
LexGetToken(Parser, NULL, TRUE);
(*Typ)->Members = &GlobalTable;
memset((void *)&InitValue, '\0', sizeof(struct Value));
InitValue.Typ = &IntType;
InitValue.Val = (union AnyValue *)&EnumValue;
do {
if (LexGetToken(Parser, &LexValue, TRUE) != TokenIdentifier)
ProgramFail(Parser, "identifier expected");
EnumIdentifier = LexValue->Val->Identifier;
if (LexGetToken(Parser, NULL, FALSE) == TokenAssign)
{
LexGetToken(Parser, NULL, TRUE);
EnumValue = ExpressionParseInt(Parser);
}
VariableDefine(Parser, EnumIdentifier, &InitValue, NULL, FALSE);
Token = LexGetToken(Parser, NULL, TRUE);
if (Token != TokenComma && Token != TokenRightBrace)
ProgramFail(Parser, "comma expected");
EnumValue++;
} while (Token == TokenComma);
}
/* parse a type - just the basic type */
int TypeParseFront(struct ParseState *Parser, struct ValueType **Typ, int *IsStatic)
{
struct ParseState Before;
struct Value *LexerValue;
enum LexToken Token;
int Unsigned = FALSE;
struct Value *VarValue;
int StaticQualifier = FALSE;
*Typ = NULL;
/* ignore leading type qualifiers */
ParserCopy(&Before, Parser);
Token = LexGetToken(Parser, &LexerValue, TRUE);
while (Token == TokenStaticType || Token == TokenAutoType || Token == TokenRegisterType || Token == TokenExternType)
{
if (Token == TokenStaticType)
StaticQualifier = TRUE;
Token = LexGetToken(Parser, &LexerValue, TRUE);
}
if (IsStatic != NULL)
*IsStatic = StaticQualifier;
/* handle signed/unsigned with no trailing type */
if (Token == TokenSignedType || Token == TokenUnsignedType)
{
enum LexToken FollowToken = LexGetToken(Parser, &LexerValue, FALSE);
Unsigned = (Token == TokenUnsignedType);
if (FollowToken != TokenIntType && FollowToken != TokenLongType && FollowToken != TokenShortType && FollowToken != TokenCharType)
{
if (Token == TokenUnsignedType)
*Typ = &UnsignedIntType;
else
*Typ = &IntType;
return TRUE;
}
Token = LexGetToken(Parser, &LexerValue, TRUE);
}
switch (Token)
{
case TokenIntType: *Typ = Unsigned ? &UnsignedIntType : &IntType; break;
case TokenShortType: *Typ = Unsigned ? &UnsignedShortType : &ShortType; break;
case TokenCharType: *Typ = &CharType; break;
case TokenLongType: *Typ = Unsigned ? &UnsignedLongType : &LongType; break;
#ifndef NO_FP
case TokenFloatType: case TokenDoubleType: *Typ = &FPType; break;
#endif
case TokenVoidType: *Typ = &VoidType; break;
case TokenStructType: case TokenUnionType:
if (*Typ != NULL)
ProgramFail(Parser, "bad type declaration");
TypeParseStruct(Parser, Typ, Token == TokenStructType);
break;
case TokenEnumType:
if (*Typ != NULL)
ProgramFail(Parser, "bad type declaration");
TypeParseEnum(Parser, Typ);
break;
case TokenIdentifier:
/* we already know it's a typedef-defined type because we got here */
VariableGet(Parser, LexerValue->Val->Identifier, &VarValue);
*Typ = VarValue->Val->Typ;
break;
default: ParserCopy(Parser, &Before); return FALSE;
}
return TRUE;
}
/* parse a type - the part at the end after the identifier. eg. array specifications etc. */
struct ValueType *TypeParseBack(struct ParseState *Parser, struct ValueType *FromType)
{
enum LexToken Token;
struct ParseState Before;
ParserCopy(&Before, Parser);
Token = LexGetToken(Parser, NULL, TRUE);
if (Token == TokenLeftSquareBracket)
{
/* add another array bound */
if (LexGetToken(Parser, NULL, FALSE) == TokenRightSquareBracket)
{
/* an unsized array */
LexGetToken(Parser, NULL, TRUE);
return TypeGetMatching(Parser, TypeParseBack(Parser, FromType), TypeArray, 0, StrEmpty, TRUE);
}
else
{
/* get a numeric array size */
enum RunMode OldMode = Parser->Mode;
int ArraySize;
Parser->Mode = RunModeRun;
ArraySize = ExpressionParseInt(Parser);
Parser->Mode = OldMode;
if (LexGetToken(Parser, NULL, TRUE) != TokenRightSquareBracket)
ProgramFail(Parser, "']' expected");
return TypeGetMatching(Parser, TypeParseBack(Parser, FromType), TypeArray, ArraySize, StrEmpty, TRUE);
}
}
else
{
/* the type specification has finished */
ParserCopy(Parser, &Before);
return FromType;
}
}
/* parse a type - the part which is repeated with each identifier in a declaration list */
void TypeParseIdentPart(struct ParseState *Parser, struct ValueType *BasicTyp, struct ValueType **Typ, char **Identifier)
{
struct ParseState Before;
enum LexToken Token;
struct Value *LexValue;
int Done = FALSE;
*Typ = BasicTyp;
*Identifier = StrEmpty;
while (!Done)
{
ParserCopy(&Before, Parser);
Token = LexGetToken(Parser, &LexValue, TRUE);
switch (Token)
{
case TokenOpenBracket:
if (*Typ != NULL)
ProgramFail(Parser, "bad type declaration");
TypeParse(Parser, Typ, Identifier, NULL);
if (LexGetToken(Parser, NULL, TRUE) != TokenCloseBracket)
ProgramFail(Parser, "')' expected");
break;
case TokenAsterisk:
if (*Typ == NULL)
ProgramFail(Parser, "bad type declaration");
*Typ = TypeGetMatching(Parser, *Typ, TypePointer, 0, StrEmpty, TRUE);
break;
case TokenIdentifier:
if (*Typ == NULL || *Identifier != StrEmpty)
ProgramFail(Parser, "bad type declaration");
*Identifier = LexValue->Val->Identifier;
Done = TRUE;
break;
default: ParserCopy(Parser, &Before); Done = TRUE; break;
}
}
if (*Typ == NULL)
ProgramFail(Parser, "bad type declaration");
if (*Identifier != StrEmpty)
{
/* parse stuff after the identifier */
*Typ = TypeParseBack(Parser, *Typ);
}
}
/* parse a type - a complete declaration including identifier */
void TypeParse(struct ParseState *Parser, struct ValueType **Typ, char **Identifier, int *IsStatic)
{
struct ValueType *BasicType;
TypeParseFront(Parser, &BasicType, IsStatic);
TypeParseIdentPart(Parser, BasicType, Typ, Identifier);
}
|
C | #include <stdio.h>
int I;
int perfecto(long);
void imprime(long *);
void main()
{
long PER[4], J = 6;
int eval;
for (I = 0; I < 4; I++)
{
eval = 0;
while (eval == 0)
{
eval = perfecto(J);
J++;
}
PER[I] = J-1;
}
printf("\nLos numeros perfectos son: ");
imprime(PER);
}
int perfecto(long N)
{
int J, sum = 0, res;
for (J = 1; J <= N / 2; J++)
{
if ((N % J) == 0)
{
sum = sum + J;
}
}
if(sum == N)
{
res = 1;
}
else
{
res = 0;
}
return res;
}
void imprime(long A[])
{
for(I = 0; I < 4; I++)
{
printf("\nPosicion %d: %ld", I+1, A[I]);
}
} |
C | #include <stdio.h>
#include <conio.h>
void main()
{
int a,i,dem=0;
printf("nhap so a\n");
scanf("%d",&a);
if (a<2)
{
printf("a khong phai la so nguyen to\n");
}
else if (a==2)
{
printf("a=2 la mot so nguyen to\n");
}
else
for (i=2;i<a;i++)
if (a%i==0)
dem++;
if (dem==0)
printf("a=%d la mot so nguyen to\n",a);
else
printf("a=%d khong phai la mot so nguyen to\n",a);
getch();
}
|
C | //--- Include Headers --------------------------------------------------------//
#include "error_handling.h"
#include "test.h"
//--- External Functions -----------------------------------------------------//
/**
* @brief Returns value that multiplies the two parameters.
* It has a multiplication table limit.
*
* @param param1 operand for multiplication
* @param param2 operand for multiplication
* @return tERROR common error structure
*/
tERROR test1(uint32_t param1, uint32_t param2) {
// Check parameters
if ((2 > param1) && (param1 > 9)) {
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
#if !defined (_MSC_VER)
#include <unistd.h>
#else
#pragma warning ( disable : 4244 )
#endif
#include <string.h>
#if defined (__MINGW32__) || defined (_MSC_VER)
// Later versions of MSVC can handle %lld but some older
// ones can only handle %I64d. Easiest to simply use
// %I64d then all versions of MSVC will handle it just fine
#define LLd "I64d"
#else
#define LLd "lld"
#endif
#define MAX_LVL_LEN 28
#define MAX_LEN 7
#define C2I(c) ((unsigned int)(unsigned char)(c))
unsigned int * proba1;
unsigned int * proba2;
unsigned int * first;
int main(int argc, char * * argv)
{
FILE * fichier;
char * ligne;
unsigned int i;
unsigned int j;
unsigned int k;
unsigned int l;
unsigned long long index;
unsigned char position[256];
unsigned int charset;
unsigned int nb_lignes;
if(argc!=3)
{
printf("Usage: %s statfile pwdfile\n", argv[0]);
return -1;
}
fichier = fopen(argv[1], "r");
if(!fichier)
{
printf("could not open %s\n", argv[1]);
return -1;
}
first = malloc( sizeof(int) * 256 );
ligne = malloc(4096);
proba2 = malloc(sizeof(unsigned int) * 256 * 256);
proba1 = malloc(sizeof(unsigned int) * 256 );
for(i=0;i<256*256;i++)
proba2[i] = 1000;
for(i=0;i<256;i++)
proba1[i] = 1000;
for(i=0;i<256;i++)
{
first[i] = 255;
position[i] = 255;
}
nb_lignes = 0;
charset = 0;
while(fgets(ligne, 4096, fichier))
{
if (ligne[0] == 0)
continue;
ligne[strlen(ligne)-1] = 0; // chop
if( sscanf(ligne, "%d=proba1[%d]", &i, &j) == 2 )
{
proba1[j] = i;
if(position[j] == 255)
{
position[j] = charset;
charset++;
}
}
if( sscanf(ligne, "%d=proba2[%d*256+%d]", &i, &j, &k) == 3 )
{
if( (first[j]>k) && (i<1000))
first[j] = k;
proba2[j*256+k] = i;
if(position[k] == 255)
{
position[k] = charset;
charset++;
}
}
nb_lignes++;
}
fclose(fichier);
fichier = fopen(argv[2], "r");
if(!fichier)
{
printf("could not open %s\n", argv[2]);
return -1;
}
while(fgets(ligne, 4096, fichier))
{
if (ligne[0] == 0)
continue;
ligne[strlen(ligne)-1] = 0; // chop
i=1; j=0; k=0;
j = C2I(ligne[0]);
k = proba1[j];
printf("%s\t%d", ligne, k);
l = 0;
index = position[j];
if(position[j]==255)
index = 8.1E18;
while(ligne[i])
{
if(index<8E18)
index = (index*charset)+position[C2I(ligne[i])];
if(position[C2I(ligne[i])]==255)
index = 8.1E18;
printf("+%d", proba2[j*256+C2I(ligne[i])]);
k+=proba2[j*256+C2I(ligne[i])];
if(l)
l+=proba2[j*256+C2I(ligne[i])];
if(i==2)
l=proba1[C2I(ligne[i])];
j = C2I(ligne[i]);
i++;
}
if(index<8E18)
printf("\t%d\t%d\t%"LLd"\t%d\n",k,i,index,l);
else
printf("\t%d\t%d\t-\t%d\n",k,i,l);
}
free(proba1);
free(proba2);
free(first);
free(ligne);
fprintf(stderr, "charsetsize = %d\n", charset);
return 0;
}
|
C | /*
Dynamically allocate memory for a string
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char * str = NULL;
char enough;
int limit;
printf("You are going to enter a text\nBut before we need the limit to this text: ");
scanf("%d", &limit);
str = (char *) calloc(limit, sizeof(char));
if (str != NULL){
printf("Now enter the text: ");
scanf("%s",str);
printf("This is the string you wrote: %s\n", str);
printf("Is that enough [Y/N]? ");
scanf(" %c", &enough);
if (enough == 'N'){
printf("How many more chacters would you like to write?");
scanf("%d", &limit);
realloc(str, limit);
char new[limit];
scanf(" %s", new);
strcat(str, new);
}
printf("This is your string: %s\n", str);
}
free(str);
return 0;
} |
C | /**
* \file
*
* \brief Misc utility functions and definitions
*
* Copyright (C) 2009 Atmel Corporation. All rights reserved.
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel AVR product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#ifndef UTIL_H_INCLUDED
#define UTIL_H_INCLUDED
#include <compiler.h>
#include <stdint.h>
#include <types.h>
/**
* \defgroup utility_group Utility Library
*
* This is a collection of utility functions and macros which may be
* useful when dealing with certain common problems, e.g. accessing data
* from a byte stream, simple mathematical operations, etc.
*
* @{
*/
/**
* \brief Stringify the result after expansion of a macro argument.
*/
#define xstr(s) str(s)
/**
* \brief Stringify a macro argument without expansion.
*/
#define str(s) #s
/**
* \brief Get the number of elements in array @a a.
*/
#define ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0]))
/**
* \brief Determine whether or not the character @a c is a digit.
*
* \param c The character to consider.
* \retval 0 The character \a c is not a digit.
* \retval 1 The character \a c is a digit.
*/
static inline int isdigit(int c)
{
return (c >= '0') && (c <= '9');
}
/**
* \brief Determine whether or not the character \a c is a control
* character.
*
* \param c The character to consider.
* \retval 0 The character \a c is not a control character.
* \retval 1 The character \a c is a control character.
*/
static inline int iscntrl(int c)
{
return (c < 32) || (c >= 127);
}
/**
* \brief Determine whether or not the character \a c is a space.
*
* \note This implementation is very limited in that it doesn't
* consider a bunch of control characters that probably should be
* interpreted as space.
*
* \param c The character to consider.
* \retval 0 The character \a c is not a space.
* \retval 1 The character \a c is a space.
*/
static inline int isspace(int c)
{
return c == ' ';
}
/**
* \brief Get the containing object.
*
* \param ptr Pointer to the contained object.
* \param type Type of the containing object.
* \param member Member name of the contained object inside the
* containing object.
* \return Pointer to the containing object.
*/
#define container_of(ptr, type, member) \
((type *)((uintptr_t)(ptr) - offsetof(type, member)))
//! \name Minimum and Maximum
//@{
/**
* \brief Get the lowest of two signed values.
* \param a A signed integer
* \param b Another signed integer
* \return The numerically lowest value of \a a and \a b.
*/
#define min_s(a, b) \
((sizeof(a) == 1) && (sizeof(b) == 1) ? compiler_min_s8(a, b) \
: (sizeof(a) <= 2) && (sizeof(b) <= 2) ? compiler_min_s16(a, b) \
: (sizeof(a) <= 4) && (sizeof(b) <= 4) ? compiler_min_s32(a, b) \
: compiler_min_s64(a, b))
/**
* \brief Get the lowest of two unsigned values.
* \param a An unsigned integer
* \param b Another unsigned integer
* \return The numerically lowest value of \a a and \a b.
*/
#define min_u(a, b) \
((sizeof(a) == 1) && (sizeof(b) == 1) ? compiler_min_u8(a, b) \
: (sizeof(a) <= 2) && (sizeof(b) <= 2) ? compiler_min_u16(a, b) \
: (sizeof(a) <= 4) && (sizeof(b) <= 4) ? compiler_min_u32(a, b) \
: compiler_min_u64(a, b))
/**
* \brief Get the highest of two signed values.
* \param a A signed integer
* \param b Another signed integer
* \return The numerically highest value of \a a and \a b.
*/
#define max_s(a, b) \
((sizeof(a) == 1) && (sizeof(b) == 1) ? compiler_max_s8(a, b) \
: (sizeof(a) <= 2) && (sizeof(b) <= 2) ? compiler_max_s16(a, b) \
: (sizeof(a) <= 4) && (sizeof(b) <= 4) ? compiler_max_s32(a, b) \
: compiler_max_s64(a, b))
/**
* \brief Get the highest of two unsigned values.
* \param a An unsigned integer
* \param b Another unsigned integer
* \return The numerically highest value of \a a and \a b.
*/
#define max_u(a, b) \
((sizeof(a) == 1) && (sizeof(b) == 1) ? compiler_max_u8(a, b) \
: (sizeof(a) <= 2) && (sizeof(b) <= 2) ? compiler_max_u16(a, b) \
: (sizeof(a) <= 4) && (sizeof(b) <= 4) ? compiler_max_u32(a, b) \
: compiler_max_u64(a, b))
//@}
/**
* \internal
* Undefined function. Will cause a link failure if ilog2() is called
* with an invalid constant value.
*/
int_fast8_t ilog2_undefined(void);
/**
* \brief Calculate the base-2 logarithm of a number rounded down to
* the nearest integer.
*
* \param x A 32-bit value
* \return The base-2 logarithm of \a x, or -1 if \a x is 0.
*/
__always_inline static int_fast8_t ilog2(uint32_t x)
{
if (is_constant(x))
return ((x) & (1ULL << 31) ? 31 :
(x) & (1ULL << 30) ? 30 :
(x) & (1ULL << 29) ? 29 :
(x) & (1ULL << 28) ? 28 :
(x) & (1ULL << 27) ? 27 :
(x) & (1ULL << 26) ? 26 :
(x) & (1ULL << 25) ? 25 :
(x) & (1ULL << 24) ? 24 :
(x) & (1ULL << 23) ? 23 :
(x) & (1ULL << 22) ? 22 :
(x) & (1ULL << 21) ? 21 :
(x) & (1ULL << 20) ? 20 :
(x) & (1ULL << 19) ? 19 :
(x) & (1ULL << 18) ? 18 :
(x) & (1ULL << 17) ? 17 :
(x) & (1ULL << 16) ? 16 :
(x) & (1ULL << 15) ? 15 :
(x) & (1ULL << 14) ? 14 :
(x) & (1ULL << 13) ? 13 :
(x) & (1ULL << 12) ? 12 :
(x) & (1ULL << 11) ? 11 :
(x) & (1ULL << 10) ? 10 :
(x) & (1ULL << 9) ? 9 :
(x) & (1ULL << 8) ? 8 :
(x) & (1ULL << 7) ? 7 :
(x) & (1ULL << 6) ? 6 :
(x) & (1ULL << 5) ? 5 :
(x) & (1ULL << 4) ? 4 :
(x) & (1ULL << 3) ? 3 :
(x) & (1ULL << 2) ? 2 :
(x) & (1ULL << 1) ? 1 :
(x) & (1ULL << 0) ? 0 :
ilog2_undefined());
return 31 - compiler_clz(x);
}
/**
* \brief Test if a given value is a power of two.
*
* \param x The value to test
* \return true if \a x is a power of two, false otherwise
*/
__always_inline static bool is_power_of_two(unsigned long x)
{
return x && !(x & (x - 1));
}
ERROR_FUNC(priv_round_down_bad_type, "Invalid type passed to round_down");
/**
* \brief Round down to the nearest power of two boundary.
*
* \param x A positive integer
* \param order log2 of the required boundary.
* \return \a x rounded down to the nearest multiple of (1 << \a order)
*/
#define round_down(x, order) \
(sizeof(x) == 4 ? round_down32((uint32_t)(x), (order)) : \
sizeof(x) == 2 ? round_down16((uint16_t)(x), (order)) : \
sizeof(x) == 1 ? round_down8 (( uint8_t)(x), (order)) : \
(priv_round_down_bad_type(),1))
static inline uint8_t round_down8(uint8_t x, unsigned int order)
{
return (x & ~((1U << order) - 1));
}
static inline uint16_t round_down16(uint16_t x, unsigned int order)
{
return (x & ~((1U << order) - 1));
}
static inline uint32_t round_down32(uint32_t x, unsigned int order)
{
return (x & ~((1UL << order) - 1));
}
ERROR_FUNC(priv_round_up_bad_type, "Invalid type passed to round_up");
/**
* \brief Round up to the nearest power of two boundary.
*
* \param x A positive integer
* \param order log2 of the required boundary.
* \return \a x rounded up to the next multiple of (1 << \a order)
*/
#define round_up(x, order) \
(sizeof(x) == 4 ? round_up32((uint32_t)(x), (order)) : \
sizeof(x) == 2 ? round_up16((uint16_t)(x), (order)) : \
sizeof(x) == 1 ? round_up8 (( uint8_t)(x), (order)) : \
(priv_round_up_bad_type(),1))
static inline uint8_t round_up8(uint8_t x, unsigned int order)
{
return round_down8(x + (1U << order) - 1, order);
}
static inline uint16_t round_up16(uint16_t x, unsigned int order)
{
return round_down16(x + (1U << order) - 1, order);
}
static inline uint32_t round_up32(uint32_t x, unsigned int order)
{
return round_down32(x + (1UL << order) - 1, order);
}
/**
* \brief Round up to the nearest word-aligned boundary.
*
* \param x Address or offset to be word-aligned
* \return The smallest number \a y where \a y >= \a x and \a y & 3 == 0.
*/
static inline unsigned long word_align(unsigned long x)
{
return round_up(x, 2);
}
#ifdef CONFIG_PAGE_SIZE
/**
* Round up to the nearest multiple of #CONFIG_PAGE_SIZE.
*
* \param x Address or offset to be page aligned
* \return The smallest number \a y where \a y >= @a x and
* \a y % #CONFIG_PAGE_SIZE == 0.
*/
static inline unsigned long page_align(unsigned long x)
{
return (x + CONFIG_PAGE_SIZE - 1) & ~(CONFIG_PAGE_SIZE - 1);
}
#endif
/**
* \brief Calculate \f$ \left\lceil \frac{a}{b} \right\rceil \f$ using
* integer arithmetic.
*
* \param a An integer
* \param b Another integer
*
* \return (\a a / \a b) rounded up to the nearest integer.
*/
#define div_ceil(a, b) (((a) + (b) - 1) / (b))
//! @}
#endif /* UTIL_H_INCLUDED */
|
C | #include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
/*******************************************************************************
LINKED LIST
/* @desc: structure to handle the list of commands
* @params: key --> command name and params
* cmd --> argument 1
* data --> argument 2
*******************************************************************************/
struct node {
char *key;
char *data;
char *cmd;
struct node *next;
};
struct node *head = NULL;
struct node *current = NULL;
//display the list
void printList() {
struct node *ptr = head;
while (ptr != NULL) {
printf("%s,%s,%s\n", ptr->key, ptr->cmd, ptr->data);
ptr = ptr->next;
}
}
//insert link at the first location
void insertFirst(char *key, char *cmd, char *data) {
struct node *link = (struct node*) malloc(sizeof(struct node)); //create a link
link->key = malloc(strlen(key)+1);
link->cmd = malloc(strlen(cmd)+1);
link->data = malloc(strlen(data)+1);
strcpy(link->key,key);
strcpy(link->cmd,cmd);
strcpy(link->data,data);
link->next = head; //point it to old first node
head = link; //point first to new first node
}
//delete first item
struct node* deleteFirst() {
struct node *tempLink = head;
head = head->next; //mark next to first link as first
return tempLink; //return the deleted link
}
//is list empty
bool isEmpty() {
return head == NULL;
}
//return the length of the linked list
int listLength() {
int length = 0;
struct node *current;
for(current = head; current != NULL; current = current->next) {
length++;
}
return length;
}
//get first element
struct node* pop() {
struct node* current = head; //start from the first link
if(head == NULL) { //if list is empty
return NULL;
}
return current; //return the current Link (head)
}
void sort() {
int i, j, k;
struct node *current;
struct node *next;
char *tempKey;
char *tempData;
char *tempCmd;
int size = listLength();
k = size ;
for ( i = 0 ; i < size - 1 ; i++, k-- ) {
current = head;
next = head->next;
for ( j = 1 ; j < k ; j++ ) {
tempData = current->data;
current->data = next->data;
next->data = tempData;
tempKey = current->key;
current->key = next->key;
next->key = tempKey;
tempCmd = current->cmd;
current->cmd = next->cmd;
next->cmd = tempCmd;
current = current->next;
next = next->next;
}
}
}
/*------------------------------------------------------------------------------
UTILS
------------------------------------------------------------------------------*/
#define BUFFER_LENGTH 16384
#define HALF_BUFFER_LENGTH 8192
#define QUARTER_BUFFER_LENGTH 4096
#define SMALL_BUFFER_LENGTH 1024
#define MINI_BUFFER_LENGTH 128
//*********************************************************************************************************
/* @desc: check presence of prefix and suffix parameters
* @params: prefix -- string of text
* suffix -- string of text
* @return: false if prefix is initialized and suffix not. false if suffix is initializedand prefix not.
* true if prefix and suffix are both inizialized or both not.
*
**********************************************************************************************************/
bool checkPrefixSuffix(char prefix[HALF_BUFFER_LENGTH], char suffix[HALF_BUFFER_LENGTH]){
if ( prefix[0] == '\0' && suffix[0] == '\0'){
return true;
} else if ( prefix[0] != '\0' && suffix[0] != '\0' ) {
return true;
} else {
return false;
}
}
//******************************************************************************
/* @desc: counts occurrencies of a char or string in a string
* @params: prm -- full string of text
* sep -- separator string
* @return: int numer of occurrencies
*
*******************************************************************************/
int countParms (char * prm, char * sep) {
int count = 0;
const char *tmp = prm;
while(tmp = strstr(tmp, sep))
{
count++;
tmp++;
}
return count;
}
//*********************************************************************************************************************************************
/* @desc: add a command to the commands list.
* @params: incommand -- name of the command, it can provide his own params separated by commas. example {commandname,param1,param2}
* filename -- location of the command list text file on your computer.
**********************************************************************************************************************************************/
void addCmdToList(char *incommand, char *filename, char arg_firstpar[MINI_BUFFER_LENGTH], char prefix[MINI_BUFFER_LENGTH], char suffix[MINI_BUFFER_LENGTH]){
FILE * fp = fopen(filename, "r");
if (fp == NULL) {
printf("can't open file\n");
exit(-1);
}
char line[BUFFER_LENGTH], *tl, *tok, *partok, seps[] = "\t";
char command[BUFFER_LENGTH] = "";
char firstpar[QUARTER_BUFFER_LENGTH] = "";
char temp_firstpar[QUARTER_BUFFER_LENGTH] = "";
char scndpar[HALF_BUFFER_LENGTH] = "";
char temp_scndpar[HALF_BUFFER_LENGTH] = "";
char dest_scndpar[HALF_BUFFER_LENGTH] = "";
char default_scndpar[MINI_BUFFER_LENGTH] = "";
char * incommand_aux = malloc(strlen(incommand)+1);
char pref_aux[MINI_BUFFER_LENGTH] = "";
char suff_aux[MINI_BUFFER_LENGTH] = "";
int j = 1;
( prefix[0] == '\0') ? (strncpy(pref_aux,"data", MINI_BUFFER_LENGTH)) : (strncpy(pref_aux, prefix, MINI_BUFFER_LENGTH));
( suffix[0] == '\0') ? (strncpy(suff_aux,"timestamp", MINI_BUFFER_LENGTH)) : (strncpy(suff_aux, suffix, MINI_BUFFER_LENGTH));
sprintf(default_scndpar, "{\"%s\":{%s}, \"%s\":\"20170623105756\"}", pref_aux, "%s", suff_aux);
while ( (fgets(line,BUFFER_LENGTH,fp)) != NULL){
if(line[0] == '#'){continue;}
if(line[strlen(line)-1] == '\n'){
line[strlen(line)-1] = '\0';
}
strcpy(incommand_aux, incommand);
sscanf(line, "%s", command);
if (strncmp(incommand, command, strlen(command)) == 0 && strlen(command) == strlen(strtok(incommand_aux, ","))){
for (tl = strtok (line, seps); tl; tl = strtok (NULL,seps)){
if (j == 1) {strncpy(command, tl, QUARTER_BUFFER_LENGTH);}
if (j == 2) {strncpy(firstpar, tl, QUARTER_BUFFER_LENGTH);}
if (j == 3) {strncpy(scndpar, tl, HALF_BUFFER_LENGTH);}
j++;
}
if (strstr(firstpar, "%s")){
strncpy(temp_firstpar, firstpar, QUARTER_BUFFER_LENGTH);
sprintf(firstpar, temp_firstpar, arg_firstpar);
}
if (scndpar[0] == '\0'){
sprintf(scndpar, default_scndpar, "");
} else {
sprintf(temp_scndpar, default_scndpar, scndpar);
strncpy(scndpar, temp_scndpar, HALF_BUFFER_LENGTH);
}
int i,cp = 1;
int numPrmsIncommand = 0;
int numPrmsscndpar = 0;
numPrmsIncommand = countParms(incommand, ",");
numPrmsscndpar = countParms(scndpar , "%s");
if (countParms(incommand, ",") != countParms(scndpar , "%s")){
printf("Wrong number of params on command: %s\n", strtok(incommand, ","));
printf("needed: %d - given: %d\n", numPrmsscndpar, numPrmsIncommand);
fclose(fp);
exit(-1);
}else{
if (strstr(incommand, ",") != NULL ) {
int c = 0;
partok = strtok(incommand, ",");
partok = strtok(NULL, ",");
for (i = 0; i <= strlen(scndpar); i++) {
if (scndpar[i] != '\%'){
dest_scndpar[c] = scndpar[i];
c++;
} else {
if ((scndpar[i] == '\%') && (scndpar[i+1] == 's')){
strcat(dest_scndpar, partok);
c = c + strlen(partok);
partok = strtok(NULL, ",");
i++;
} else {
dest_scndpar[c] = scndpar[i];
c++;
}
}
}
strncpy(scndpar, dest_scndpar, HALF_BUFFER_LENGTH);
}
}
insertFirst(command, firstpar, scndpar);
pref_aux[0] = '\0';
suff_aux[0] = '\0';
fclose(fp);
return;
}
}
free(incommand_aux);
printf("Can't find: %s\n", incommand);
fclose(fp);
exit(-1);
}
//******************************************************************************
// @desc: show help on screen (opt -?)
//******************************************************************************
void printHelp() {
printf("____________________________________________________________________________________________________\n");
printf("-- The program sends mosquitto commands along with data stored in a tab-delimited command file --\n");
printf("Use: mosquitto_send [ARGUMENTS]\n");
printf(" -f FILENAME : change filename to FILENAME\n");
printf(" -c COMMAND NAME : search and execute given command/s\n");
printf(" -s SLEEPTIME : set given sleeptime between commands, default 0\n");
printf(" -h HOST : change default host mosquitto server to HOST\n");
printf(" -i ID : device ID, default 0, set it before a command to modify all the following commands\n" );
printf(" -a PREFIX : set the prefix parameter, dependency (-b), set it before a command to modify all the following commands \n");
printf(" -b SUFFIX : set the suffix parameter, dependency (-a), set it before a command to modify all the following commands \n");
printf(" -d : debug mode\n");
printf(" -m : show help\n");
printf("____________________________________________________________________________________________________\n");
exit(0);
}
//*********************************************************************************************************
/* @desc: check if the provided sleeptime is positive value, if not set 0. Then it prints out on screen.
* @params: int sleeptime (opt -s)
**********************************************************************************************************/
int checkSleepTime(int sleeptime) {
if (sleeptime < 0 ){
sleeptime = 0;
}
printf("sleeptime -->: %d\n", sleeptime);
return sleeptime;
}
/*------------------------------------------------------------------------------
MAIN
------------------------------------------------------------------------------*/
int main(int argc, char **argv){
char * filename = "mqtt_commands.txt";
char * optcmd = NULL;
char arg_firstpar[MINI_BUFFER_LENGTH] = "0";
char incmd[BUFFER_LENGTH] = "";
char strcmd[BUFFER_LENGTH];
char prefix[HALF_BUFFER_LENGTH] = "";
char suffix[HALF_BUFFER_LENGTH] = "";
int sleeptime = 0;
int opt;
int length = 0;
int r;
bool debug = false;
bool presuffix = true;
while ((opt = getopt(argc,argv,"?mdf:c:s:h:i:a:b:")) != -1) {
switch(opt) {
case '?':
printHelp();
break;
case 'm':
printHelp();
break;
case 'f':
filename = malloc(strlen(optarg)+1);
strcpy (filename, optarg);
printf("filename: %s\n", filename);
break;
case 'c':
strncpy (incmd, optarg, BUFFER_LENGTH);
addCmdToList(incmd,filename,arg_firstpar,prefix,suffix);
break;
case 's':
sleeptime = atoi(optarg);
break;
case 'h':
optcmd = malloc(strlen(optarg)+1);
strcpy(optcmd, optarg);
break;
case 'd':
debug = true;
break;
case 'i':
strncpy (arg_firstpar, optarg, MINI_BUFFER_LENGTH);
break;
case 'a':
strncpy (prefix, optarg, HALF_BUFFER_LENGTH);
break;
case 'b':
strncpy (suffix, optarg, HALF_BUFFER_LENGTH);
break;
default:
printHelp();
break;
}
}
if ( checkPrefixSuffix(prefix, suffix) != presuffix) {
printf("a and b params must be both set or unset\n");
exit(-1);
}
checkSleepTime(sleeptime);
sort();
length = listLength();
while (length > 0) {
struct node *thisNode = pop();
if (optcmd){
printf("mosquitto_pub -h '%s' -t '%s' -m '%s'\n", optcmd, thisNode->cmd, thisNode->data );
if (!debug) {
sprintf(strcmd, "mosquitto_pub -h '%s' -t '%s' -m '%s'", optcmd, thisNode->cmd, thisNode->data);
r = system(strcmd);
if (r != EXIT_SUCCESS) {
printf("command has failed with code %d\n", WEXITSTATUS(r));
exit(r);
}
}
}
else{
printf("mosquitto_pub -t '%s' -m '%s'\n", thisNode->cmd, thisNode->data);
if(!debug){
sprintf(strcmd, "mosquitto_pub -t '%s' -m '%s'", thisNode->cmd, thisNode->data);
r = system(strcmd);
if (r != EXIT_SUCCESS) {
printf("command has failed with code %d\n", WEXITSTATUS(r));
exit(r);
}
}
}
deleteFirst();
if (sleeptime != 0) {
if (!isEmpty()) {
printf("-- sleep %d seconds --\n", sleeptime);
sleep(sleeptime);
}
}
length--;
}
return 0;
}
|
C | // 6. Write a C program to read the value of an integer m and display the value of n is 1 when m is larger than 0,
// 0 when m is 0 and -1 when m is less than 0.
// Test Data: -5
// Expected Output:
// The value of n = -1
#include <stdio.h>
int main()
{
int m,n;
printf("Enter the value of m: ");
scanf("%d",&m);
if (m > 0)
{
n = 1;
}
else if (m < 0)
{
n = -1;
}
else
{
n = 0;
}
printf("n is %d\n",n);
} |
C | //http://www.patest.cn/contests/mooc-ds2015spring/03-树1
//题源:训练建树和遍历基本功
//题意:层次遍历输出叶子(list all the leaves in the order of top down, and left to right.)
//方法:所给数据parent、child关系明确,不需要动态确定关系,静态链表存储更优。
// 队列实现层次遍历:
// 1.Q.enque(root)
// 2.while(!Q.empty)
// r = Q.deque()
// visited(r)
// Q.enque(r.lchild)
// Q.enque(r.rchild)
//
//tips: C语言getchar()或scanf(%c)时回车处理让代码很丑陋
// 这里可以用gets(str)接收一行输入,str[0]、str[2]分别是左右子树
/*
Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
4 1 5
*/
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define N (10)
typedef struct BiTNode
{
int parent,lchild,rchild;
}BiTNode,BiTree[N];
void LevelTraversal(BiTree T)
{
int Q[N];
int r = 0, f = 0, e;
Q[r++] = GetRoot(T);
while(r != f)
{
e = Q[f++];
if(0 <= T[e].lchild)
Q[r++] = T[e].lchild;
if(0 <= T[e].rchild)
Q[r++] = T[e].rchild;
//is leaf
if(T[e].lchild < 0 && T[e].rchild < 0)
printf("%d%c",e,r!=f?' ':'\n');
}
}
void CreateBiTree(BiTree T)
{
int n;
//note: n <= 10
scanf("%d", &n),getchar();
for(int i = 0; i < n; i++)
{
char str[4] = {0};
gets(str);
if(isdigit(str[0]))
{
T[i].lchild = str[0] - '0';
T[str[0]-'0'].parent = i;
}
else{
T[i].lchild = -1;
}
if(isdigit(str[2]))
{
T[i].rchild = str[2] - '0';
T[str[2]-'0'].parent = i;
}
else{
T[i].rchild = -1;
}
}
}
int GetRoot(BiTree T)
{
int root = 0;
while(T[root].parent > 0)
root = T[root].parent;
return root;
}
int main()
{
BiTree T = {0};
CreateBiTree(T);
LevelTraversal(T);
return 0;
}
|
C | #include<string.h>
#include<stdio.h>
int main()
{
char *p;
int i;
p=strchr("This is my string",'m');
printf("%s\n",p);
char s[]="Is it not is so, why is like that is";
p=strtok(s,"is");
while(s!=NULL)
{
p=strtok(s,"is");
printf("%s\n",s);
}
}
|
C | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* Adopted from the public domain code in NaCl by djb. */
#include <string.h>
#include <stdio.h>
//#include "prtypes.h"
//#include "secport.h"
#include <stdint.h>
#include "chacha20.h"
#if defined(_MSC_VER)
#pragma intrinsic(_lrotl)
#define ROTL32(x, n) _lrotl(x, n)
#else
#define ROTL32(x, n) ((x << n) | (x >> ((8 * sizeof x) - n)))
#endif
#define ROTATE(v, c) ROTL32((v), (c))
#define U32TO8_LITTLE(p, v) \
{ (p)[0] = ((v) ) & 0xff; (p)[1] = ((v) >> 8) & 0xff; \
(p)[2] = ((v) >> 16) & 0xff; (p)[3] = ((v) >> 24) & 0xff; }
//#define U8TO32_LITTLE(p) \
// (((PRUint32)((p)[0]) ) | ((PRUint32)((p)[1]) << 8) | \
// ((PRUint32)((p)[2]) << 16) | ((PRUint32)((p)[3]) << 24))
#define U8TO32_LITTLE(p) \
(((uint32_t)((p)[0]) ) | ((uint32_t)((p)[1]) << 8) | \
((uint32_t)((p)[2]) << 16) | ((uint32_t)((p)[3]) << 24))
#define QUARTERROUND(x, a, b, c, d) \
x[a] = x[a] + x[b]; x[d] = ROTATE(x[d] ^ x[a], 16); \
x[c] = x[c] + x[d]; x[b] = ROTATE(x[b] ^ x[c], 12); \
x[a] = x[a] + x[b]; x[d] = ROTATE(x[d] ^ x[a], 8); \
x[c] = x[c] + x[d]; x[b] = ROTATE(x[b] ^ x[c], 7);
static void
//ChaChaCore(unsigned char output[64], const PRUint32 input[16], int num_rounds)
ChaChaCore(unsigned char output[64], const uint32_t input[16], int num_rounds)
{
//PRUint32 x[16];
uint32_t x[16];
int i;
//PORT_Memcpy(x, input, sizeof(PRUint32) * 16);
memcpy(x, input, sizeof(uint32_t) * 16);
for (i = num_rounds; i > 0; i -= 2) {
QUARTERROUND(x, 0, 4, 8, 12)
QUARTERROUND(x, 1, 5, 9, 13)
QUARTERROUND(x, 2, 6, 10, 14)
QUARTERROUND(x, 3, 7, 11, 15)
QUARTERROUND(x, 0, 5, 10, 15)
QUARTERROUND(x, 1, 6, 11, 12)
QUARTERROUND(x, 2, 7, 8, 13)
QUARTERROUND(x, 3, 4, 9, 14)
}
for (i = 0; i < 16; ++i) {
x[i] = x[i] + input[i];
}
for (i = 0; i < 16; ++i) {
U32TO8_LITTLE(output + 4 * i, x[i]);
}
}
static const unsigned char sigma[16] = "expand 32-byte k";
void
ChaCha20XOR(unsigned char *out, const unsigned char *in, unsigned int inLen,
const unsigned char key[32], const unsigned char nonce[12],
uint32_t counter)
{
unsigned char block[64];
//PRUint32 input[16];
uint32_t input[16];
unsigned int i;
input[4] = U8TO32_LITTLE(key + 0);
input[5] = U8TO32_LITTLE(key + 4);
input[6] = U8TO32_LITTLE(key + 8);
input[7] = U8TO32_LITTLE(key + 12);
input[8] = U8TO32_LITTLE(key + 16);
input[9] = U8TO32_LITTLE(key + 20);
input[10] = U8TO32_LITTLE(key + 24);
input[11] = U8TO32_LITTLE(key + 28);
input[0] = U8TO32_LITTLE(sigma + 0);
input[1] = U8TO32_LITTLE(sigma + 4);
input[2] = U8TO32_LITTLE(sigma + 8);
input[3] = U8TO32_LITTLE(sigma + 12);
input[12] = counter;
input[13] = U8TO32_LITTLE(nonce + 0);
input[14] = U8TO32_LITTLE(nonce + 4);
input[15] = U8TO32_LITTLE(nonce + 8);
while (inLen >= 64) {
ChaChaCore(block, input, 20);
for (i = 0; i < 64; i++) {
out[i] = in[i] ^ block[i];
}
input[12]++;
inLen -= 64;
in += 64;
out += 64;
}
if (inLen > 0) {
ChaChaCore(block, input, 20);
for (i = 0; i < inLen; i++) {
out[i] = in[i] ^ block[i];
}
}
}
|
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 dirent {int dummy; } ;
typedef int /*<<< orphan*/ DIR ;
/* Variables and functions */
int /*<<< orphan*/ ereport (int,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ errcode_for_file_access () ;
int /*<<< orphan*/ errmsg (char*,char const*) ;
scalar_t__ errno ;
struct dirent* readdir (int /*<<< orphan*/ *) ;
struct dirent *
ReadDirExtended(DIR *dir, const char *dirname, int elevel)
{
struct dirent *dent;
/* Give a generic message for AllocateDir failure, if caller didn't */
if (dir == NULL)
{
ereport(elevel,
(errcode_for_file_access(),
errmsg("could not open directory \"%s\": %m",
dirname)));
return NULL;
}
errno = 0;
if ((dent = readdir(dir)) != NULL)
return dent;
if (errno)
ereport(elevel,
(errcode_for_file_access(),
errmsg("could not read directory \"%s\": %m",
dirname)));
return NULL;
} |
C | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <algorithm>
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;
typedef long long int LL;
const int MAXN = 0x7fffffff;
const int MINN = -0x7fffffff;
const double eps = 1e-9;
const int dir[8][2] = {{0,1},{1,0},{0,-1},{-1,0},{-1,1},
{1,1},{1,-1},{-1,-1}};
const int MAX = 10;
char m[MAX][MAX];int cnt, n, k, sum;
bool p[MAX];
bool judge(int i, int j) {
if (p[j] == false && m[i][j] == '#') return true;
else return false;
}
void dfs(int x) {
if (sum == k) {cnt++; return;}
if (x >= n) return;
int i;
for (i = 0; i < n; ++i) {
if (judge(x, i)) {
p[i] = true; sum++; dfs(x+1);
p[i] = false; sum--;
}
}
dfs(x + 1);
}
int main(void){
#ifndef ONLINE_JUDGE
freopen("poj1321.in", "r", stdin);
#endif
while (~scanf("%d%d", &n, &k)) {
int i, j;
if (k == -1 && n == -1) break;
//getchar();
for (i = 0; i <n ; ++i) {
for (j = 0; j < n; ++j) {
//scanf("%c", &m[i][j]);
cin>>m[i][j];
}
//getchar();
}
cnt = 0;
memset(p, false, sizeof(p));
sum = 0;
dfs(0);
printf("%d\n", cnt);
}
return 0;
} |
C | /** @file say_hello.c
* Simple test application to read and write to the character device /dev/khello. Used for testing with the khello kernel module.
*
* Usage:
* After loading the kernel module.
* To read from the device: "./say_hello read"
* To write to the device: ./say_hello write something"
*
*/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#define DEVICE "/dev/khello" /**< The character device. */
/** Check the arguments on the command line.
* @param p_num Number of arguments
* @param p_args List of arguments
* @return 0 if arguments are OK. Else -1.
*/
static int check_args(const int p_num, char *p_args[]);
/** Process the value set in erno.
* @param The errno itself.
*/
static void process_errnum(const int p_errnum);
/** Perform a read operation on the device.
*/
static void do_read();
/** Performs a write operation on the device.
* @param p_msg Message to write. Only the 1st 32 bytes will be writen to the device. The device also replaces the last byte in its 32-byte buffer with a '0'.
*/
static void do_write(const char *const p_msg);
int main(int argc, char *argv[])
{
int operation; /* Operation to execute. 1=read. 2=write. */
/* Check input arguments and decide on operation to carry out. */
if((operation = check_args(argc, argv)) == -1) {
printf("Incorrect args. Abort.\n");
return 0;
}
switch(operation) {
case 1:
do_read();
break;
case 2:
do_write(argv[2]);
break;
default:
break;
}
return 0;
}
static int check_args(const int p_num, char *p_args[])
{
if(p_num < 2)
return -1;
if(strcmp(p_args[1], "read")==0)
return 1;
if((strcmp(p_args[1], "write")==0) && (p_num >= 3))
return 2;
return -1;
}
static void do_read()
{
int count, fd = -1;
unsigned char buf[32];
if((fd = open(DEVICE, O_RDONLY)) == -1) {
process_errnum(errno);
return;
}
if((count = read(fd, buf, 32)) != -1) {
buf[count -1] = 0;
printf("READ from %s: %s\n", DEVICE, buf);
} else
process_errnum(errno);
close(fd);
}
static void do_write(const char *const p_msg)
{
int count, fd = -1;
if((count = strlen(p_msg)) > 32)
count = 32;
if((fd = open(DEVICE, O_WRONLY)) == -1) {
process_errnum(errno);
return;
}
if(write(fd, p_msg, count) != -1)
printf("WRITE to %s: %s\n", DEVICE, p_msg);
else
process_errnum(errno);
close(fd);
}
static void process_errnum(const int p_errnum)
{
printf("%s\n", strerror(p_errnum));
}
|
C | #include <stdio.h>
void f3();
int main(int argc, char const *argv[])
{
void f2();
void f1();
int n = 8;
f1();
f2();
return 0;
}
void f1()
{
printf("f1\n");
f3(4);
}
void f2()
{
//f3(3);
printf("f2\n");
}
void f3(int a){
printf("f3%d\n",a);
} |
C |
struct dlnode
{
int info;
struct dlnode *rlink;
struct dlnode *llink;
};
typedef struct dlnode *DLNODE;
static int dlcount = 0;
DLNODE head;
void dldrawstring(float x, float y, char *string)
{
char *c;
glRasterPos2f(x, y);
for(c = string; *c != '\0'; c++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, *c);
}
}
DLNODE dlgetnode()
{
DLNODE temp;
temp = (DLNODE)malloc(sizeof(struct dlnode));
if(temp == NULL)
{
printf("Out of memory\n");
exit(1);
}
return temp;
}
void dldisp()
{
glColor3f(1.0, 1.0, 1.0);
char c[] = "List is Empty";
glRasterPos2f(820.0, 200.0);
for(int i = 0; c[i] != '\0'; i++)
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, c[i]);
glFlush();
}
DLNODE dldisplay(DLNODE head)
{
DLNODE temp;
int i = 0, k, j = 0;
temp = head->rlink;
glClearColor(0.752941, 0.752941, 0.752941, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0);
dldrawstring(680.0, 360.0, "DOUBLY LINKED LIST");
dldrawstring(680.0, 330.0, "*********************");
if(temp == head)
{
dldisp();
return head;
}
int data ;
while(temp != head)
{
for(k = 0; k < dlcount; k++)
{
GLfloat x1 = 100, x2 = 150, x3 = 350, x4 = 400, x5 = 500, x6 = 480, x7 = 20, x9 = 0;
data = temp->info;
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_POLYGON);
glVertex2i(x2 + k * 400, 200);
glVertex2i(x2 + k * 400, 225);
glVertex2i(x3 + k * 400, 225);
glVertex2i(x3 + k * 400, 200);
glEnd();
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_POLYGON);
glVertex2i(x3 + k * 400, 225);
glVertex2i(x3 + k * 400, 200);
glVertex2i(x4 + k * 400, 200);
glVertex2i(x4 + k * 400, 225);
glEnd();
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_POLYGON);
glVertex2i(x1 + k * 400, 225);
glVertex2i(x1 + k * 400, 200);
glVertex2i(x2 + k * 400, 200);
glVertex2i(x2 + k * 400, 225);
glEnd();
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex2i(x1 + k * 400, 207);
glVertex2i(x9 + k * 400, 207);
glVertex2i(x9 + k * 400, 207);
glVertex2i(x7 + k * 400, 202);
glVertex2i(x9 + k * 400, 207);
glVertex2i(x7 + k * 400, 210);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex2i(x4 + k * 400, 215);
glVertex2i(x5 + k * 400, 215);
glVertex2i(x5 + k * 400, 215);
glVertex2i(x6 + k * 400, 210);
glVertex2i(x5 + k * 400, 215);
glVertex2i(x6 + k * 400, 219);
glEnd();
glColor3f(0.0, 0.0, 0.0);
char data_string[10];
to_string(data_string, data);
int x8 = 225;
glColor3f(1.0, 1.0, 1.0);
dldrawstring(x8 + k * 400, 210, data_string);
temp = temp->rlink;
glFlush();
}
}
return head;
}
DLNODE insertfront(DLNODE head, int item)
{
DLNODE temp, cur;
temp = dlgetnode();
temp->info = item;
cur = head->rlink;
head->rlink = temp;
temp->llink = head;
temp->rlink = cur;
cur->llink = temp;
return head;
}
DLNODE insertrear(DLNODE head, int item)
{
DLNODE temp, cur;
temp = dlgetnode();
temp->info = item;
cur = head->llink;
head->llink = temp;
temp->rlink = head;
temp->llink = cur;
cur->rlink = temp;
return head;
}
DLNODE insertleft(DLNODE head, int ele)
{
int item;
DLNODE temp, cur, pre;
if(head->rlink == head)
{
printf("List is empty :- \n");
dlcount--;
return head;
}
cur = head->rlink;
while(cur != head)
{
if(cur->info == ele)
break;
cur = cur->rlink;
}
if(cur == head)
{
printf("%d Element not found\n", ele);
dlcount--;
return head;
}
printf("Enter element to be inserted :- \n");
scanf("%d", &item);
pre = cur->llink;
temp = dlgetnode();
temp->info = item;
temp->llink = pre;
temp->rlink = cur;
cur->llink = temp;
pre->rlink = temp;
return head;
}
DLNODE insertright(DLNODE head, int ele)
{
int item;
glClear(GL_COLOR_BUFFER_BIT);
DLNODE temp, cur, next;
if(head->rlink == head)
{
printf("List is empty\n");
dlcount--;
return head;
}
cur = head->rlink;
while(cur != head)
{
if(cur->info == ele)
{
printf("Enter element to be inserted :- \n");
scanf("%d", &item);
next = cur->rlink;
temp = dlgetnode();
temp->info = item;
temp->llink = cur;
temp->rlink = next;
cur->rlink = temp;
next->llink = temp;
return head;
}
cur = cur->rlink;
}
printf("%d Element not found\n", ele);
dlcount--;
return head;
}
DLNODE deletfront(DLNODE head)
{
DLNODE cur, next;
if(head->rlink == head)
{
printf("List is empty\n");
dlcount++;
return head;
}
cur = head->rlink;
next = cur->rlink;
head->rlink = next;
next->llink = head;
printf("Node to be deleted is = %d\n", cur->info);
free(cur);
return head;
}
DLNODE deletrear(DLNODE head)
{
DLNODE cur, prev;
if(head->llink == head)
{
printf("List is empty\n");
dlcount++;
return head;
}
cur = head->llink;
prev = cur->llink;
head->llink = prev;
prev->rlink = head;
printf("Node to b deleted is = %d\n", cur->info);
free(cur);
return head;
}
DLNODE del(DLNODE head, int ele)
{
DLNODE cur, next, pre;
glClear(GL_COLOR_BUFFER_BIT);
if(head->rlink == head)
{
printf("List is empty\n");
dlcount++;
return head;
}
cur = head->rlink;
while(cur != head)
{
if(cur->info == ele)
break;
cur = cur->rlink;
}
if(cur == head)
{
printf("%d Element not found\n", ele);
dlcount++;
return head;
}
pre = cur->llink;
next = cur->rlink;
printf("%d Element found and deleted\n", ele);
pre->rlink = next;
next->llink = pre;
free(cur);
return head;
}
void renderscenedl()
{
glClear(GL_COLOR_BUFFER_BIT);
dldisplay(head);
glFlush();
}
void dlinit()
{
glClearColor(0.752941, 0.752941, 0.752941, 1.0);
glColor3f(0.0f, 0.0f, 0.0f);
glPointSize(0.8);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 2000.0, 0.0, 400.0);
}
void dlmenu(int option)
{
int ele;
switch(option)
{
case 1:
printf("Enter item to be inserted :- \n");
scanf("%d", &ele);
head = insertfront(head, ele);
dlcount++;
dldisplay(head);
break;
case 2:
printf("Enter item to be inserted :- \n");
scanf("%d", &ele);
head = insertrear(head, ele);
dlcount++;
dldisplay(head);
break;
case 3:
printf("Enter key to be searched :- \n");
scanf("%d", &ele);
head = insertleft(head, ele);
dlcount++;
dldisplay(head);
break;
case 4:
printf("Enter key to be searched :- \n");
scanf("%d", &ele);
head = insertright(head, ele);
dlcount++;
dldisplay(head);
break;
case 5:
head = deletfront(head);
dlcount--;
dldisplay(head);
break;
case 6:
head = deletrear(head);
dlcount--;
dldisplay(head);
break;
case 7:
printf("Enter key :- \n");
scanf("%d", &ele);
dlcount--;
head = del(head, ele);
dldisplay(head);
break;
case 8:
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
glutLeaveMainLoop();
}
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* region_manager.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jwalsh <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/06/11 15:53:29 by jwalsh #+# #+# */
/* Updated: 2018/07/09 15:41:36 by jwalsh ### ########.fr */
/* */
/* ************************************************************************** */
#include "malloc.h"
/*
** Returns the region list corresponding to allocation size request
*/
t_region *get_first_region(size_t size)
{
if (size <= TINY_LIMIT)
return (&g_lists.tiny);
if (size <= SMALL_LIMIT)
return (&g_lists.small);
return (&g_lists.large);
}
/*
** Returns the mininum map size depending on size to allocated
*/
size_t get_region_min_map_size(size_t size)
{
size_t page_size;
size_t page_count;
if (size <= TINY_LIMIT)
return (TINY_MIN_MAP_SIZE);
else if (size <= SMALL_LIMIT)
return (SMALL_MIN_MAP_SIZE);
else
{
page_size = getpagesize();
page_count = (size + REGION_HEADER_SIZE) / page_size + 1;
return (page_count * page_size);
}
}
t_region get_new_region(size_t size)
{
t_region region;
size_t final_size;
region = NULL;
size = size + BLOCK_HEADER_SIZE;
if (size <= BLOCK_HEADER_SIZE)
return (NULL);
final_size = get_region_min_map_size(size);
region = mmap(0, final_size, PROT_READ | PROT_WRITE,
MAP_ANON | MAP_PRIVATE, -1, 0);
if (region == MAP_FAILED)
{
print_mmap_error();
errno = ENOMEM;
return (NULL);
}
region->size = final_size;
region->next = NULL;
region->last_block = NULL;
region->after_last_block = (t_block)(®ion->content);
region->content = 0;
return (region);
}
int region_has_space(t_region region, size_t size)
{
if (get_size_of_free_space_at_end_of_region(region) >= size +
BLOCK_HEADER_SIZE)
return (1);
else
return (0);
}
t_region get_region_head(size_t size)
{
t_region *head;
head = get_first_region(size);
if (!*head)
*head = get_new_region(size);
return (*head);
}
|
C | #include <stdio.h>
int main(void)
{
int a;
printf("number? ");
scanf("%d",&a);
if (a==1)
{
printf("Sunday\n");
}
else if (a==2)
{
printf("Monday\n");
}
else if (a==3)
{
printf("Tuesday\n");
}
else if (a==4)
{
printf("Wednesday\n");
}
else if (a==5)
{
printf("Thursday\n");
}
else if (a==6)
{
printf("Friday\n");
}
else if (a==7)
{
printf("Saturday\n");
}
else
{
printf("wrong input\n");
}
return 0;
}
|
C | //Libraries including
#include <stdio.h>
void main (){
//Printing information
printf("I'm Amir Shetaia\n"
"\nMy birthdate is 1 Oct 2001\n"
"\nI Study at Faculty of Engineering\n"
"\nMansoura University 2024\n"
"\nMy E-mail is \"[email protected]\"");
} |
C | #include<stdio.h>
#include<stdlib.h>
#define N 10
struct date
{
int year;
int month;
int day;
};
struct appliance
{
char unitname[20];
char telephone[11];
};
struct food
{
struct date a;
};
struct goods
{
char num[20];
char name[20];
struct date b;
int money;
int quantity;
char kind;
union
{
struct appliance app;
struct food fo;
}type;
};
int main (void)
{
int i,j,n;
struct goods go[N];
printf("please input the number of good:\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("please input number and name:\n");
scanf("%s %s",go[i].num,go[i].name);
printf("plesse input indate:\n");
scanf(" %d %d %d",&go[i].b.year,&go[i].b.month,&go[i].b.day);
printf("please input money and quantity:\n");
scanf(" %d %d",&go[i].money,&go[i].quantity);
printf("please input the kind of goods:\n");
scanf(" %c",&go[i].kind);
if(go[i].kind=='a'||go[i].kind=='A')
{
printf("please input unitname and telephone:\n");
scanf(" %s %s",go[i].type.app.unitname,go[i].type.app.telephone);
}
else if(go[i].kind=='f'||go[i].kind=='F')
{
printf("please input date guarantee:\n");
scanf(" %d %d %d",&go[i].type.fo.a.year,&go[i].type.fo.a.month,&go[i].type.fo.a.day);
}
else
printf("input error!\n");
}
printf("*****************************information******************************\n");
for(i=0;i<n;i++)
{
printf("NO.%s\t%s",go[i].num,go[i].name);
printf("\t%d-%d-%d",go[i].b.year,go[i].b.month,go[i].b.day);
printf("\t%d\t%d",go[i].money,go[i].quantity);
if(go[i].kind=='a'||go[i].kind=='A')
printf("\t%s\t%s",go[i].type.app.unitname,go[i].type.app.telephone);
else if(go[i].kind=='f'||go[i].kind=='F')
printf("\t%d-%d-%d",go[i].type.fo.a.year,go[i].type.fo.a.month,go[i].type.fo.a.day);
printf("\n");
}
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* handle_left_just.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pluu <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/07 15:56:49 by pluu #+# #+# */
/* Updated: 2017/05/07 15:56:51 by pluu ### ########.fr */
/* */
/* ************************************************************************** */
#include "../incs/ft_printf.h"
static int handle_left_prefix(t_arg **ainfo, t_data **aout)
{
(*aout)->flag = find_flag(ainfo, aout);
if ((*aout)->flag)
{
if ((*aout)->flag == 'x' || (*aout)->flag == 'X')
{
*(*aout)->presult++ = '0';
*(*aout)->presult++ = (*aout)->flag;
return (2);
}
else if (!is_hash_flag(ainfo) || (is_hash_flag(ainfo)
&& (*ainfo)->precis <= 1))
{
*(*aout)->presult++ = (*aout)->flag;
return (1);
}
}
return (0);
}
static int handle_left_precis(t_arg **ainfo, t_data **aout, char c)
{
int precis;
precis = 0;
if ((*ainfo)->precis > (*aout)->len && ((*ainfo)->spec == 'd' ||
(*ainfo)->spec == 'i' || (*ainfo)->spec == 'o' ||
(*ainfo)->spec == 'O' || (*ainfo)->spec == 'u' ||
(*ainfo)->spec == 'U' || (*ainfo)->spec == 'x' ||
(*ainfo)->spec == 'X' || (*ainfo)->spec == 'D'))
{
precis = (*ainfo)->precis - (*aout)->len;
ft_memset((*aout)->presult, c, precis);
(*aout)->presult += precis;
}
return (precis);
}
void handle_left_just(t_arg **ainfo, t_data **aout, char c)
{
int i;
int j;
int k;
if ((*ainfo)->precis != -1 && (*ainfo)->precis != 0 &&
(*ainfo)->precis < (*aout)->len && ((*ainfo)->spec == 's' ||
(*ainfo)->spec == 'd' || (*ainfo)->spec == 'i'))
i = (*ainfo)->precis;
else if ((*ainfo)->precis == 0 && (*ainfo)->precis < (*aout)->len &&
ft_strcmp((*aout)->s_arg, "0") == 0 &&
(((!is_hash_flag(ainfo) && ((*ainfo)->spec == 'o' ||
(*ainfo)->spec == 'u' || (*ainfo)->spec == 'U')))
|| (*ainfo)->spec == 'x' || (*ainfo)->spec == 'X'))
i = 0;
else
i = (*aout)->len;
j = handle_left_prefix(ainfo, aout);
k = handle_left_precis(ainfo, aout, c);
ft_memcpy((*aout)->presult, (*aout)->s_arg, i);
if (k)
ft_memset((*aout)->presult + i, ' ', (*aout)->width - i - j - k);
else
ft_memset(((*aout)->presult) + i, c, (*aout)->width - i - j);
}
|
C | #ifndef _COMPASSCAL_LIB
#define _COMPASSCAL_LIB
#ifdef __cplusplus
extern "C" {
#endif
/* standard calling convention under Win32 is __stdcall */
#if defined(_WIN32)
#define COMPASSCAL_API __stdcall
#else
#define COMPASSCAL_API
#endif
/**
* Progress report callback funtion. Most of these variables won't concern the user.
*
* @param userPtr The user data sent for lbfgs() function by the client.
* @param x The current values of the calibration parameters. This is a 2x2 or 3x3 matrix followed by 2 or 3 offsets.
* @param g The current gradient values of the calibration parameters.
* @param fx The current value of the objective function.
* @param xnorm The Euclidean norm of the calibration parameters.
* @param gnorm The Euclidean norm of the gradients.
* @param step The line-search step used for this iteration.
* @param n The number of variables.
* @param k The iteration count.
* @param ls The number of evaluations called for this iteration.
* @retval int Zero to continue the optimization process. Returning a
* non-zero value will cancel the optimization process.
*/
typedef int (COMPASSCAL_API *progress_t)(
void *userPtr,
const double *x,
const double *g,
const double fx,
const double xnorm,
const double gnorm,
const double step,
int n,
int k,
int ls
);
/**
* Calculates compass correction parameters in 3 dimensions. Input data should represenst as much of the ellipsoid as possible.
* @param sData An array of sets of compass data in the form {axis0,axis1,axis2}
* @param cDataCount The number of elements in cData
* @param progress A function callback for progress updates, can be NULL
* @param args The compass correction arguments; in order: magField, offset0-1-2, gain0-1-2, T0-1-2-3-4-5
* @param userPtr A user defined pointer that gets returned in the progress callback, can be NULL
*/
int COMPASSCAL_API getCompassArgs_3D(double cData[][3], int cDataCount, progress_t progress, double args[13], void *userPtr);
/**
* Calculates compass correction parameters in 2 dimensions.
* Input data should represenst a level circle rotated about the axis of gravity in the x-y (axis 0 and 1) plane.
* This calibration will set the magnetic field in axis 2 to 0.
* @param sData An array of sets of compass data in the form {axis0,axis1}
* @param cDataCount The number of elements in cData
* @param progress A function callback for progress updates, can be NULL
* @param args The compass correction arguments; in order: magField, offset0-1-2, gain0-1-2, T0-1-2-3-4-5
* @param userPtr A user defined pointer that gets returned in the progress callback, can be NULL
*/
int COMPASSCAL_API getCompassArgs_2D_ver1(double cData[][2], int cDataCount, progress_t progress, double args[13], void *userPtr);
/**
* Calculates compass correction parameters for 3 dimentions, using 2 dimentional data.
* Input data should represenst a level circle rotated about the axis of gravity in the x-y (axis 0 and 1) plane.
* This calibration will set the axis 2 gain to the average of axis0 and axis1, but axis 2 will still have offset errors.
* @param sData An array of sets of compass data in the form {axis0,axis1,axis2}
* @param cDataCount The number of elements in cData
* @param progress A function callback for progress updates, can be NULL
* @param args The compass correction arguments; in order: magField, offset0-1-2, gain0-1-2, T0-1-2-3-4-5
* @param userPtr A user defined pointer that gets returned in the progress callback, can be NULL
*/
int COMPASSCAL_API getCompassArgs_2D_ver2(double cData[][3], int cDataCount, progress_t progress, double args[13], void *userPtr);
#ifdef __cplusplus
}
#endif
#endif
|
C | #include<stdio.h>
void main(){
int i,size=5,item,pos,a[10],j;
printf("enter the elements: ");
for(i=0;i<size;i++){
scanf("%d",&a[i]);
}
printf("enter the item to insert");
scanf("%d",&item);
printf("enter the postion to insert");
scanf("%d",&pos);
size++;
for(j=size;j>=pos;j--){
a[j]=a[j-1];
}
a[j]=item;
printf("after inserting the array is : ");
for(i=0;i<size;i++){
printf("|%d|",a[i]);
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <cjson/cJSON.h>
#include <curl/curl.h>
#include <dirent.h>
#include <errno.h>
#include "header.h"
#include "functions.c"
int main(int argc, char *argv[] ){
int count, i;
count = 360;
int numOfFiles, oldNumOfFiles = 0;
char * fistPart = "find ";
char * seconPart = " -type f | wc -l";
char path[400];
char urlSlack[300];
char icon[100];
char channel[100];
char username[50];
char passwordSQL[100];
get_and_test_path(path);
printf("\n");
get_and_test_url(urlSlack);
printf("\n");
get_and_test_icon(icon);
printf("\n");
get_and_test_channel(channel);
printf("\n");
get_and_test_user_name(username);
printf("\n\n\n-------Commande enregistrée-------\n\n");
char * fullCommand;
size_t fullSize = strlen( fistPart ) + 1 + strlen( path ) + 1 + strlen(seconPart) + 1;
fullCommand = (char *) malloc( fullSize );
strcpy( fullCommand, fistPart );
strcat( fullCommand, path);
strcat( fullCommand, seconPart );
int pid = fork();
if (pid < 0){
perror("Echec lors du clonage.");
exit(-1);
}
else if (pid > 0){
printf("Service lancé sur le PID : %d \n", pid);
exit(0);
}
while(i != count){
i++;
sleep(1);
printf("%s", fullCommand);
FILE *fp = popen(fullCommand, "r");
fscanf(fp, "%d", &numOfFiles);
pclose(fp);
if((numOfFiles > oldNumOfFiles) && (oldNumOfFiles == 0)){
struct Slack slack;
slack.url = urlSlack;
slack.text = malloc(MAX);
slack.channel = channel;
slack.icon = icon;
slack.username = username;
slack.text = malloc(MAX * sizeof(char));
char buffer[150];
int a = numOfFiles;
sprintf(buffer, "il y a %d fichiers - première entrée", a);
strcpy(slack.text, buffer);
slack_communication(slack);
oldNumOfFiles = numOfFiles;
//lecture BDD
sleep(1);
}
else if(numOfFiles < oldNumOfFiles){
struct Slack slack;
slack.url = urlSlack;
slack.text = malloc(MAX);
slack.channel = channel;
slack.icon = icon;
slack.username = username;
slack.text = malloc(MAX * sizeof(char));
char buffer[150];
int a = numOfFiles;
sprintf(buffer, "il y a %d fichiers - Un fichier a été supprimé", a);
strcpy(slack.text, buffer);
slack_communication(slack);
oldNumOfFiles = numOfFiles;
sleep(1);
}
else if(numOfFiles > oldNumOfFiles){
struct Slack slack;
slack.url = urlSlack;
slack.text = malloc(MAX);
slack.channel = channel;
slack.icon = icon;
slack.username = username;
slack.text = malloc(MAX * sizeof(char));
char buffer[150];
int a = numOfFiles;
sprintf(buffer, "il y a %d fichiers - Un fichier a été ajouté. ", a);
strcpy(slack.text, buffer);
slack_communication(slack);
oldNumOfFiles = numOfFiles;
//Lecture BDD pour AHB
sleep(1);
}
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main()
{
char answer[4] = {0};
char guess[4] = {0};
// make answer
srand(time(NULL));
snprintf(answer, 4, "%03d", rand() % 1000);
printf("answer: %s\n", answer);
// guess
printf("input: ");
scanf("%03s", guess);
// decision
int i, j;
int strikes = 0, balls = 0;
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
if(answer[i] == guess[j]) {
if(i == j) {
strikes++;
}
else {
balls++;
}
}
}
}
// output
printf("[guess:%03s] [answer:%s] %d strikes, %d balls\n",
guess, answer, strikes, balls);
return 0;
}
|
C | #include <stdio.h>
int main ()
{
int cont, inicial;
unsigned long int nro;
printf("Ingrese un numero entero positivo. Determinaremos su factorial.\n");
scanf("%d",&nro);
while(nro<0){
printf("Ingrese un numero correcto.\n");
scanf("%d",&nro);
}
cont=nro, inicial=nro;
cont=cont-1;
while(cont!=0){
nro=(nro)*(cont);
cont--;
}
printf("El factorial de %d es %i",inicial, nro);
return 0;
}
|
C | #include "holberton.h"
/**
* add - The primary function being carried out
* @a: the first character in formula
* @b: the second character in formula
* Description: Parses 'a' and 'b' and returns 'val'
* a blank line
* Return: returns @val
*/
int add(int a, int b)
{
int val;
val = (a + b);
return (val);
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<math.h>
void sort(int *arr,int num)
{
int i,temp,j;
for(i=0;i<num-1;i++)
{
for(j=i;j<num-1;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
int leastcost(int *arr,int num)
{
int i,j,k,cost,counter,counter1=0;
counter=ceil(num/2);
for(i=0;i<counter;i++)
{
k=0;
for(j=0;j<4;j++)
{
if(k<2)
{
cost=cost + arr[j+counter1];
}
k++;
}
counter1=counter1+4;
}
return cost;
}
int main(void)
{
int t,n,k,i,j,*a,*p;
scanf("%d",&t);
if(t>=1 && t<=1000)
{
for(i=0;i<t;i++)
{
scanf("%d",&n);
if(n>=1 && n<=1000)
{
a=malloc(n*sizeof(int));
p=malloc(t*sizeof(int));
for(j=0;j<n;j++)
{
scanf("%d",&a[j]);
}
sort(a,n);
p[i]=leastcost(a,n);
}
}
}
for(i=0;i<t;i++)
{
printf("%d\n",p[i]);
}
return 0;
}
|
C | #include<stdio.h>
//#include<conio.h>
struct data
{
int rollno;
char name[20];
int age;
int per;
};
void create(struct data d[10], int i)
{
printf("\nStudent No.: %d\n",i+1);
printf("Enter Roll No: ");
scanf("%d",&d[i].rollno);
printf("Enter Name: ");
scanf("%s",d[i].name);
printf("Enter Age: ");
scanf("%d",&d[i].age);
printf("Enter Percentage: ");
scanf("%d",&d[i].per);
}
void display(struct data d[10],int i)
{
printf("%d\t\t%s\t%d\t%d\n",d[i].rollno,d[i].name,d[i].age,d[i].per);
}
void add(struct data d[4],int c)
{
printf("\nAdd the datails\n");
printf("\nStudent No.: %d\n",c);
printf("Enter Roll No: ");
scanf("%d",&d[c-1].rollno);
printf("Enter Name: ");
scanf("%s",d[c-1].name);
printf("Enter Age: ");
scanf("%d",&d[c-1].age);
printf("Enter Percentage: ");
scanf("%d",&d[c-1].per);
}
void search(struct data d[10],int r,int entry)
{
int i,flag=0;
for(i=0;i<entry;i++)
{
if(r==d[i].rollno)
{
printf("\nSerach Found\n");
printf("Roll No.\tName\tAge\tPercent\n");
printf("%d\t\t%s\t%d\t%d\n",d[i].rollno,d[i].name,d[i].age,d[i].per);
flag=1;
}
}
if(flag==0)
printf("Search Not Found\n");
}
void modify(struct data d[10],int r, int entry)
{
int i,flag=0;
for(i=0;i<entry;i++)
{
if(r==d[i].rollno)
{
printf("\nStudent No.: %d\n",i+1);
printf("Enter Roll No: ");
scanf("%d",&d[i].rollno);
printf("Enter Name: ");
scanf("%s",d[i].name);
printf("Enter Age: ");
scanf("%d",&d[i].age);
printf("Enter Percentage: ");
scanf("%d",&d[i].per);
flag=1;
}
}
if(flag==0)
printf("Roll No. Not Found\n");
}
int delete(struct data d[10],int r,int entry)
{
int i,flag=0,str;
for(i=0;i<entry;i++)
{
if(r==d[i].rollno)
{
str=i;
flag=1;
break;
}
}
if(flag==1)
{
printf("Record is deleted\n");
entry--;
for(i=str;i<entry;i++)
{
d[i]=d[i+1];
}
}
else
printf("Record can not be deelted given roll no. not found\n");
return entry;
}
void main()
{
struct data d[100];
int choice,i,count=0,entry=0,ser;
do
{
printf("\n1.Insert Data\n2.Display Data\n3.Add Data\n4.Search a Record\n5.Modify a Record\n6.Delete a Record\n");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter the number of entries\n");
scanf("%d",&entry);
for(i=0;i<entry;i++)
{
create(d,i);
count++;
}
break;
case 2: printf("Roll No.\tName\tAge\tPercent\n");
for(i=0;i<entry;i++)
{
display(d,i);
}
break;
case 3: add(d,count+1);
entry++;
count++;
break;
case 4:printf("\nEnter a roll no. to be searched\n");
scanf("%d",&ser);
search(d,ser,entry);
break;
case 5:printf("\nEnter a roll no. which you want to modify\n");
scanf("%d",&ser);
modify(d,ser,entry);
break;
case 6:printf("\nEnter a roll no. which you want to delete\n");
scanf("%d",&ser);
entry=delete(d,ser,entry);
break;
}
}while(choice<7);
}
|
C | /*
* main.c
*
* Created on: Feb 6, 2014
* Author: gankit
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define TEST
#undef TEST
#ifndef TEST
#define NO_OF_MATRICES 15
#else
#define NO_OF_MATRICES 3
#endif
#define INF ~(1 << 31)
#define ZERO 0
inline int min(int a, int b) {
return (a < b) ? a : b;
}
int optimizeParenthisization (int *nXm, int **solution, int grp, int pos)
{
int temp, size;
if (solution[grp - 1][pos - 1] < INF)
temp = solution[grp - 1][pos - 1];
else {
temp = INF;
for (size = 1; size <= (grp - 1); size++)
{
temp = min(temp, (nXm[pos - 1] * nXm[size + pos - 1] * \
nXm[grp + pos -1]) + \
optimizeParenthisization(nXm, solution, size, pos) + \
optimizeParenthisization(nXm, solution, grp - size, \
size + pos));
}
}
solution[grp - 1][pos - 1] = temp;
return temp;
}
void optimizeParenthisizationBottomUp (int *nXm, int **solution, int grp)
{
int temp, size, pos, loc;
for (pos = 1; pos <= grp; pos++)
{
solution[1 - 1][pos - 1] = 0;
}
for (pos = 1; pos <= (grp - 1); pos++)
{
solution[2 - 1][pos - 1] = nXm[pos - 1] * nXm[pos] * nXm[pos + 1];
}
for (size = 3; size <= grp; size++)
{
for (pos = 1; pos <= (grp - size + 1); pos++)
{
temp = INF;
for (loc = 1; loc <= (size - 1); loc++) {
temp = min(temp, (nXm[pos - 1] * nXm[loc + pos - 1] * \
nXm[size + pos - 1]) + \
solution[loc - 1][pos - 1] + \
solution[size - loc - 1][loc + pos - 1]);
}
solution[size - 1][pos - 1] = temp;
}
}
}
void optimizeParenthisizationWrapper (int *nXm, int **solution, int grp)
{
int size, pos;
for (pos = 1; pos <= grp; pos++)
solution[1 - 1][pos - 1] = 0;
for (pos = 1; pos <= (grp - 1); pos++)
solution[2 - 1][pos - 1] = nXm[pos - 1] * nXm[pos] * nXm[pos + 1];
for (size = 3; size <= grp; size++)
for (pos = 1; pos <= (grp - size + 1); pos++)
solution[size - 1][pos - 1] = INF;
pos = optimizeParenthisization(nXm, solution, grp, 1);
}
void displaySolutionMatrix (int **solution, int grp)
{
int size, pos;
for (size = 1; size <= grp; size++) {
for (pos = 1; pos <= (grp - size + 1); pos++) {
printf(" %06d,", solution[size - 1][pos - 1]);
}
printf("\n\n");
}
}
void displayMatrixChain (int *n_X_m, int grp)
{
int size;
for (size = 1; size <= grp; size++) {
printf(" %03d X %03d", n_X_m[size - 1], n_X_m[size]);
printf("\n\n");
}
}
int main()
{
int *nXm, size, order;
int **solution;
order = NO_OF_MATRICES;
nXm = (int *)malloc((order + 1) * sizeof(int));
solution = (int **)malloc(order * sizeof(int *));
for (size = 1; size <= order; size++)
{
solution[size - 1] = (int *)malloc((order - size + 1) * sizeof(int));
}
#ifndef TEST
for (size = 1; size <= (order + 1); size++)
{
srand(time(NULL) + size * size + 100);
nXm[size - 1] = 1 + rand() % 99;
}
#else
/* Test sequence, set NO_OF_MATRICES = 3 and then test.
* Answer must be 7500.*/
nXm[0] = 10;
nXm[1] = 100;
nXm[2] = 5;
nXm[3] = 50;
#endif
displayMatrixChain(nXm, order);
optimizeParenthisizationWrapper(nXm, solution, order);
displaySolutionMatrix(solution, order);
optimizeParenthisizationBottomUp(nXm, solution, order);
displaySolutionMatrix(solution, order);
return 0;
}
|
C | // Name: Anthony Tracy
// Note this is still psudocode, there is implimentation of C for most part, but still psudocode
// This would be code found in a fucntion that the process would fork()
// Let there be some shared data as shown below:
MAX_THREAD=4;
AT_BARRIER=0;
/*
This is some section of code that each
thread would be running and
depending on the data
this will take a different
amount of time for each.
*/
// At this point we need the barrier:
lock();
AT_BARRIER++; // Critical section, need mutex or the lock
signal()
while(AT_BARRIER<=MAX_THREAD)
{
wait(); // we can now unlock the barrier;
}
/*
This is the section that 4 processes
must be ready before we start this part.
*/
|
C | #include <greek.h>
#include "normucase.proto.h"
/*
* convert from beta code capital letters
*
* greg crane
* february 1987
*/
/*
* start with something like "*(/ellhn"
* and end with "E(/llhn"
*/
normucase(char *word)
{
register char * s;
register char * t;
if( *word != BETA_UCASE_MARKER ) return(0);
s = word;
while(!isalpha(*s)&&*s) s++;
/*
* in case of "*(/ellhn", s points now to "ellhn"
*/
if( ! islower(*s) )
return(0);
*word = toupper(*s);
/*
* word now "E(/ellhn"
*/
t = s+1;
strcpy(s,t);
/*
* word now "E(/llhn"
*/
}
|
C | #ifndef SIGCHAIN_H
#define SIGCHAIN_H
/**
* Code often wants to set a signal handler to clean up temporary files or
* other work-in-progress when we die unexpectedly. For multiple pieces of
* code to do this without conflicting, each piece of code must remember
* the old value of the handler and restore it either when:
*
* 1. The work-in-progress is finished, and the handler is no longer
* necessary. The handler should revert to the original behavior
* (either another handler, SIG_DFL, or SIG_IGN).
*
* 2. The signal is received. We should then do our cleanup, then chain
* to the next handler (or die if it is SIG_DFL).
*
* Sigchain is a tiny library for keeping a stack of handlers. Your handler
* and installation code should look something like:
*
* ------------------------------------------
* void clean_foo_on_signal(int sig)
* {
* clean_foo();
* sigchain_pop(sig);
* raise(sig);
* }
*
* void other_func()
* {
* sigchain_push_common(clean_foo_on_signal);
* mess_up_foo();
* clean_foo();
* }
* ------------------------------------------
*
*/
/**
* Handlers are given the typedef of sigchain_fun. This is the same type
* that is given to signal() or sigaction(). It is perfectly reasonable to
* push SIG_DFL or SIG_IGN onto the stack.
*/
typedef void (*sigchain_fun)(int);
/* You can sigchain_push and sigchain_pop individual signals. */
int sigchain_push(int sig, sigchain_fun f);
int sigchain_pop(int sig);
/**
* push the handler onto the stack for the common signals:
* SIGINT, SIGHUP, SIGTERM, SIGQUIT and SIGPIPE.
*/
void sigchain_push_common(sigchain_fun f);
void sigchain_pop_common(void);
#endif /* SIGCHAIN_H */
|
C | /*-----------------------------------------------
SIZE.c -
------------------------------------------------*/
#include <stdlib.h>
#include <string.h>
#include "Common.h"
#include "CoAPBlk.h"
/**
* Construct SIZE struct
*/
void NewBlock(CoAPBlk_t *blk, u8 bf, u8 blkn, u16 len)
{
blk->bf = bf;
blk->blkn = blkn;
blk->len = len;
}
void BlkFromBytes(CoAPBlk_t *blk, u8 buf[])
{
blk->bf = buf[0] >> 7;
blk->blkn = (buf[0] & 0x7f) >> 3;
blk->len = buf[0] & 0x07;
blk->len = (blk->len << 8) + (buf[1] & 0xff);
}
/**
* Convert Block struct to bytes, return byte array length
*/
u8 Blk2Bytes(CoAPBlk_t *blk, u8 buf[])
{
buf[0] = (blk->bf << 7) + (blk->blkn << 3) + (u8)((blk->len >> 8) & 0x07);
buf[1] = (u8)(blk->len & 0xff);
return 2;
}
/**
* Convert Block struct to option struct, return OK or error code
*/
Ret Blk2Option(CoAPBlk_t *blk, u8 opt_code, CoAPOption *opt)
{
opt->opt_code = opt_code;
opt->opt_len = Blk2Bytes(blk,opt->opt_val);
return COAP_OK;
}
|
C | #include "time.h"
static unsigned timer_ticks = 0;
static time_handle handles[NUM_TIME_HANDLES];
static int handle_index = -1;
void set_phase(unsigned hz) {
unsigned divisor = 1193180 / hz; /* Calculate our divisor */
outb(0x43, 0x36); /* Set our command byte 0x36 */
outb(0x40, divisor & 0xFF); /* Set low byte of divisor */
outb(0x40, (uint8_t)(divisor >> 8)); /* Set high byte of divisor */
}
void timer_handler(struct regs *r) {
timer_ticks++;
unsigned i;
for(i = 0; i < NUM_TIME_HANDLES; ++i) {
time_handle fcn = handles[i];
// break if no function present
if(fcn == NULL) {
continue;
}
fcn(r, timer_ticks);
}
}
void init_time() {
// 1 millisecond timing
set_phase(TICKS_PER_SEC);
install_irq_handle(0, timer_handler);
}
int install_time_handler(time_handle fcn) {
int index = ++handle_index;
// out of space
if(index >= NUM_TIME_HANDLES) {
return -1;
}
handles[index] = fcn;
return index;
}
void uninstall_time_handler(int index) {
handles[index] = NULL;
}
unsigned get_ticks() {
return timer_ticks;
}
|
C | /*
* sendMail.c
*
* Rafael dos Santos Alves ([email protected])
* Viviane de França Oliveira ([email protected])
*
*/
#include "network.h"
#include "error.h"
#include "const.h"
#include "types.h"
int main (int argc, char *argv[])
{
int port=0;
char server[MAXNAMESIZE];
char from[MAXNAMESIZE];
char to[MAXDATASIZE];
char cc[MAXDATASIZE];
char bcc[MAXDATASIZE];
char subject[MAXDATASIZE];
char body[MAXDATASIZE];
char attachment[MAXNAMESIZE];
bzero(server,MAXNAMESIZE);
bzero(from,MAXNAMESIZE);
bzero(to,MAXDATASIZE);
bzero(cc,MAXDATASIZE);
bzero(bcc,MAXDATASIZE);
bzero(subject,MAXDATASIZE);
bzero(body,MAXDATASIZE);
bzero(attachment,MAXNAMESIZE);
errortype error;
int option;
int idx=0;
int to_flag=0,from_flag=0,subject_flag=0,body_flag=0;
int verbose=0;
opterr = 0;
static char opts[] = "f:t:A:s:P:S:b:B:c:hvV";
struct option longopts[]={
{"from", required_argument, 0, 'f'},
{"to", required_argument, 0, 't'},
{"cc", required_argument, 0, 'c'},
{"bcc", required_argument, 0, 'b'},
{"Server", required_argument, 0, 'S'},
{"Port", required_argument, 0, 'P'},
{"Body", required_argument, 0, 'B'},
{"subject", required_argument, 0 ,'s'},
{"Attachment",required_argument, 0,'A'},
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{0,0,0,0},
};
error=LoadDefaultParameters(server,&port,from,to,body,subject,verbose);
if(error!=0){
printerror(error,0);
exit(-1);
}
#ifdef _MY_DEBUG_
printf("%s, %d, %s, %s, %s\n",server, port, from, body, subject);
#endif
while((option=getopt_long(argc,argv,opts,longopts,&idx))!=-1){
switch(option){
case 0:
{
printf("missing option\n");
break;
}
case 'h':
{
printf("\nUsage: %s [-h|--help]\n",argv[0]);
printf(" %s [-f|--from <endereço de origem>] [-t|--to <endereço do destinatário>] [Options]\n",argv[0]);
printf("\nOptions:\n[-S|--Server <endereço do servidor>]\n[-P|--Port <porta>]\n[-c|--cc <endereço de cópia]\n[-b|--bcc <endereço de cópia oculta>]\n[-s|--subject <assunto>]\n[-B|--Body <corpo da mensagem>]\n[-A|--Attachment <anexos>]\n[-v|--verbose]\n\n");
exit(-1);
break;
}
case 'v':
{
verbose=1;
printf("\nVerbose Mode\n\n");
break;
}
case 'f':
{
bzero(from,MAXNAMESIZE);
strcpy(from,optarg);
#ifdef _MY_DEBUG_
printf("Mail from: %s.\n",from);
#endif
from_flag++;
break;
}
case 't':
{
bzero(to,MAXNAMESIZE);
strcpy(to,optarg);
#ifdef _MY_DEBUG_
printf("Mail to: %s.\n",to);
#endif
to_flag++;
break;
}
case 'c':
{
bzero(cc,MAXNAMESIZE);
strcpy(cc,optarg);
#ifdef _MY_DEBUG_
printf("Mail cc: %s.\n",cc);
#endif
break;
}
case 'b':
{
bzero(bcc,MAXNAMESIZE);
strcpy(bcc,optarg);
#ifdef _MY_DEBUG_
printf("Mail bcc: %s.\n",bcc);
#endif
break;
}
case 'A':
{
bzero(attachment,MAXNAMESIZE);
strcpy(attachment,optarg);
#ifdef _MY_DEBUG_
printf("Attachment: %s\n",optarg);
#endif
break;
}
case 'S':
{
bzero(server,MAXNAMESIZE);
strcpy(server,optarg);
#ifdef _MY_DEBUG_
printf("Mail server: %s.\n",server);
#endif
break;
}
case 's':
{
bzero(subject,MAXDATASIZE);
strcpy(subject,optarg);
#ifdef _MY_DEBUG_
printf("Mail subject: %s.\n",subject);
#endif
subject_flag++;
break;
}
case 'P':
{
port=atoi(optarg);
#ifdef _MY_DEBUG_
printf("Port used: %d.\n",port);
#endif
break;
}
case 'B':
{
bzero(body,MAXDATASIZE);
strcpy(body,optarg);
#ifdef _MY_DEBUG_
printf("Mail body: %s\n",body);
#endif
body_flag++;
break;
}
default:
{
printf("Opção inválida!\n");
exit(-1);
break;
}
}
}
if(!from_flag){
printerror(MissingInputFrom,verbose);
exit(-1);
}
if(!to_flag){
printerror(MissingInputTo,verbose);
exit(-1);
}
if(!subject_flag){
if(verbose)
printf("Missing optional argument: \'Subject\'\n");//printerror(...)
// exit(-1);
}
if(!body_flag){
if(verbose)
printf("Missing optional argument: \'body\'\n");//printerror(...)
// exit(-1);
}
error = sendMail(server, port, from, to, cc, bcc, subject, body, attachment,verbose);
if(error!=0){
printerror(error,verbose);
exit(-1);
}
return 0;
}
|
C | #include<stdio.h>
void main()
{
char str[81],*p=str,*q,t;
gets(str);
printf("The origenal string:\n");
puts(str);
for(p=str;*(p+1);p++)
for(q=p+1;*q;q++)
if(*q<*p)
{
t=*p;
*p=*q;
*q=t;
}
printf("The result string:\n");
puts(str);
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* final.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mapryl <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/03 22:54:38 by mapryl #+# #+# */
/* Updated: 2019/03/03 23:02:08 by mapryl ### ########.fr */
/* */
/* ************************************************************************** */
void ft_putchar(char c);
int calc_base_length(int n)
{
int cur_level_hight;
int cur_hight;
int cur_length;
int i;
cur_level_hight = 3;
cur_hight = 1;
cur_length = 1;
i = 1;
while (1)
{
cur_hight += 1;
cur_length += 2;
if (cur_hight == cur_level_hight)
{
if (++i > n)
return (cur_length + 2);
cur_hight = 1;
cur_level_hight += 1;
cur_length += 6;
}
}
}
void put_n_char(char ch, int n)
{
int i;
i = 0;
while (i++ < n)
{
ft_putchar(ch);
}
}
void print_pyramid_row(int i, int n, int *p)
{
int door_begin_left;
if (i == n && p[4] > p[1])
{
ft_putchar('/');
door_begin_left = (p[5] - 2 - p[2]) / 2;
put_n_char('*', door_begin_left);
if (n >= 5 && p[4] - p[1] == p[2] / 2 + 1)
{
put_n_char('|', p[2] - 2);
ft_putchar('$');
ft_putchar('|');
}
else
put_n_char('|', p[2]);
put_n_char('*', door_begin_left);
ft_putchar('\\');
}
else
{
ft_putchar('/');
put_n_char('*', p[5] - 2);
ft_putchar('\\');
}
ft_putchar('\n');
}
void init_pyramid(int *pyramid, int n)
{
pyramid[0] = calc_base_length(n);
if (n % 2 == 1)
{
pyramid[2] = n;
pyramid[1] = 2;
}
else
{
pyramid[2] = n - 1;
pyramid[1] = 3;
}
pyramid[3] = 3;
pyramid[4] = 0;
pyramid[5] = 1;
}
void sastantua(int n)
{
int i;
int pyramid[6];
int offset;
if (n <= 0)
return ;
i = 1;
init_pyramid(pyramid, n);
while (1)
{
pyramid[4]++;
pyramid[5] += 2;
offset = (pyramid[0] - pyramid[5]) / 2;
put_n_char(' ', offset);
print_pyramid_row(i, n, pyramid);
if (pyramid[4] == pyramid[3])
{
if (++i > n)
return ;
pyramid[4] = 0;
pyramid[5] += 4;
pyramid[3] += 1;
}
}
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: glasset <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/03/08 11:09:40 by glasset #+# #+# */
/* Updated: 2014/03/09 15:54:19 by gmarais ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include "puissance.h"
int put_error(char *str, int ernum)
{
write(2, str, ft_strlen(str));
return (ernum);
}
int only_nb(char *str, int min)
{
size_t i;
i = 0;
if (str[0] == '\0')
return (-1);
while (str[i])
{
if (str[i] < '0' || str[i] > '9')
return (-1);
i++;
}
if (i == ft_strlen(str) && min <= ft_atoi(str))
return (0);
return (-1);
}
int ft_rand(void)
{
srand(time(NULL));
return (rand()%2);
}
void print_winner(int winner, t_env *e)
{
print_board(e);
if (winner == 1)
{
put_charcolor(PAWNS_HUM, "\033[1;33m");
ft_putendl(": wins!");
}
else if (winner == 2)
{
put_charcolor(PAWNS_IA, "\033[1;31m");
ft_putendl(": wins!");
}
else
ft_putendl("(>X_X)> Draw! <(X_X<)");
}
int main(int ac, char **av, char **env)
{
t_env e;
int player;
int winner;
if (ac != 4 && ac != 3)
return (put_error("Usage: puissance4 [num_line] [num_column]\n", -1));
if (init_env(&e, av, env) || init_board(&e) == -1)
return (-1);
player = ft_rand();
print_board(&e);
while (!(winner = play_round(&e, player)))
{
print_board(&e);
player = (player) ? 0 : 1;
}
print_winner(winner, &e);
return (0);
}
|
C | #ifndef _EVENT_H
#define _EVENT_H
/* Events are actually function pointers, and your event is expected to take
** one argument that is a pointer to the object to which the event occurs.
*/
typedef void *Object;
typedef void (*Event)(Object);
typedef double Time;
typedef struct _eventStruct
{
Time time;
Event event; /* pointer to event function that accepts object as param */
Object object;
} EventInfo;
/* initialize the event list to have max size. Returns NULL if too big,
** else non-NULL.
*/
int EventListInit(int maxNumEvents);
/* returns pointer to EventInfo (which you can ignore) if OK, else NULL.
*/
EventInfo *EventInsert(Event event, Time delta, Object object);
/* Returns the next event, or NULL if there are none
*/
EventInfo *EventNext(void);
/* Return the current time */
extern Time _event_now;
#define EventNow() _event_now
#endif /* _EVENT_H */
|
C | /* -------------------------------------------------------------------------
* Project: sumoGeek
* Author: Germán Sc.
* Date: 18-08-17
* Version: 0.1
*
* Description:
* Biblioteca para el control de los motores.
* ------------------------------------------------------------------------- */
#ifndef SRC_LIB_MOTORLIB_H_
#define SRC_LIB_MOTORLIB_H_
typedef struct motorStruct {
byte motorPinA;
byte motorPinB;
byte motorPinEnable;
int motorSpeed;
bool motorRunning;
} motorControlBlock;
/* Variables Externas. */
extern motorControlBlock* motorR;
extern motorControlBlock* motorL;
/* Funciones de Incializacion de la estructura de control del Motor. */
motorControlBlock* motorInit(byte pinEnable, byte pinA, byte pinB);
/* Funciones de control de motores. */
void motorStop(motorControlBlock* motor);
void motorStart(motorControlBlock* motor);
void motorSetSpeed(motorControlBlock* motor, int pwmVal);
#endif /* SRC_LIB_MOTORLIB_H_ */
|
C | #include<stdio.h>
#include<stdlib.h>
#define size 30
char s[size];
int top=-1;
void push(char item)
{
if(top==size-1)
printf("Overflow");
else
s[++top]=item;
}
int is_operator(char item)
{
if(item=='*'||item=='/'||item=='+'||item=='-'||item=='^')
return(1);
else
return(0);
}
int precedence(char item)
{
if(item=='^')
return(4);
else if(item=='/'||item=='*')
return(3);
else if(item=='+'||item=='-')
return(2);
else
return(1);
}
char pop()
{
char item;
item=s[top];
top--;
return(item);
}
void main()
{
char infix[30],postfix[30],a,item;
int i=0,j=0;
printf("Enter the infix expression\n");
gets(infix);
while(infix[i]!='\0')
{
item=infix[i];
if(item=='(')
push(item);
else if(isalnum(item))
{
postfix[j]=item;
j=j+1;
}
else if(is_operator(item)==1)
{
if(item!='^')
{
while(top!=-1&&precedence(s[top])>=precedence(item))
{
postfix[j]=pop();
j=j+1;
}
}
push(item);
}
else if(item==')')
{
while(s[top]!='(')
{
postfix[j]=pop();
j=j+1;
}
a=pop();
}
i++;
}
while(top!=-1)
postfix[j++]=pop();
postfix[j]='\0';
puts(postfix);
}
|
C | #include <pebble.h>
#include "log_menu_window.h"
#include "old_entry_window.h"
#include "model.h"
Window *log_menu_window; // The window that houses it all
static MenuLayer *log_menu_layer; // The layer that houses it all
static WorkoutPeek *workouts; // The collection of workouts that we need to worry about to avoid slowness when redrawing
static int workout_count; // The total number of workouts
/* log_menu_init() function */
void log_menu_init(){
if(log_menu_window == NULL){
log_menu_window = window_create();
}
// Let's get all of the workout peeks and store them in our array
workout_count = get_workout_count();
workouts = (WorkoutPeek*)malloc(workout_count * sizeof(peek_workout(0)));
for(int i = 0; i < workout_count; i++){
workouts[i] = peek_workout(i);
}
window_set_window_handlers(log_menu_window, (WindowHandlers){
.load = log_menu_window_load,
.unload = log_menu_window_unload
});
window_stack_push(log_menu_window, true);
}
/*
* Window Handlers
*/
void log_menu_window_load(Window *window){
// Create and setup the menu_layer
log_menu_layer = menu_layer_create(layer_get_frame(window_get_root_layer(window)));
menu_layer_set_callbacks(log_menu_layer, NULL, (MenuLayerCallbacks){
.get_num_sections = get_num_sections_callback,
.get_num_rows = get_num_rows_callback,
.get_header_height = get_header_height_callback,
.draw_header = draw_header_callback,
.draw_row = draw_row_callback,
.select_click = row_selected_callback
});
// Subscribe the clicks to this window
menu_layer_set_click_config_onto_window(log_menu_layer, window);
// Add the layer to the window
layer_add_child(window_get_root_layer(window), menu_layer_get_layer(log_menu_layer));
}
void log_menu_window_unload(Window *window){
menu_layer_destroy(log_menu_layer);
free(workouts);
}
/*
* Callbacks - so many callbacks...
*/
/* Returns the number of sections for the menu */
uint16_t get_num_sections_callback(MenuLayer *layer, void *data){
return 1;
}
/* Returns the number of rows (or old workouts) */
uint16_t get_num_rows_callback(MenuLayer *menu_layer, uint16_t section_index, void *data){
return workout_count;
}
/* Returns the header height */
int16_t get_header_height_callback(MenuLayer *menu_layer, uint16_t section_index, void *data){
return MENU_CELL_BASIC_HEADER_HEIGHT;
}
/* Draws the header of the section or whatever */
void draw_header_callback(GContext* ctx, const Layer *cell_layer, uint16_t section_index, void *data){
menu_cell_basic_header_draw(ctx, cell_layer, "Old Workouts");
}
/* Draws the row at the index given */
void draw_row_callback(GContext* ctx, const Layer *cell_layer, MenuIndex *cell_index, void *data){
// Get the workout peek structure from wherever the index is
WorkoutPeek peek = workouts[cell_index->row];
// Throw it into a buffer to write out the title and subtitle
char title_buffer[] = "DD MMM YYYY - T";
char day = 'A';
if(peek.day_type)
day = 'B';
snprintf(title_buffer, sizeof(title_buffer), "%i %s %i - %c", peek.day, int_to_month(peek.month), peek.year, day);
menu_cell_basic_draw(ctx, cell_layer, title_buffer, "", NULL);
}
/* Runs when a row is selected */
void row_selected_callback(MenuLayer *menu_layer, MenuIndex *cell_index, void *data){
int selected_index = cell_index->row;
old_entry_window_init(selected_index);
}
|
C | //
// main.c
// P2676_超级书架
//
// Created by 谢 on 2019/9/24.
// Copyright © 2019 谢. All rights reserved.
//
#include <stdio.h>
int ls[20005];
int main() {
int n,b,i,j,val,sum=0,time = 0;
scanf("%d%d",&n,&b);
for (i=0; i<n; i++) {
scanf("%d",&ls[i]);
}
for (i=0; i<n; i++) {
for (j=i; j>=0; j-=1) {
if (ls[j] < ls[j+1]) {
val = ls[j+1];
ls[j+1] = ls[j];
ls[j] = val;
}
}
}
i = 0;
while (sum<b) {
sum += ls[i];
i++;
time++;
}
printf("%d\n",time);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include "quick_sort.h"
void print(int array[], int num)
{
for (int i = 0; i < num; ++i)
{
printf("%d\t", array[i]);
}
printf("\n");
}
int main(int argc, char const *argv[])
{
int a[] = {13,19,9,5,12,8,7,4,21,2,6,11};
print(a, 12);
quick_sort(a, 0, 11);
print(a, 12);
return 0;
}
|
C | #include<avr/io.h>
#include<avr/delay.h>
#define PORT PORTD
#define DDR DDRD
int main(void)
{
DDR = 0xFF;
PORT = 0x00;
while(1)
{
for( int i =0 ; i<8 ; i++)
PORT = (1<<i),_delay_ms(80);
for( int i = 7 ; i>=0 ; i--)
PORT = (1<<i), _delay_ms(80);
}
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include "gc_stack.h"
#include "prim_int63.h"
typedef value primfloat;
typedef value primfloatintpair;
typedef value primfloat_comparison;
typedef value primfloat_class;
#define trace(...) // printf(__VA_ARGS__)
#define Double_block 1277 // Double_tag & 1024
primfloat mk_float (struct thread_info *tinfo, double x) {
trace("Calling mk_float with %a, %f\n", x, x);
register value *$alloc;
register value *$limit;
$limit = (*tinfo).limit;
$alloc = (*tinfo).alloc;
if (!(2LLU <= $limit - $alloc)) {
/*skip*/;
(*tinfo).nalloc = 2LLU;
garbage_collect(tinfo);
/*skip*/;
$alloc = (*tinfo).alloc;
$limit = (*tinfo).limit;
}
*($alloc + 0LLU) = Double_block;
*((double*) ($alloc + 1LLU)) = x;
(*tinfo).alloc = (*tinfo).alloc + 2LLU;
// trace ("mk_float return adress: %p\n", (void*)(((unsigned long long *) $alloc) + 1LLU));
// trace ("mk_float return value: %f\n", Double_val ((double*)(((unsigned long long *) $alloc) + 1LLU)));
return (value) ((unsigned long long *) $alloc + 1LLU);
}
#define FEq 1U
#define FLt 3U
#define FGt 5U
#define FNotComparable 7U
primfloat_comparison prim_float_compare(primfloat x, primfloat y) {
double xv = Double_val(x);
double yv = Double_val(y);
trace ("Comparing floats: %f and %f\n", xv, yv);
if (x < y) return FLt;
else if (x > y) return FGt;
else if (x == y) return FEq;
else return FNotComparable;
}
primbool prim_float_eqb(primfloat x, primfloat y) {
double xv = Double_val(x);
double yv = Double_val(y);
trace ("Comparing floats for equality: %f and %f\n", xv, yv);
return (mk_bool (xv == yv));
}
primbool prim_float_equal(primfloat x, primfloat y) {
double xv = Double_val(x);
double yv = Double_val(y);
trace ("Comparing floats for equality: %f and %f\n", xv, yv);
switch (fpclassify(xv))
{ case FP_NORMAL:
case FP_SUBNORMAL:
case FP_INFINITE:
return (mk_bool (xv == yv));
case FP_NAN:
return (mk_bool (isnan (yv)));
case FP_ZERO:
return (mk_bool (xv == yv && ((1 / xv) == (1 / yv))));
default:
exit (1); // Should not happen
}
// return (mk_bool (xv == yv));
}
primbool prim_float_ltb(primfloat x, primfloat y) {
double xv = Double_val(x);
double yv = Double_val(y);
trace ("prim_float_ltb %f and %f\n", xv, yv);
return (mk_bool (xv < yv));
}
primbool prim_float_leb(primfloat x, primfloat y) {
double xv = Double_val(x);
double yv = Double_val(y);
return (mk_bool (xv <= yv));
}
// let eshift = 2101 (* 2*emax + prec *)
unsigned long long eshift = 2101;
primfloatintpair prim_float_frshiftexp(struct thread_info *tinfo, primfloat x) {
double xv = Double_val(x);
int e = 0;
value frac;
trace ("prim_float_frshiftexp %f\n", xv);
switch (fpclassify(xv))
{
case FP_NAN:
case FP_INFINITE:
case FP_ZERO:
return (mk_pair(tinfo, x, Val_long(0)));
case FP_NORMAL:
case FP_SUBNORMAL:
trace ("prim_float_frshiftexp frexp %f\n", frexp(xv, &e));
frac = mk_float(tinfo, frexp(xv, &e));
trace ("prim_float_frshiftexp result %f, %llu\n", Double_val(frac), (e + eshift));
return (mk_pair(tinfo, frac, Val_long(e + eshift)));
default:
exit(1); // Should not happen
}
}
primfloat prim_float_ldshiftexp(struct thread_info *tinfo, primfloat x, primint y) {
//todo fix
double xv = Double_val(x);
int e = 0;
value frac;
trace ("prim_float_ldshiftexp %f\n", xv);
switch (fpclassify(xv))
{
case FP_NAN:
case FP_INFINITE:
case FP_ZERO:
return (mk_pair(tinfo, x, Val_long(0)));
case FP_NORMAL:
case FP_SUBNORMAL:
frac = mk_float(tinfo, frexp(xv, &e));
return (mk_pair(tinfo, frac, Val_long(e + eshift)));
default:
exit(1); // Should not happen
}
}
int prec = 53;
primint prim_float_normfr_mantissa(primfloat x) {
double xv = Double_val(x);
double f = fabs(xv);
trace ("prim_float_normfr_mantissa %f, abs: %f, ldexp: %f, %llu\n", xv, f, ldexp(f, prec),
((unsigned long long) ldexp(f, prec)));
if (f >= 0.5 && f < 1.0)
{ return (Val_long ((unsigned long long) (ldexp(f, prec)))); }
else return (Val_long(0));
}
primfloat_class prim_float_classify(primfloat x) {
double xv = Double_val(x);
trace ("prim_float_classify %f\n", xv);
switch (fpclassify(xv))
{
case FP_NAN: return ((8 << 1) + 1);
case FP_INFINITE: return (signbit(xv) ? (7 << 1) + 1 : (6 << 1) + 1);
case FP_ZERO: return (signbit(xv) ? (5 << 1) + 1 : (4 << 1) + 1);
case FP_SUBNORMAL: return (signbit(xv) ? (3 << 1) + 1 : (2 << 1) + 1);
case FP_NORMAL: return (signbit(xv) ? (1 << 1) + 1 : 1);
default: exit (1); // impossible
}
}
primfloat prim_float_abs(struct thread_info *tinfo, primfloat x) {
double xv = Double_val(x);
trace ("prim_float_abs %f\n", xv);
return (mk_float (tinfo, fabs(xv)));
}
primfloat prim_float_sqrt(struct thread_info *tinfo, primfloat x) {
double xv = Double_val(x);
trace ("prim_float_sqrt %f\n", xv);
return (mk_float (tinfo, sqrt(xv)));
}
primfloat prim_float_opp(struct thread_info *tinfo, primfloat x) {
double xv = Double_val(x);
trace ("prim_float_opp %f\n", xv);
return (mk_float (tinfo, - xv));
}
primfloat prim_float_div(struct thread_info *tinfo, primfloat x, primfloat y) {
double xv = Double_val(x);
double yv = Double_val(y);
trace ("prim_float_div %f and %f\n", xv, yv);
return (mk_float (tinfo, xv / yv));
}
primfloat prim_float_mul(struct thread_info *tinfo, primfloat x, primfloat y) {
double xv = Double_val(x);
double yv = Double_val(y);
trace ("prim_float_mul %f and %f\n", xv, yv);
return (mk_float (tinfo, xv * yv));
}
primfloat prim_float_add(struct thread_info *tinfo, primfloat x, primfloat y) {
double xv = Double_val(x);
double yv = Double_val(y);
trace ("prim_float_add %f and %f\n", xv, yv);
return (mk_float (tinfo, xv + yv));
}
primfloat prim_float_sub(struct thread_info *tinfo, primfloat x, primfloat y) {
double xv = Double_val(x);
double yv = Double_val(y);
trace ("prim_float_sub %f and %f\n", xv, yv);
return (mk_float (tinfo, xv - yv));
}
primfloat prim_float_of_uint63(struct thread_info * tinfo, primint x) {
double xv = (double) (Long_val(x));
trace ("prim_float_of_uint63 %f\n", xv);
return (mk_float (tinfo, xv));
}
union double_bits {
double d;
uint64_t u;
};
static double next_up(double x) {
union double_bits bits;
trace ("prim_float_nextup %f\n", x);
if (!(x < INFINITY)) return x; // x is +oo or NaN
bits.d = x;
int64_t i = bits.u;
if (i >= 0) ++bits.u; // x >= +0.0, go away from zero
else if (bits.u + bits.u == 0) bits.u = 1; // x is -0.0, should almost never happen
else --bits.u; // x < 0.0, go toward zero
return bits.d;
}
static double next_down(double x) {
union double_bits bits;
trace ("prim_float_nextdown %f\n", x);
if (!(x > -INFINITY)) return x; // x is -oo or NaN
bits.d = x;
int64_t i = bits.u;
if (i == 0) bits.u = INT64_MIN + 1; // x is +0.0
else if (i < 0) ++bits.u; // x <= -0.0, go away from zero
else --bits.u; // x > 0.0, go toward zero
return bits.d;
}
primfloat prim_float_next_up(struct thread_info * ti, primfloat x) {
double xv = Double_val(x);
return (mk_float (ti, next_up(xv)));
}
primfloat prim_float_next_down(struct thread_info * ti, primfloat x) {
double xv = Double_val(x);
return (mk_float (ti, next_down(xv)));
}
|
C |
#include <stdio.h>
void display_float(double x) {
int i;
for (i=0; i<8; i++) { // 8 is sizeof(double)
unsigned char c;
c = ((char *)(&x))[i];
printf("%x-", c);
}
printf("\n");
}
main() {
double a = 800.0 ;
double b = 0.75 ;
double c = 0.6 ;
printf("sizeof(double)=%d\n", sizeof(double));
printf("a=%f\n", a);
display_float(a);
printf("b=%f\n", b);
display_float(b);
printf("c=%f\n", c);
display_float(c);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_s_conv.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bgonzale <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/09/26 16:02:34 by bgonzale #+# #+# */
/* Updated: 2019/04/08 04:46:11 by bgonzale ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
int ft_s_right(t_fwplc *ptrfwplc, t_flags *ptrflags, char *str)
{
int str_len;
int mwidth;
int prec;
str_len =
(ptrfwplc->precision >= 0 && ptrfwplc->precision <= ft_strlen(str))
? ptrfwplc->precision : ft_strlen(str);
mwidth = 0;
prec = 0;
if (ptrfwplc->minw > str_len)
{
while (mwidth < ptrfwplc->minw - str_len)
{
(ptrflags->zero) ? ft_putchar('0') : ft_putchar(' ');
mwidth++;
}
}
if (ptrfwplc->precision > -1)
{
while (prec < str_len)
ft_putchar(str[prec++]);
}
else
ft_putstr(str);
return (str_len + mwidth);
}
int ft_s_left(t_fwplc *ptrfwplc, char *str)
{
int str_len;
int mwidth;
int prec;
str_len =
(ptrfwplc->precision >= 0 && ptrfwplc->precision <= ft_strlen(str))
? ptrfwplc->precision : ft_strlen(str);
mwidth = 0;
prec = 0;
if (ptrfwplc->precision > -1)
{
while (prec < str_len)
ft_putchar(str[prec++]);
}
else
ft_putstr(str);
if (ptrfwplc->minw > str_len)
{
while (mwidth < ptrfwplc->minw - str_len)
{
ft_putchar(' ');
mwidth++;
}
}
return (str_len + mwidth);
}
int ft_s_conv(t_fwplc *ptrfwplc, t_flags *ptrflags, va_list arg)
{
char *str;
int str_len;
str = va_arg(arg, char *);
str_len = 0;
if (!str)
{
ft_putstr("(null)");
return (6);
}
if (ptrflags->minus)
str_len = ft_s_left(ptrfwplc, str);
else
str_len = ft_s_right(ptrfwplc, ptrflags, str);
return (str_len);
}
|
C | #include <stdio.h>
#include<stdlib.h>
typedef struct node {
int value;
struct node *next;
struct node *prev;
} node;
node *head=NULL;
node *tail=NULL;
int isEmpty()
{
if ((head==NULL)&&(tail==NULL))
return 1;
else return 0;
}
int init(int value)
{
struct node *tmp;
tmp = (struct node*)malloc(sizeof(struct node));
tmp->value=value;
tmp->next=NULL;
tmp->prev=NULL;
head= tmp;
tail = tmp;
}
void zap(int x)
{
if(isEmpty()==1)
init (x);
else
{
struct node *tmp = (struct node*)malloc(sizeof(struct node));
tmp->value=x;
tmp->prev=tail;
tmp->next=NULL;
tail=tmp;
tmp->prev->next=tmp;
}
};
int destroy()
{
if(isEmpty()==0)
{
struct node *tmp=head;
struct node *temp=NULL;
while(tmp!=NULL)
{
temp=tmp->next;
free(tmp);
tmp=temp;
}
head=NULL;
tail=NULL;
}
};
void get_out()
{
struct node *tmp=head;
printf("%d", tmp->value);
while(tmp->next!=NULL)
{
tmp=tmp->next;
printf(" %d", tmp->value);
}
printf("\n");
}
struct node *adressk(int k)
{
struct node *tmp=head;
for (int i =1;i<k;i++)
{
tmp=tmp->next;
if(tmp==NULL) break;
}
return tmp;
}
struct node *znach(int k)
{
node *tmp=head;
while (tmp!=NULL && tmp->value != k)
{
tmp=tmp->next;
}
return tmp;}
void append(int num, int data)
{
node *tmp = adressk(num);
if (tmp==NULL||tmp==tail)
{
struct node *temp = malloc(sizeof(node));
temp->value=data;
temp->next=NULL;
temp->prev=tail;
temp->prev->next=temp;
tail=temp;
}
else
{
node *temp = malloc(sizeof(node));
temp->value=data;
temp->next=tmp->next;
temp->prev=tmp;
tmp->next->prev=temp;
tmp->next=temp;
}
}
void prepend(int num, int data)
{
node *tmp = adressk(num);
if (tmp==NULL||tmp==head)
{
node *temp = malloc(sizeof(node));
temp->value=data;
temp->prev=NULL;
temp->next=head;
head=temp;
temp->next->prev=temp;
}
else
{
node *temp = malloc(sizeof(node));
temp->value=data;
temp->prev=tmp->prev;
temp->next=tmp;
tmp->prev=temp;
temp->prev->next=temp;
}
}
void deletk(struct node *tmp)
{
int f=0;
if(tmp==NULL)
f=1;
if (tmp==head && tmp==tail &&f==0 ){ destroy();f=1;}
if (tmp==head&&f==0)
{
head=tmp->next;
tmp->next->prev=NULL;
free(tmp);
f=1;
}
if(tmp==tail&&f==0)
{
tail=tmp->prev;
tmp->prev->next=NULL;
free(tmp);
f=1;
}
if (tmp!=head && tmp!=tail && f==0)
{
tmp->next->prev=tmp->prev;
tmp->prev->next=tmp->next;
free(tmp);
f=1;
}
}
int main()
{
int n=0,x=0,k=0;
scanf("%d",&n);
for (int i=0;i<n;i++)
{
scanf("%d",&x);
zap(x);
}
get_out();
scanf("%d", &k);
deletk(adressk(k));
if(isEmpty()==0) get_out();
scanf("%d", &k);
deletk(znach(k));
if(isEmpty()==0) get_out();
scanf("%d %d", &k, &n);
append(k,n);
if(isEmpty()==0) get_out();
scanf("%d %d", &k, &n);
prepend(k,n);
if(isEmpty()==0) get_out();
destroy();
return 0;
}
|
C | #include <stdio.h>
void main (void)
{
int contador;
for (contador = 1; contador <=5; contador++)
printf ("%d ", contador);
printf ("\nIniciando o segundo laço\n");
for (contador = 1 ; contador <= 10; contador++)
printf ("\nIniciando terceiro laço\n");
for (contador = 1 ; contador <= 100; contador++);
}
|
C | /*
============================================================================
Name : c.c
Author : Priyadarshini Singh Solanki
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Linkedlist {
int data;
struct Linkedlist *next;
};
void push(struct Linkedlist **head_ref, int newdata) {
struct Linkedlist *newNode = (struct Linkedlist*) malloc(
sizeof(struct Linkedlist));
newNode->data = newdata;
newNode->next = *head_ref;
*head_ref = newNode;
return;
}
void reverseLinklist(struct Linkedlist **head_ref) {
struct Linkedlist *current;
struct Linkedlist *prev = NULL;
struct Linkedlist *nextnode;
current = *head_ref;
while (current != NULL) {
nextnode = current->next;
current->next = prev;
prev = current;
current = nextnode;
}
*head_ref = prev;
}
void printLinkedlist(struct Linkedlist *head_ref) {
while (head_ref != '\0') {
printf("%d ", head_ref->data);
fflush(stdout);
head_ref = head_ref->next;
}
}
int main(void) {
struct Linkedlist *head = NULL;
push(&head, 24);
push(&head, 2);
push(&head, 5);
push(&head, 7);
push(&head, 72);
push(&head, 34);
push(&head, 9);
printLinkedlist(head);
reverseLinklist(&head);
printf("\n");
printLinkedlist(head);
return EXIT_SUCCESS;
}
|
C | /* Задача 11. Напишете функция void squeeze(char s[], int c), която премахва символа с от низа s[] */
#include <stdio.h>
/* "abacd"
.3 bcd */
void squeeze(char s[], int c) {
int i = 0, j = 0;
while (s[i] != '\0') {
if (s[j] == c) j++;
s[i] = s[j];
i++, j++;
}
}
int main() {
char string[] = "Hey there, how are you?";
squeeze(string, 'e');
printf("%s", string);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
FILE* inputFile = fopen("sample_text.txt", "r");
int c;
while ((c = fgetc(inputFile)) != EOF)
{
putchar(c);
}
fclose(inputFile);
exit(0);
}
|
C | #include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "unistd.h"
#include "time.h"
#include "MQTTClient.h"
#define ADDRESS "211.67.16.19"
#define CLIENTID "cpp-mqtt-0001"
#define TOPIC "/python/mqtt"
// QoS0,At most once,至多一次;
// QoS1,At least once,至少一次;
// QoS2,Exactly once,确保只有一次。
#define QOS 0
#define TIMEOUT 10000L
int main(int argc, char* argv[])
{
// 创建mqtt客户端
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc;
srand(time(NULL));
MQTTClient_create(&client, ADDRESS, CLIENTID,
MQTTCLIENT_PERSISTENCE_NONE, NULL);
// 连接mqtt服务器
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
exit(-1);
}
static int msg_count = 0;
char publish_message_buf[128];
while (msg_count < 100) {
usleep(10000);
sprintf(publish_message_buf,
"{\"messages\":%d,\"userDate\":%d,\"userStr\":%4.2f}",
msg_count++, rand() % 128, rand() % 1024 * 0.01f);
// 发布消息
pubmsg.payload = publish_message_buf;
pubmsg.payloadlen = strlen(publish_message_buf);
pubmsg.qos = QOS;
pubmsg.retained = 0;
MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
// printf("Waiting for up to %d seconds for publication of %s\n"
// "on topic %s for client with ClientID: %s\n",
// (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
//printf("Message with delivery token %d delivered\n", token);
}
// 断开服务器连接
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return rc;
} |
C | /*
* merge_array.c
*
* Entire merge sort.
*
* Created on: 2013/01/11
* Author: leo
*/
#include "sort.h"
static int (*comp)(const void *, const void *);
static size_t length;
/* array_sort */
static void copy(void *dst, const void *src, size_t size)
{
#ifdef DEBUG
qsort_moved++;
#endif
memcpy(dst, src, size * length); /* restore an elements */
}
static void sort(void *dst, void *src, size_t nmemb) {
if (nmemb <= 1) return;
#ifdef DEBUG
qsort_called++;
if (trace_level >= TRACE_DUMP) dump_array("sort() start in " __FILE__, src, nmemb, 0, 0, length);
#endif
size_t n_lo = nmemb >> 1; // = nmemb / 2
size_t n_hi = nmemb - n_lo;
size_t lo_length = n_lo * length;
sort(src, dst, n_lo);
sort((char *)src + lo_length, (char *)dst + lo_length, n_hi);
char *left = src;
char *right = &left[lo_length];
char *store = dst;
#ifdef DEBUG
if (trace_level >= TRACE_DUMP) dump_array("merge sub-arrays", left, n_lo, 0, n_hi, length);
#endif
while (TRUE) {
if (comp(left, right) <= 0) {
#ifdef DEBUG
if (trace_level >= TRACE_DUMP) dump_array("merge left", left, 1, 0, 0, length);
#endif
copy(store, left, 1); store += length; left += length; // add one
if (--n_lo <= 0) { // empty?
#ifdef DEBUG
if (trace_level >= TRACE_DUMP) dump_array("append right", right, n_hi, 0, 0, length);
#endif
copy(store, right, n_hi); // append remained data
break;
}
}
else {
#ifdef DEBUG
if (trace_level >= TRACE_DUMP) dump_array("merge right", right, 1, 0, 0, length);
#endif
copy(store, right, 1); store += length; right += length;
if (--n_hi <= 0) {
#ifdef DEBUG
if (trace_level >= TRACE_DUMP) dump_array("append left", left, n_lo, 0, 0, length);
#endif
copy(store, left, n_lo);
break;
}
}
}
#ifdef DEBUG
if (trace_level >= TRACE_DUMP) dump_array("sort() done.", dst, nmemb, 0, 0, length);
#endif
}
void merge_array(void *base, size_t nmemb, size_t size, int (*compare)(const void *, const void *)) {
#ifdef DEBUG
if (trace_level >= TRACE_DUMP) fprintf(OUT, "merge_array() nmemb = %s\n", dump_size_t(NULL, nmemb));
#endif
if (nmemb <= 1) return;
void *dup = calloc(nmemb, size);
if (dup != NULL) {
length = size; comp = compare;
memcpy(dup, base, nmemb * size);
sort(base, dup, nmemb);
free(dup);
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
int fact(int val){
int res = 1;
for(int i=val;i>0;i--){
res *= i;
}
return res;
}
float c(int n ,int r){
int t1, t2, t3;
t1 = fact(n);
t2 = fact(r);
t3 = fact(n-r);
return t1/(t2*t3);
}
float pascalTriangleC(int n ,int r){
if(r == 0 || n == r)
return 1;
else
return pascalTriangleC(n-1,r-1) + pascalTriangleC(n-1,r);
}
int main()
{
printf("\n%f",c(5,2) );
printf("\n%f",pascalTriangleC(5,2) );
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* length_conversion1.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vsteffen <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/01 19:35:47 by vsteffen #+# #+# */
/* Updated: 2018/03/01 19:35:51 by vsteffen ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
void detect_length_mod_hh2(t_data *data, char conversion)
{
if (conversion == 'U')
transform_u(data->current, (unsigned long int)va_arg(data->ap, \
unsigned long int));
else if (conversion == 'n')
transform_n(data, (intmax_t *)va_arg(data->ap, signed char *));
else if (conversion == 'p')
transform_p(data->current, va_arg(data->ap, void *));
else if (conversion == 'C')
transform_wide_c(data, data->current, \
(wchar_t)va_arg(data->ap, wint_t));
else if (conversion == 'S')
transform_wide_s(data, data->current, va_arg(data->ap, wchar_t *));
else
data->error = 1;
}
void detect_length_mod_hh1(t_data *data, char conversion)
{
if (conversion == 'd' || conversion == 'i')
transform_d(data->current, (signed char)va_arg(data->ap, int));
else if (conversion == 'o')
transform_o(data->current, (unsigned char)va_arg(data->ap, int));
else if (conversion == 'u')
transform_u(data->current, (unsigned char)va_arg(data->ap, int));
else if (conversion == 'x')
transform_x(data->current, (unsigned char)va_arg(data->ap, int));
else if (conversion == 'X')
transform_big_x(data->current, (unsigned char)va_arg(data->ap, int));
else if (conversion == 'D')
transform_d(data->current, (long int)va_arg(data->ap, long int));
else if (conversion == 'O')
transform_o(data->current, (unsigned long int)va_arg(data->ap, \
unsigned long int));
else
detect_length_mod_hh2(data, conversion);
}
void detect_length_mod_h2(t_data *data, char conversion)
{
if (conversion == 'U')
transform_u(data->current, (unsigned long int)va_arg(data->ap, \
unsigned long int));
else if (conversion == 'n')
transform_n(data, (intmax_t *)va_arg(data->ap, short *));
else if (conversion == 'p')
transform_p(data->current, va_arg(data->ap, void *));
else if (conversion == 'C')
transform_wide_c(data, data->current, \
(wchar_t)va_arg(data->ap, wint_t));
else if (conversion == 'S')
transform_wide_s(data, data->current, va_arg(data->ap, wchar_t *));
else
data->error = 1;
}
void detect_length_mod_h1(t_data *data, char conversion)
{
if (conversion == 'd' || conversion == 'i')
transform_d(data->current, (short)va_arg(data->ap, int));
else if (conversion == 'o')
transform_o(data->current, (unsigned short)va_arg(data->ap, int));
else if (conversion == 'u')
transform_u(data->current, (unsigned short)va_arg(data->ap, int));
else if (conversion == 'x')
transform_x(data->current, (unsigned short)va_arg(data->ap, int));
else if (conversion == 'X')
transform_big_x(data->current, (unsigned short)va_arg(data->ap, int));
else if (conversion == 'D')
transform_d(data->current, (long int)va_arg(data->ap, long int));
else if (conversion == 'O')
transform_o(data->current, (unsigned long int)va_arg(data->ap, \
unsigned long int));
else
detect_length_mod_h2(data, conversion);
}
|
C | // Aldán Creo Mariño, SOII 2020/21
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <math.h>
double suma = 0;
int T, M;
#define FALSE 0
#define TRUE 1
#define N 2
int turno;
int interesado[N];
void entrar_region(int proceso)
{
int otro;
otro = 1 - proceso;
interesado[proceso] = TRUE;
turno = proceso;
while (turno == proceso && interesado[otro] == TRUE) {};
}
void salir_region(int proceso)
{
interesado[proceso] = FALSE;
}
void sum(int hilo)
{
int j;
for (j = hilo; j <= M; j += T)
{
entrar_region(hilo);
suma = suma + j;
salir_region(hilo);
}
}
int main(int argc, char **argv)
{
int i;
if (argc != 4)
{
fprintf(stderr, "Debe especificarse: %s [M] [T] [valor correcto de la suma]\n", argv[0]);
}
M = atoi(argv[1]);
T = atoi(argv[2]);
double valor_correcto = (double)atoi(argv[3]);
pthread_t *ids = (pthread_t *)malloc(sizeof(pthread_t) * T);
for (i = 0; i < T; i++)
{
pthread_create(ids + i, NULL, sum, i);
}
for (i = 0; i < T; i++)
{
pthread_join(ids[i], NULL);
}
printf("%d,%d,%d\n", M, T, (int) fabs(valor_correcto - suma));
free(ids);
return (EXIT_SUCCESS);
}
|
C |
#include <stdarg.h>
#include <stdio.h>
int f(void* junk1, char junk2, int n, ...) {
va_list l;
va_start(l, n);
int ret = 0;
for(int i = 0; i < n; ++i) {
ret += va_arg(l, int);
}
va_end(l);
return ret;
}
int main(int argc, char** argv) {
return f(0, 2, 5, argc, argc, argc, argc, argc);
}
|
C | #include "functions.h"
int main(int argc, char *argv[]) {
/* Controllo del corretto inserimento di argomenti a riga di comando */
if(argc!=2){
printf("\nNumero errato di argomenti, si prega di scrivere solo il nome dell'eseguibile seguito dal nome del file\n\n");
exit(-1);
}
FILE *file; // Dichiarazione del file dal quale leggere la biblioteca
int n=0, anno, flag=0, key, flag_sconto; // Dichiarazione di variabili utili ai controlli
char *titolo, *editore, buffer[100]=""; // Dichiarazione delle variabili utili a contenere le stringhe
float prezzo, percentuale; // Dichiarazione delle variabili utili a impostare il prezzo dei libri
file=fopen(argv[1], "r"); // Apertura in lettura del file
/* Controllo della corretta apertura del file */
if(file==NULL) {
printf("Errore in apertura dei file \n");
exit(1);
}
/* Ciclio utile al conto di righe presenti nel file */
while(!feof(file)){
fgets(buffer, 100, file);
titolo=malloc(strlen(buffer));
strcpy(titolo, dropN(buffer));
fgets(buffer, 100, file);
editore=malloc(strlen(buffer));
fscanf(file,"%d\n",&anno);
fscanf(file,"%f\n",&prezzo);
n++;
}
Libro *biblioteca=malloc(sizeof(Libro)*n); // Dichiarazione e allocazione dinamica di un numero di puntatori all'ADT Libro pari ad n
/* Controllo della corretta allocazione di memoria */
if (biblioteca == NULL) {
printf("\nError: Out Of Memory\n\n");
exit(EXIT_FAILURE);
}
rewind(file); // Rilettura del file dall'inizio
/* Ciclio utile al riempimento della biblioteca tramite il file */
for(int i=0; i<n; i++){
fgets(buffer, 100, file);
titolo=malloc(strlen(buffer));
strcpy(titolo, dropN(buffer));
fgets(buffer, 100, file);
editore=malloc(strlen(buffer));
strcpy(editore, dropN(buffer));
fscanf(file,"%d\n",&anno);
fscanf(file,"%f\n",&prezzo);
biblioteca[i] = creaLibro(titolo, editore, prezzo, anno);
}
/* Iterazione del menu, con annesso switch per gestire la scelta dell'utente. */
while(flag==0){
printf("\n\n1 -Ricerca del libro piu' antico;"
"\n2 -Ricerca del libro meno costoso;"
"\n3 -Stampare tutti i libri di un dato editore;"
"\n4 -Applicare un determinato sconto a tutti i libri di un determinato anno;"
"\n5 -Ricerca dei libri con il minor scarto di prezzo;"
"\n6 -Calcolo del costo totale dei libri di un dato anno;"
"\n7 -Rimozione di tutti i libri di un determinato anno dalla biblioteca;"
"\n0 -Chiude il programma\n");
/* Presa in input della scelta dell'utente */
printf("\nCosa si desidera fare? ");
scanf("%d", &key);
switch (key){
case 1:
libroPiuVecchio(biblioteca, n); // chiamata alla funzione libroPiuVecchio in caso l'utente immeta 1;
break;
case 2:
libroMenoCostoso(biblioteca, n); // chiamata alla funzione libroMenoCostoso in caso l'utente immeta 2;
break;
case 3:
/* Presa in input dell'editore da ricercare con annessa allocazione dinamica e copia della stringa dal buffer al puntatore*/
printf("\nInserire l'editore da cercare \t");
getchar();
fgets(buffer, 100, stdin);
editore=malloc(sizeof(char*)*strlen(buffer));
strcpy(editore, dropN(buffer));
ricercaEditore(biblioteca, editore, n); // chiamata alla funzione ricerdaEditore in caso l'utente immeta 3;
break;
case 4:
/* Presa in input della percentuale di sconto da applicare e l'anno sul quale applicarla */
printf("\nInserire la percentuale di sconto da applicare: \t");
scanf("%f", &percentuale);
printf("\nInserire l'anno sul quale applicare lo sconto: \t");
scanf("%d", &anno);
flag_sconto=scontaLibri(biblioteca, anno, percentuale, n); // chiamata alla funzione scontaLibri in caso l'utente immeta 4;
/* In caso non fosse stato scontato alcun libro, il programma stamperebbe questo messaggio */
if(flag_sconto==1){
printf("\n\nOps, potrebbe essere stato riscontrato un errore");
}
break;
case 5:
trovaLibriPrezzoSimile(biblioteca, n); // chiamata alla funzione trovaLibriPrezzoSimile in caso l'utente immeta 5;
break;
case 6:
/* Presa in input dell'anno di cui calcolare il costo totale dei libri */
printf("\nInserire l'anno da calcolare: \t");
scanf("%d", &anno);
costoTotale(biblioteca, anno, n); // chiamata alla funzione trovaLibriPrezzoSimile in caso l'utente immeta 6;
break;
case 7:
/* Presa in input dell'annata di cui eliminare i libri */
printf("\nInserire l'annata dei libri da eliminare: \t");
scanf("%d", &anno);
n = eliminaLibri(biblioteca, anno, n); // chiamata alla funzione trovaLibriPrezzoSimile in caso l'utente immeta 7;
/* Nel caso in cui dovessero essere stati eliminati tutti i libri, verrebbe stampato questo messaggio con successiva chiusura del programma */
if(n==0){
printf("\nSono stati rimossi tutti i libri dalla biblioteca, arrivederci!\n ");
return 1;
}
break;
case 0:
flag=1; // Assegnamento del valore 1 al flag per uscire dal menu e chiudere il programma
break;
default:
printf("\n\nSi prega di selezionare una delle opzioni\n\n"); // stampa di un messaggio di errore nel caso in cui non dovesse essere stato immesso nessun input corrispondente a funzioni;
break;
}
}
/* Chiusura del programma */
fclose(file);
free(biblioteca);
printf("\n");
system("PAUSE");
return 0;
}
|
C | #include "sensor.h"
#include "motor.h"
int main(void)
{
_delay_ms(3000); // 3초후 동작
int error_val;
sensor_init(); // 포트C를 센서 입력으로 설정
motor1_init();
motor2_init();
while (1)
{
error_val = get_error(get_sensor()); // 에러값 저장 (-3 ~ +3)
motor1_get_spd(error_val);
motor2_get_spd(error_val);
_delay_ms(1);
}
return 0;
}
/*
#include "sensor.h"
#include "motor.h"
#define NOR_SPD 550 // 실제 동작 실험하고 조정
#define CH_SPD 85
int main(void)
{
int error_val;
int cnt = 0;
int spd1 , spd2;
sensor_init(); // 포트C를 센서 입력으로 설정
usart0_init();
while (1)
{
error_val = get_error(get_sensor()); // 에러값 저장 (-3 ~ +3)
if(error_val != 0) // 라인이 기울어져 있을때
{
motor1_init(spd1 = NOR_SPD - (error_val * CH_SPD));
motor2_init(spd2 = NOR_SPD + (error_val * CH_SPD));
}
else
{
motor1_init(spd1 = NOR_SPD);
motor2_init(spd2 = NOR_SPD);
}
if(cnt == 0)
{
ISR_active();
cnt++;
}
}
return 0;
}
*/
|
C | #include<stdio.h>
int main()
{
int a=023; // 0 before a number is octal
int b=0x23;
printf("octal 023 is %d in decimal\n",a);
printf("hexadecimal 0x23 is %d in decimal\n",b);
printf("Size of 23L is %d",sizeof(23L));
return 0;
} |
C | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_2__ TYPE_1__ ;
/* Type definitions */
struct termp {TYPE_1__* ps; } ;
struct TYPE_2__ {int flags; char* psmarg; int /*<<< orphan*/ psmargcur; int /*<<< orphan*/ pdfbytes; } ;
/* Variables and functions */
int PS_MARGINS ;
int /*<<< orphan*/ ps_growbuf (struct termp*,int) ;
int /*<<< orphan*/ putchar (char) ;
__attribute__((used)) static void
ps_putchar(struct termp *p, char c)
{
int pos;
/* See ps_printf(). */
if ( ! (PS_MARGINS & p->ps->flags)) {
putchar(c);
p->ps->pdfbytes++;
return;
}
ps_growbuf(p, 2);
pos = (int)p->ps->psmargcur++;
p->ps->psmarg[pos++] = c;
p->ps->psmarg[pos] = '\0';
} |
C | #include <stdio.h>
int n, s;
int z[401][401];
int main() {
scanf("%d %d", &n, &s);
for (int i = 1, a, b; i <= s; i++) {
scanf("%d %d", &a, &b);
z[a][b] = -1;
z[b][a] = 1;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
for (int k = 1; k <= n; k++) {
if (z[j][i] && (z[j][i] == z[i][k]))
z[j][k] = z[j][i];
}
}
}
scanf("%d", &s);
for (int i = 1, a, b, t; i <= s; i++) {
scanf("%d %d", &a, &b);
printf("%d\n", z[a][b]);
}
return 0;
} |
C | #include<stdio.h>
#include<stdlib.h>
int main()
{
int i,j,k,T,minx,minn,bus,b[1001],ch,cm,th[1001],tm[1001],tn[1001];
scanf("%d",&T);
for(i=1;i<=T;i++)
{
scanf("%d %d:%d",&bus,&ch,&cm);
for(j=0;j<bus;j++)
{
scanf("%d:%d %d",&th[j],&tm[j],&tn[j]);
}
minx=100000000;
for(j=0;j<bus;j++)
{
if(ch>th[j])
{
minn=24-ch+th[j];
minn=minn*60;
minn=minn+(tm[j]-cm)+tn[j];
}
else if(ch==th[j]&&tm[j]<cm)
{
minn=24;
minn=minn*60;
minn=minn+(tm[j]-cm)+tn[j];
}
else
{
minn=th[j]-ch;
minn=minn*60;
minn=minn+(tm[j]-cm)+tn[j];
}
if(minn<minx)
minx=minn;
}
printf("Case %d: %d\n",i,minx);
}
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* :::::::: */
/* get_next_line.c :+: :+: */
/* +:+ */
/* By: mvan-hou <[email protected]> +#+ */
/* +#+ */
/* Created: 2019/04/30 16:00:12 by mvan-hou #+# #+# */
/* Updated: 2019/07/21 20:10:10 by mvan-hou ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
int find_next_line(char *str, char *n, char **remainder)
{
n = ft_strchr(str, '\n');
if (n)
{
if (*remainder)
free(*remainder);
*remainder = ft_strdup(n + 1);
if (!(*remainder))
return (-1);
*n = '\0';
}
return (0);
}
int add_to_line(char *buf, char **line)
{
char *temp;
size_t len;
len = ft_strlen(*line);
temp = ft_strndup(*line, len);
if (!temp)
return (-1);
free(*line);
*line = ft_strnjoin(temp, buf, len, BUFF_SIZE);
if (!(*line))
return (-1);
free(temp);
return (0);
}
int read_file(const int fd, char **remainder, char **line)
{
char buf[BUFF_SIZE + 1];
char *n;
int ret;
ret = 1;
while (ret > 0)
{
ft_bzero(buf, BUFF_SIZE + 1);
ret = read(fd, buf, BUFF_SIZE);
if (ret < 0)
return (-1);
n = ft_strchr(buf, '\n');
if (find_next_line(buf, n, remainder) == -1)
return (-1);
if (add_to_line(buf, line) == -1)
return (-1);
if (ret == 0 && ft_strlen(*line) > 0)
return (1);
if (n)
return (1);
}
return (0);
}
int check_remainder(int fd, char **remainder, char **line)
{
char *temp;
char *n;
size_t len;
len = ft_strlen(remainder[fd]);
temp = ft_strndup(remainder[fd], len);
if (!temp)
return (-1);
n = ft_strchr(temp, '\n');
if (find_next_line(temp, n, &remainder[fd]) == -1)
return (-1);
if (!n)
remainder[fd] = NULL;
free(*line);
*line = ft_strndup(temp, len);
if (!(*line))
return (-1);
free(temp);
return (0);
}
int get_next_line(const int fd, char **line)
{
static char *remainder[4096];
char buf[BUFF_SIZE + 1];
if (fd < 0 || fd > 4095 || !line || read(fd, buf, 0) < 0)
return (-1);
*line = ft_strnew(0);
if (!(*line))
return (-1);
if (remainder[fd])
{
if (check_remainder(fd, remainder, line) == -1)
return (-1);
}
if (!remainder[fd])
return (read_file(fd, &remainder[fd], line));
if (remainder[fd])
return (1);
return (0);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
void selectionSort(int size, int arr[]) {
int temp = 0, max = 0;
for(int i = 1; i < size; i++)
if(arr[i] > arr[max])
max = i;
temp = arr[size - 1];
arr[size - 1] = arr[max];
arr[max] = temp;
if(size != 2)
selectionSort(size - 1, arr);
}
int main(void) {
int i;
srand(time(NULL));
i = (rand()%20)+1;
int arr[i];
for(int j = 0; j < i; j++){
arr[j] = (rand()%100)+1;
printf("%d", arr[j]);
if(j != i - 1)
printf(" ");
else
puts("");
}
puts("");
selectionSort(i, arr);
for(int j = 0; j < i; j++){
printf("%d", arr[j]);
if(j != i - 1)
printf(" ");
else
puts("");
}
return 0;
}
|
C | //Project 3B
#include <functions.h>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//File read and write functions
void ReadImage(char *filename, Image &output)
{
FILE *f_in;
char magicNum[128];
int width, height, maxval;
Pixel *aBuffer;
f_in = fopen(filename, "rb");
if(!f_in)
{
printf("Input file could not open \n");
return;
}
/* Reading the header of the file */
fscanf(f_in, "%s\n%d %d\n%d\n", magicNum, &width, &height, &maxval);
if (strcmp(magicNum, "P6") != 0)
{
fprintf(stderr, "Input file %s is not a PNM file of type P6\n", filename);
return;
}
aBuffer = new Pixel[width*height];
/* Reading the buffer */
fread(aBuffer, sizeof(Pixel), width*height, f_in);
output.ResetSize(width, height);
output.setBuffer(aBuffer);
fclose(f_in);
free(aBuffer);
}
void WriteImage(char *filename, Image &img)
{
FILE *f_out = fopen(filename, "wb");
Pixel *aBuffer;
if (!f_out)
{
printf("Output file could not open \n");
return;
}
/*Writing header */
fprintf(f_out, "%s\n%d %d\n%d\n", "P6", img.getWidth(), img.getHeight(), 255);
/*Writing Buffer*/
fwrite(img.getBuffer(), sizeof(Pixel), img.getWidth() * img.getHeight(), f_out);
fclose(f_out);
}
//Image manipulation functions
void HalfSize(Image &input, Image &output)
{
output.ResetSize(input.getWidth() / 2, input.getHeight() / 2);
output.buffer = new Pixel[output.getHeight() * output.getWidth()];
int in = 0, out = 0;
for (int i = 0; i < output.getHeight(); i++)
{
for(int j = 0; j < output.getWidth(); j++)
{
in = i*2*input.getWidth()+j*2;
out = i*output.getWidth()+j;
output.buffer[out] = input.buffer[in];
}
}
}
void LeftRightCombine(Image &leftInput, Image &rightinput, Image &output)
{
int leftWidth = leftInput.getWidth();
int rightWidth = rightinput.getWidth();
int totalWidth = leftWidth + rightWidth;
int height = leftInput.getHeight();
output.ResetSize(totalWidth, height);
output.buffer = new Pixel[totalWidth * height];
for( int i = 0; i < totalWidth; i++)
{
for(int j = 0; j < height; j++)
{
if(i < leftWidth)
{
output.buffer[j*totalWidth+i] = leftInput.buffer[j*leftWidth+i];
}
else
{
output.buffer[j*totalWidth+i] = rightinput.buffer[j*leftWidth+i];
}
}
}
}
void TopBottomCombine(Image &topInput, Image &bottomInput, Image &output)
{
int topWidth = topInput.getWidth();
int topHeight = topInput.getHeight();
int bottomWidth = bottomInput.getWidth();
int bottomHeight = bottomInput.getHeight();
int totalHeight = topHeight + bottomHeight;
int totalWidth = (topWidth + bottomWidth) / 2;
output.ResetSize(totalWidth,totalHeight);
if (topWidth != bottomWidth)
{
printf("Error: inputs have different widths. \n");
}
output.buffer = new Pixel[totalHeight * totalWidth];
for (int i = 0; i < topInput.getWidth() * topInput.getHeight(); i++)
{
output.buffer[i] = topInput.buffer[i];
}
for (int i = 0; i < topInput.getWidth() * topInput.getHeight(); i++)
{
output.buffer[topInput.getWidth() * topInput.getHeight() + i] = bottomInput.buffer[i];
}
}
void Blend(Image &input1, Image &input2, double factor, Image &output)
{
int width1 = input1.getWidth();
int height1 = input1.getHeight();
int width2 = input2.getWidth();
int height2 = input2.getHeight();
int totalHeight = (height1 + height2) / 2;
int totalWidth = (width1 + width2) / 2;
//float factor = f;
output.ResetSize(totalWidth, totalHeight);
if (width1 != width2 && height1 != height2)
{
printf("Error: inputs have different heights and widths\n");
}
output.buffer = new Pixel[totalHeight * totalWidth];
for(int i = 0; i < output.getWidth() * output.getHeight(); i++)
{
output.buffer[i].r = input1.buffer[i].r * factor + input2.buffer[i].r * (1 - factor);
output.buffer[i].g = input1.buffer[i].g * factor + input2.buffer[i].g * (1 - factor);
output.buffer[i].b = input1.buffer[i].b * factor + input2.buffer[i].b * (1 - factor);
}
}
|
C | /*
Maksymilian Mastalerz(0956502)
[email protected]
*/
#include <stdio.h>
#include <stdlib.h>
#include "HashTableAPI.h"
#include "functions.h"
/**Function for creating a node for the hash table.
*@pre Node must be cast to void pointer before being added.
*@post Node is valid and able to be added to the hash table
*@param key integer that represents the data (eg 35->"hello")
*@param data is a generic pointer to any data type.
*@return returns a node for the hash table
**/
Node *createNode(int key, void *data) {
Node *newNode = malloc(sizeof(Node));
newNode->next = NULL;
newNode->key = key;
newNode->data = data;
return newNode;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *pi;
void prefix(char *str, int ind)
{
int i, t = 0;
pi[0] = 0;
for (i = ind; i < strlen(str); i++) {
//t = pi[t - 1];
while ((t > 0) && (str[t] != str[i]))
t = pi[t - 1];
if (str[t] == str[i])
t++;
pi[i] = t;
}
}
void res (char *str, char *str_2, int ind)
{
int i, t = 0, k = strlen(str);
for (i = ind; i < strlen(str_2); i++) {
//t = pi[t - 1];
while ((t > 0) && (str[t] != str_2[i]))
t = pi[t - 1];
if (str[t] == str_2[i])
t++;
if (t == k) {
if (i - k + 1 >= 0) {
printf("%d ", i - k + 1);
}
}
}
printf("\n");
}
void kmpsubst(char *s, char *t)
{
int i = 1, l, real_index;
//printf("%s\n%s\n", s, t);
char *s_res;
l = strlen(s) + strlen(t) + 1;
pi = (int*)malloc(l * sizeof(int));
//s_res = (char*)malloc((l + 1) * sizeof(char));
prefix (s, i);
res (s, t, i-1);
free(pi);
//free(s_res);
}
int main(int argc, char **argv)
{
//char a[100];
//scanf("%s", a);
// char b[100];
//scanf("%s", b);
kmpsubst(argv[1], argv[2]);
//kmpsubst (a, b);
return 0;
} |
C | #ifndef TYPES_H_
#define TYPES_H_
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <commons/log.h>
#include <commons/collections/queue.h>
#include <commons/collections/list.h>
#include <commons/string.h>
#include <ensalada/validacion.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <signal.h>
#include <unistd.h>
#include <ensalada/dtb.h>
static int contador_id_dtb = 1;
typedef enum{
EJECUTAR,
STATUS,
FINALIZAR,
METRICAS,
EXIT
} tipo_accion_consola_safa;
typedef struct{
tipo_accion_consola_safa accion;
char* argumento;
}operacionConsolaSafa;
/*
* @NAME: string_to_accion
* @DESC: convierte el string en un entero que representa el tipo de operacion
*/
tipo_accion_consola_safa string_to_accion(char* string);
/*
* @NAME: parsear_linea
* @ARG: linea que se quiere parsear
* @RET: estructura con la operacion parseada
*/
operacionConsolaSafa* parsear_linea(char* linea);
/*
* @NAME: destroy_operacion
* @DESC: libera la memoria de la operacion
*/
void destroy_operacion(operacionConsolaSafa* op_safa);
/*
* @NAME: ejecutar_linea
* @ARG: linea que se quiere ejecutar
* @DESC: llama a la funcion correspondiente a la operacion que se quiere realizar
* @RET: void
*/
void ejecutar_linea(char* linea);
/*
* @NAME: consola_safa
* @DESC: recibir las operaciones por teclado y mostrar resultado
*/
void* consola_safa(void*);
/*********************************
**** Funciones de la consola ****
*********************************/
void con_ejecutar(char* ruta_escriptorio);
void con_status(int id_DTB);
void con_finalizar(int id_DTB);
void con_metricas(int id_DTB);
void con_pausar(void);
void con_resumir(void);
/*
* @NAME: sig_handler
* @DESC: Maneja las interrupciones para finalizar liberando la memoria
*/
void sig_handler(int signo);
/*
* @NAME: exit_gracefully
* @DESC: liberar la memoria para finalizar correctamente
*/
void exit_gracefully();
#endif /* TYPES_H_ */
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* read.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vvysotsk <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/02/02 17:04:09 by vvysotsk #+# #+# */
/* Updated: 2018/02/02 17:04:10 by vvysotsk ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
static int ft_count_tetri(const char *str)
{
int dot;
int sharp;
int end_line;
int index;
index = 0;
dot = 0;
sharp = 0;
end_line = 0;
while (str[index])
{
if (str[index] == '.')
dot++;
else if (str[index] == '#')
sharp++;
else if (str[index] == '\n')
end_line++;
else
ft_error();
index++;
}
if (sharp < 4 || dot % 4 || sharp % 4 || (end_line + 1) % 5)
ft_error();
return (sharp / 4);
}
char **ft_set_char(t_tetri *list, char **result, int max)
{
int x;
int y;
int index;
y = 0;
index = 0;
while (y < max)
{
x = 0;
while (x < max)
{
if (list->x[index] == x && list->y[index] == y)
{
result[y][x] = list->c;
index++;
}
x++;
}
result[y][x] = '\0';
y++;
}
result[y] = NULL;
return (result);
}
static t_tetri *ft_coordinates(t_tetri *list)
{
list = ft_get_xy(list, ft_strsplit(list->str, '\n'));
return (list);
}
t_tetri *ft_save_block(const char *str, int index)
{
int count_tetri;
char c;
t_tetri *temp;
t_tetri *buff;
count_tetri = ft_count_tetri(str);
c = 'A';
if (!(temp = (t_tetri*)malloc(sizeof(t_tetri))))
return (NULL);
buff = temp;
while (count_tetri-- > 0)
{
temp->str = ft_strndup(&str[index], 20);
ft_check(temp->str);
temp->c = c++;
temp = ft_coordinates(temp);
temp = ft_update_xy(temp);
index += 21;
ft_check_char(str[index - 1]);
if (!(temp->next = (t_tetri *)malloc(sizeof(t_tetri))))
return (NULL);
temp = temp->next;
}
temp->next = NULL;
return (buff);
}
char *ft_reading(char *str)
{
int fd;
int index;
char *buffer;
index = 0;
fd = open(str, O_RDONLY);
if (fd == -1)
ft_error();
if (!(buffer = ft_strnew(546)))
ft_error();
read(fd, buffer, 546);
while (buffer[index])
index++;
if (index < 19)
ft_error();
close(fd);
return (buffer);
}
|
C | #include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>
#define PORT 8080
void getCreds(int sock, char *buffer, char *cmd)
{
memset(buffer,0,2048);
memset(cmd,0,2048);
for(int i = 0; i<2;i++)
{
read( sock , buffer, 2048);
printf("%s\n",buffer );
memset(buffer,0,2048);
// fflush(stdin);
// fgets(cmd,sizeof(cmd),stdin);
// int n = strcspn(cmd,"\n");
// cmd[n] = 0;
// printf("%d\n",n);
scanf("%s",cmd);
send(sock , cmd , strlen(cmd) , 0 );
memset(cmd,0,2048);
}
}
void send_file(FILE *fp, int sockfd){
int n;
char data[PATH_MAX] = {0};
// while(1) {
// fgets(data, PATH_MAX, fp);
// if (send(sockfd, data, sizeof(data), 0) == -1) {
// perror("[-]Error in sending file.");
// return;
// exit(1);
// }
// bzero(data, PATH_MAX);
// if(feof(fp))
// {
// printf("EOF\n");
// char *null;
// int value = send(sockfd,NULL, 0, 0);
// printf("%d\n",value);
// break;
// }
// }
// return;
bzero(data, PATH_MAX);
int fs_block_sz;
while((fs_block_sz = fread(data, sizeof(char), PATH_MAX, fp)) > 0)
{
if(send(sockfd, data, fs_block_sz, 0) < 0)
{
fprintf(stderr, "ERROR: Failed to send file. (errno = )\n");
break;
}
bzero(data, PATH_MAX);
}
//printf("Ok File from Client was Sent!\n");
}
int addFile(int sock, char *buffer, char *cmd)
{
for(int i = 0; i<4;i++)
{
memset(buffer,0,2048);
read( sock , buffer, 2048);
if(i != 3)printf("%s\n",buffer );
if(i !=3)
{
memset(cmd,0,2048);
scanf(" %[^\n]s",cmd);
// char ch;
// while ((ch = getchar()) != '\n' && ch != EOF);
// fflush(stdin);
// fgets(cmd,sizeof(cmd),stdin);
// int n = strcspn(cmd,"\n");
// cmd[n] = 0;
//printf("%d\n",n);
send(sock , cmd , strlen(cmd) , 0 );
}
else if(i==3)
{
if(!strcmp(buffer,"Downloading"))
{
//printf("%s\n",cmd);
FILE *fp;
fp = fopen(cmd, "r");
if (fp == NULL) {
perror("[-]Error in reading file.");
continue;
}
send_file(fp, sock);
fclose(fp);
memset(buffer,0,2048);
return 1;
}
else{
memset(buffer,0,2048);
memset(cmd,0,2048);
return 0;
break;
}
}
}
memset(buffer,0,2048);
memset(cmd,0,2048);
}
int receiveFile(int sock, char *fileName)
{
//printf("[Client] Receiveing file from Server and saving it as final.txt...");
char cwd[1024] = {0}, destName[2048] = {0}, revbuf[PATH_MAX] = {0};
getcwd(cwd,sizeof(cwd));
sprintf(destName,"%s/%s",cwd,fileName);
FILE *fr = fopen(destName, "wb");
if(fr == NULL)
printf("File %s Cannot be opened.\n", destName);
else
{
bzero(revbuf, PATH_MAX);
int fr_block_sz = 0;
while((fr_block_sz = recv(sock, revbuf, PATH_MAX, 0)) > 0)
{
int write_sz = fwrite(revbuf, sizeof(char), fr_block_sz, fr);
if(write_sz < fr_block_sz)
{
error("File write failed.\n");
}
bzero(revbuf, PATH_MAX);
if (fr_block_sz == 0 || fr_block_sz != PATH_MAX)
{
break;
}
}
if(fr_block_sz < 0)
{
if (errno == EAGAIN)
{
printf("recv() timed out.\n");
}
else
{
fprintf(stderr, "recv() failed due to errno = %d\n", errno);
}
}
//printf("Ok received from server!\n");
fclose(fr);
char stat[1024] = {0};
strcpy(stat,"finish");
send(sock,stat,sizeof(stat),0);
}
}
void recSee(int sock)
{
char bufRec[4096];
int recvSize;
bzero(bufRec, 4096) ;
// while((recvSize=read(sock, bufRec, 4096))>0)
// {
// printf("%d\n",recvSize);
// printf("%s\n", bufRec) ;
// bzero(bufRec, 4096) ;
// }
recvSize=read(sock, bufRec, 4096);
//printf("%d\n",recvSize);
printf("%s", bufRec) ;
bzero(bufRec, 4096) ;
// printf("%d\n",recvSize);
// char Stat[4096] = {0};
// strcpy(Stat,"Finish");
// send(sock,Stat,sizeof(Stat),0);
return;
}
int main(int argc, char const *argv[]) {
struct sockaddr_in address;
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
char buffer[2048] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) {
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}
char command[2048];
int menu = 1;
int loop = 0;
int Auth=0;
while (1)
{
//printf("Auth = %d\n",Auth);
if(menu)
{
valread = read( sock , buffer, 2048);
printf("%s\n",buffer );
memset(buffer,0,2048);
}
menu = 1;
memset(command,0,2048);
int cmdCount = 0;
const char *p=" ";
char *a,*b;
char fullCommand[2048] = {0},tempCommand[2048] = {0}, file[1024]={0};
//printf("first full = %s\n",fullCommand);
memset(fullCommand,0,sizeof(fullCommand));
// int ch;
//if(loop)while ((ch = getchar()) != '\n' && ch != EOF);
// fflush(stdin);
// fgets(fullCommand,sizeof(fullCommand),stdin);
// fullCommand[strcspn(fullCommand,"\n")] = 0;
scanf(" %[^\n]",fullCommand);
//printf("after fgets = %s\n",fullCommand);
strcpy(tempCommand,fullCommand);
for( a=strtok_r(tempCommand,p,&b) ; a!=NULL ; a=strtok_r(NULL,p,&b) ) {
if(cmdCount==0) strcpy(command,a);
else if(cmdCount == 1) strcpy(file,a);
cmdCount++;
}
//scanf("%s",command);
send(sock , fullCommand, strlen(fullCommand) , 0 );
for(int i = 0 ; i<strlen(command); i++)
{
command[i] = tolower(command[i]);
}
//printf("%s\n",command);
if(!strcmp(command,"register") && !Auth)
{
getCreds(sock, buffer,command);
//loop++;
// read( sock , buffer, 2048);
// memset(buffer,0,2048);
// read( sock , buffer, 2048);
// memset(buffer,0,2048);
}
else if(!strcmp(command,"login") && !Auth)
{
getCreds(sock, buffer,command);
//loop++;
read(sock,&Auth,sizeof(Auth));
//read( sock , buffer, 2048);
//memset(buffer,0,2048);
}
else if(!strcmp(command,"add")&& Auth)
{
if(!addFile(sock, buffer,command)) menu = 0;
}
else if(!strcmp(command,"download")&& Auth)
{
char sta[20] = {0},respond[1024] = {0};
memset(sta,0,sizeof(sta));
read( sock , sta, sizeof(sta));
strcpy(respond,"ok");
send(sock,respond,sizeof(respond),0);
//printf("%s\n",sta);
if(!strcmp(sta,"downloading"))receiveFile(sock,file);
}
else if(!strcmp(command,"delete")&& Auth)
{
}
else if(!strcmp(command,"see")&& Auth)
{
recSee(sock);
}
else if(!strcmp(command,"find")&&Auth)
{
int Stat = 0;
read(sock,&Stat,sizeof(Stat));
if(Stat) recSee(sock);
}
//printf("command message sent\n");
else if(!strcmp(command,"exit"))
{
printf("Bye!\n");
break;
}
memset(buffer,0,2048);
memset(command,0,2048);
// valread = read( sock , buffer, 2048);
// printf("%s\n",buffer );
}
return 0;
} |
C | #ifndef STUDENT_H
#define STUDENT_H
#include <stdio.h>
#include <string.h>
typedef struct Student{
int id;
char name[40];
}Student;
void printStudent(Student *s){
int c = 10;
printf("Name of student: %s\n", s->name);
printf("ID of student: %d\n", s->id);
printf("Inside printStudent, c = %d\n\n", c);
}
#endif /*!STUDENT_H*/
|
C | Malloc = Memory Allocation
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <locale.h>
int main(){
setlocale(LC_ALL, "Portuguese");
int* vetor = (int*) malloc(20); //Malloc alocação de bytes na memória, nesse caso, 20bytes
if(vetor == NULL){
printf("Memória Insuficiente!\n");
}
else{
printf("20 Bytes de memória foram alocados para um ponteiro inteiro!\n");
}
return 0;
}
|
C | static unsigned next_pow2(unsigned v)
{
#if defined(__GNUC__) && defined(__i386)
if (v <= 2) return v;
__asm__("bsrl %1, %0" : "=r" (v) : "r" (v-1));
return 2 << v; // smallest pow-of-2 >= v
#else
v--; // from bit twiddling hacks
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
return v + 1;
#endif
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* term.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ezonda <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/28 23:26:44 by ezonda #+# #+# */
/* Updated: 2019/07/10 10:22:30 by ezonda ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_select.h"
void clear_display(t_var *data)
{
char *res;
if ((res = tgetstr("cl", NULL)) == NULL)
return ;
tputs(res, 0, ft_putchar_v2);
}
int hide_cursor(int mod)
{
char *res;
if (mod == 0)
{
if ((res = tgetstr("vi", NULL)) == NULL)
return (0);
tputs(res, 0, ft_putchar_v2);
}
else
{
if ((res = tgetstr("ve", NULL)) == NULL)
return (0);
tputs(res, 0, ft_putchar_v2);
}
return (0);
}
void get_winsize(t_var *data)
{
int i;
int width;
i = 1;
data->char_count = 0;
width = count_words(data);
while (data->args[i])
{
data->char_count += ft_strlen(data->args[i]);
i++;
}
ioctl(STDIN_FILENO, TIOCGWINSZ, &wind);
data->nb_cols = wind.ws_col;
data->nb_rows = data->nb_args / count_words(data) + 1;
}
void set_termcanon(t_var *data)
{
char buffer[256];
if (tgetent(buffer, getenv("TERM")) <= 0)
return ;
if (tcgetattr(0, &term) == -1)
return ;
term.c_lflag &= (~(ICANON | ECHO));
if (tcsetattr(0, TCSANOW, &term) == -1)
return ;
hide_cursor(0);
clear_display(data);
get_winsize(data);
display(data);
}
double count_words(t_var *data)
{
int i;
int max_len;
int words;
i = 1;
max_len = 0;
while (data->args[i])
{
if (ft_strlen(data->args[i]) > max_len)
max_len = ft_strlen(data->args[i]);
i++;
}
max_len++;
words = data->nb_cols / max_len;
return (words);
}
|
C | #include "main.h"
/**
* _strlen - to find the length of a string
* @s: points to the string to check
* Return: void
*/
int _strlen(char *s)
{
int i = 0;
while (s[i])
i++;
return (i);
}
|
C | /*
* =====================================================================================
*
* Filename: offer-levelOrder.c
*
* Description:
*
* Version: 1.0
* Created: 2020/09/20 15时51分43秒
* Revision: none
* Compiler: gcc
*
* Author: YOUR NAME (),
* Organization:
*
* =====================================================================================
*/
#include <stdlib.h>
/**
* Definition for a Node.
* struct Node {
* int val;
* int numChildren;
* struct Node** children;
* };
*/
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
#define MAX_NODES 5000
#define MAX_DEEPS 1000
typedef struct Node *Elemtype;
typedef struct {
Elemtype *data;
int capacity;
int front;
int rear;
int size;
}Queue;
Queue q;
void init(Queue *q, int capacity) {
q->data = (Elemtype *)malloc(sizeof(Elemtype) * capacity);
q->capacity = capacity;
q->front = 0;
q->rear = 0;
q->size = 0;
}
void uninit(Queue *q) {
free(q->data);
q->capacity = 0;
q->front = 0;
q->rear = 0;
q->size = 0;
}
void enQueue(Queue *q, const Elemtype e) {
q->data[q->rear] = e;
q->rear = (q->rear + 1) % q->capacity;
q->size++;
}
void deQueue(Queue *q, Elemtype *e) {
*e = q->data[q->front];
q->front = (q->front + 1) % q->capacity;
q->size--;
}
int getQueueSize(Queue *q) {
return q->size;
}
int empty(Queue *q) {
int ret = q->size == 0 ? 1 : 0;
return ret;
}
void helper(struct Node *root, int *returnSize, int **returnColumnSizes, int **res) {
enQueue(&q, root);
while (!empty(&q)) {
int nums = getQueueSize(&q);
(*returnColumnSizes)[*returnSize] = nums;
res[*returnSize] = (int *)malloc(sizeof(int) * nums);
for (int i = 0; i < nums; i++) {
struct Node *node;
deQueue(&q, &node);
res[*returnSize][i] = node->val;
for (int j = 0; j < node->numChildren; j++) {
enQueue(&q, node->children[j]);
}
}
(*returnSize)++;
}
}
int** levelOrder(struct Node* root, int* returnSize, int** returnColumnSizes) {
*returnSize = 0;
if (root == NULL) {
*returnColumnSizes = NULL;
return NULL;
}
init(&q, MAX_NODES);
int **res = (int **)malloc(sizeof(int *) * MAX_DEEPS);
*returnColumnSizes = (int *)malloc(sizeof(int *) * MAX_DEEPS);
helper(root, returnSize, returnColumnSizes, res);
return res;
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include "unsigned_int_operation.h"
#include "utils.h"
void test_equal_unsigned_int_add(unsigned int a, unsigned int b) {
unsigned int add_true = a + b;
bool * a_bits = num_to_bits((void *)&a);
bool * b_bits = num_to_bits((void *)&b);
bool * add_bits = (bool *)malloc(sizeof(bool) * 32);
unsigned_int_add(a_bits, b_bits, add_bits);
unsigned int add_actual = *(unsigned int *)(bits_to_num(add_bits));
if (add_true != add_actual)
printf("Test fail for %u + %u, true: %x, actual: %x\n", a, b, add_true, add_actual);
}
void test_unsigned_int_add() {
printf("Test unsigned int add\n");
// trivial cases
test_equal_unsigned_int_add(0, 0);
test_equal_unsigned_int_add(1, 0);
test_equal_unsigned_int_add(5, 3);
test_equal_unsigned_int_add(20, 3);
// overflow cases
test_equal_unsigned_int_add(0xffffffff, 0x00000002);
test_equal_unsigned_int_add(0xf0000000, 0xf0000000);
// random cases
for (int i = 0; i < 100; ++i)
test_equal_unsigned_int_add(rand(), rand());
printf("Success!\n");
}
void test_equal_unsigned_int_sub(unsigned int a, unsigned int b) {
unsigned int sub_true = a - b;
bool * a_bits = num_to_bits((void *)&a);
bool * b_bits = num_to_bits((void *)&b);
bool * sub_bits = (bool *)malloc(sizeof(bool) * 32);
unsigned_int_sub(a_bits, b_bits, sub_bits);
unsigned int sub_actual = *(unsigned int *)(bits_to_num(sub_bits));
if (sub_true != sub_actual)
printf("Test fail for %u - %u, true: %x, actual: %x\n", a, b, sub_true, sub_actual);
}
void test_unsigned_int_sub() {
printf("Test unsigned int sub\n");
// trivial cases
test_equal_unsigned_int_sub(0, 0);
test_equal_unsigned_int_sub(1, 0);
test_equal_unsigned_int_sub(5, 3);
test_equal_unsigned_int_sub(20, 3);
// overflow cases
test_equal_unsigned_int_sub(0x00000000, 0x00000002);
test_equal_unsigned_int_sub(0xf0000000, 0xff000000);
// random cases
for (int i = 0; i < 100; ++i)
test_equal_unsigned_int_sub(rand(), rand());
printf("Success!\n");
}
void test_equal_unsigned_int_mul(unsigned int a, unsigned int b) {
unsigned int mul_true = a * b;
bool * a_bits = num_to_bits((void *)&a);
bool * b_bits = num_to_bits((void *)&b);
bool * mul_bits = (bool *)malloc(sizeof(bool) * 32);
unsigned_int_mul(a_bits, b_bits, mul_bits);
unsigned int mul_actual = *(unsigned int *)(bits_to_num(mul_bits));
if (mul_true != mul_actual)
printf("Test fail for %u * %u, true: %x, actual: %x\n", a, b, mul_true, mul_actual);
}
void test_unsigned_int_mul() {
printf("Test unsigned int mul\n");
// trivial cases
test_equal_unsigned_int_mul(0, 0);
test_equal_unsigned_int_mul(1, 0);
test_equal_unsigned_int_mul(5, 3);
test_equal_unsigned_int_mul(20, 3);
// overflow cases
test_equal_unsigned_int_mul(0xffffffff, 0x00000002);
test_equal_unsigned_int_mul(0x70000000, 0xff000000);
// random cases
for (int i = 0; i < 100; ++i)
test_equal_unsigned_int_mul(rand(), rand());
printf("Success!\n");
}
void test_equal_unsigned_int_div(unsigned int a, unsigned int b) {
unsigned int div_true = a / b;
bool * a_bits = num_to_bits((void *)&a);
bool * b_bits = num_to_bits((void *)&b);
bool * div_bits = (bool *)malloc(sizeof(bool) * 32);
unsigned_int_div(a_bits, b_bits, div_bits);
unsigned int div_actual = *(unsigned int *)(bits_to_num(div_bits));
if (div_true != div_actual)
printf("Test fail for %u / %u, true: %x, actual: %x\n", a, b, div_true, div_actual);
}
void test_unsigned_int_div() {
printf("Test unsigned int div\n");
// trivial cases
//test_equal_unsigned_int_div(0, 0);
//test_equal_unsigned_int_div(1, 0);
test_equal_unsigned_int_div(0, 1);
test_equal_unsigned_int_div(5, 1);
test_equal_unsigned_int_div(4, 5);
test_equal_unsigned_int_div(20, 3);
// random cases
for (int i = 0; i < 100; ++i)
test_equal_unsigned_int_div(rand(), rand());
printf("Success!\n");
} |
C |
#include <stdio.h>
#include <stdlib.h>
void swap1(int *a, int *b){
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
void swap2(int *a, int *b){
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
int main(){
int a = 13;
int b = 7;
printf("%d = a and %d = b\n", a, b);
swap1(&a, &b);
printf("%d = a and %d = b\n", a, b);
swap2(&a, &b);
printf("%d = a and %d = b\n", a, b);
return 0;
} |
C | /* CS261- Assignment 1 - Q.2*/
/* Name: Matt Schreiber
* Date: 10-12-2013
* Solution description: Passes three values to foo(), which manipulates
* them in certain ways. Prints their initial
* values to the console, and also prints their
* values after being passed to foo().
*/
#include <stdio.h>
#include <stdlib.h>
int foo(int* a, int* b, int c){
/*Set a to double its original value*/
*a *= 2;
/*Set b to half its original value*/
*b /= 2;
/*Assign a+b to c*/
c = *a + *b;
/*Return c*/
return c;
}
int main(){
/*Declare three integers x,y and z and initialize them to 5, 6, 7 respectively*/
int x = 5, y = 6, z = 7;
/*Print the values of x, y and z*/
printf("x = %d, y = %d, & z = %d\n", x, y, z);
/*Call foo() appropriately, passing x,y,z as parameters*/
int f = foo(&x, &y, z);
/*Print the value returned by foo*/
printf("Value returned by foo() = %d\n", f);
/*Print the values of x, y and z again*/
printf("After running foo(), x = %d, y = %d, & z = %d\n", x, y, z);
/*Is the return value different than the value of z? Why?*/
/* The return value of foo() is not equal to z because the value
* foo() returns is the value of the variable c local to foo(),
* which was initially set to the value of z. Because z was passed
* by value, its value remains unchanged within the scope of main().
*/
return 0;
}
|
C | #include <stdio.h>
int maze(char[8][8], int x, int y, int x2, int y2,int visited[8][8]);
int main() {
char a[8][8] = {
{'x', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{'x', ' ', 'x', ' ', ' ', ' ', ' ', ' '},
{'x', ' ', 'x', ' ', ' ', ' ', ' ', ' '},
{'x', ' ', 'x', 'x', 'x', 'x', 'x', ' '},
{'x', ' ', 'x', ' ', ' ', ' ', ' ', ' '},
{'x', ' ', 'x', 'x', 'x', 'x', 'x', ' '},
{'x', ' ', 'x', ' ', ' ', ' ', ' ', ' '},
{'x', 'x', 'x', 'x', 'x', ' ', 'x', 'G'},
};
int visited[8][8] = {{0}};
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
visited[i][j] = -1;
}
}
int solve = maze(a, 1, 0, -1, -1,visited);
printf("Can solve %d", solve);
return 0;
}
int maze(char a[8][8], int x, int y, int x2, int y2,int visited[8][8]) {
printf("Trying %d,%d from %d,%d\n", x, y, x2, y2);
if (x < 0 || x > 7)return -1;
if (y < 0 || y > 7)return -1;
if (a[y][x] == 'x')return -1;
if (a[y][x] == 'G')return 1;
int contains = visited[y][x] == 1 ? 1 : -1;
if(contains == 1)return -1;
visited[y][x] = 1;
int l, r, d, u;
l = x - 1 != x2 ? maze(a, x - 1, y, x, y,visited) : -1;
r = x + 1 != x2 ? maze(a, x + 1, y, x, y,visited) : -1;
d = y - 1 != y2 ? maze(a, x, y - 1, x, y,visited) : -1;
u = y + 1 != y2 ? maze(a, x, y + 1, x, y,visited) : -1;
if (l == 1 || r == 1 || d == 1 || u == 1)return 1;
return -1;
} |
C | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
unsigned n = 0, i, total;
if (argc < 2) {
scanf("%u", &n);
} else {
n = atoi(argv[1]);
}
total = 0;
for (i = 1; i <= n; ++i) {
total += i;
#ifdef PRINT
if (i % 5 == 0) {
printf("%u\n", i);
}
#endif
}
printf("total: %u\n", total);
}
|
C | #include<stdio.h>
struct student
{
int rollno;
char name[20];
int percentage;
}student;
void main()
{
student rollno=1;
strcpy(student.name,"tamil");
student.percentage=92;
printf("rollno=%d",student.rollno);
printf("name=%s",student.name);
printf("percentage=%d",student.percentage);
} |
C | #include <linux/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <asm/io.h>
unsigned long *gpc0_conf;
unsigned long *gpc0_data;
//2,ʵprobe
int led_plat_drv_probe(struct platform_device * pdev )
{
struct resource *addr_res1,*addr_res2;
struct resource *irq_res;
int irqno;
printk("----------^_^ %s----------------\n",__FUNCTION__);
/*
1,ʵȫֶ
2,豸
3,豸ڵ
4,Ӳʼ-----ȡpdevеԴ
5,ʵfopsеĽӿ
*/
//ȡpdevеԴ
//1 --- pdev
//2 -- Դ
//3 -- Դı,Ŵ0ʼ
addr_res1 = platform_get_resource(pdev, IORESOURCE_MEM, 0);
gpc0_conf = ioremap(addr_res1->start, resource_size(addr_res1));
gpc0_data = gpc0_conf + 1;
//gpc0Ϊ
*gpc0_conf &= ~(0xff<<12);
*gpc0_conf |= 0x11<<12;
*gpc0_data |= 0x3 << 3;
addr_res2 = platform_get_resource(pdev, IORESOURCE_MEM, 1);
printk("addr_res2->start = 0x%x\n",addr_res2->start);
//ȡжԴ
irq_res = platform_get_resource(pdev, IORESOURCE_IRQ,0); //һ
printk("irq_res.start = %d\n",irq_res->start);
irqno = platform_get_irq(pdev, 0); //
printk("irqno = %d\n",irqno);
return 0;
}
int led_plat_drv_remove(struct platform_device * pdev)
{
printk("----------^_^ %s----------------\n",__FUNCTION__);
iounmap(gpc0_conf);
return 0;
}
const struct platform_device_id led_id_table[] = {
{"s5pv210_led",0x1234},
{"s3c2410_led",0x1122},
{"s3c6410_led",0x3344},
};
// 1pdrv
struct platform_driver led_pdrv = {
.probe = led_plat_drv_probe,
.remove = led_plat_drv_remove,
.driver = {
.name = "samsung led_drv", //Զ壬Ҫд,ƥɹʱ:ls /sys/bus/platform/drivers
},
.id_table = led_id_table,
};
static int __init led_plat_drv_init(void)
{
printk("----------^_^ %s----------------\n",__FUNCTION__);
// 3,עpdrv
return platform_driver_register(&led_pdrv);
}
static void __exit led_plat_drv_exit(void)
{
printk("----------^_^ %s----------------\n",__FUNCTION__);
//עpdrv
platform_driver_unregister(&led_pdrv);
}
module_init(led_plat_drv_init);
module_exit(led_plat_drv_exit);
MODULE_LICENSE("GPL");
|
C | #include "utils.h"
#include "pool.h"
Pool *create_pool(size_t item_size) {
Pool *q = s_malloc(sizeof(Pool));
q->item_num = 0;
q->item_size = item_size;
q->max_item_num = 0x100;
q->buf = s_malloc(q->max_item_num * q->item_size);
q->cur = q->buf;
q->free = delete_pool;
return q;
}
void *pool_use(Pool *p) {
if (p->item_num == p->max_item_num) {
p->max_item_num *= 2;
p->buf = s_realloc(p->buf, p->max_item_num * p->item_size);
}
void *res = p->buf + p->item_size * p->item_num;
p->item_num++;
return res;
}
void reset_iter(Pool *p) {
p->cur = p->buf;
}
void *pool_next(Pool *p) {
if (p->cur == p->buf + p->item_size * p->item_num) {
return NULL;
}
void *res = p->cur;
p->cur += p->item_size;
return res;
}
void *pool_get(Pool *p, size_t idx) {
return p->buf + idx * p->item_size;
}
size_t pool_idx(Pool *p, void *ptr) {
if (ptr == p->buf + p->item_size * p->item_num || (ptr - p->buf) % p->item_size != 0) {
panic(0, "internal error: pointer not belong to pool.");
}
return (ptr - p->buf) / p->item_size;
}
void *pool_peek(Pool *p) {
return p->cur;
}
void *pool_peek2(Pool *p) {
void *res = p->cur + p->item_size;
return res;
}
void delete_pool(Pool *p) {
free(p->buf);
free(p);
}
|
C | /*
6 Dados o número n de alunos de uma turma de Introdução aos
Autômatos a Pilha (MAC 414) e suas notas da primeira prova,
determinar a maior e a menor nota obtidas por essa turma (Nota
máxima = 100 e nota mínima = 0).
*/
#include <stdio.h>
int main()
{
// Variaveis
int NumAlunos, nota, maior, menor, i;
maior = 0;
menor = 100;
//Requerendo dados do usuario
printf("Informe a quantidade de alunos: \n");
scanf("%d", &NumAlunos);
// Verifica a maior e a menor nota entre os alunos
for(i=1; i <= NumAlunos; i++){
printf("\nInforme a nota de 0 a 100 %d ", i);
scanf("%d", ¬a);
if ( nota < menor){
menor = nota;
}
if (nota > maior){
maior = nota;
}
}
// Imprime resultados
printf("\nA menor nota foi %d", menor);
printf("\nA maior nota foi %d\n", maior);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _carta {
struct _carta *proximo;
int valor;
} CARTA;
typedef CARTA *PTR_CARTA;
typedef struct _baralho {
PTR_CARTA topo;
int tamanho;
} BARALHO;
typedef BARALHO *PTR_BARALHO;
int esta_vazio(PTR_BARALHO baralho){
return baralho->tamanho == 0 ? 1 : 0;
}
void inicializar(PTR_BARALHO baralho){
baralho->tamanho = 0;
baralho->topo = NULL;
}
PTR_BARALHO criar_baralho(){
PTR_BARALHO baralho = (PTR_BARALHO)malloc(sizeof(PTR_BARALHO));
inicializar(baralho);
return baralho;
}
void empilhador(PTR_BARALHO baralho, int valor){
PTR_CARTA carta = (PTR_CARTA)malloc(sizeof(PTR_CARTA));
carta->valor = valor;
carta->proximo = baralho->topo;
baralho->topo = carta;
baralho->tamanho++;
}
void despilhador(PTR_BARALHO baralho, int *outValor){
if (!esta_vazio(baralho)){
PTR_CARTA lixo = baralho->topo;
*outValor = lixo->valor;
baralho->topo = baralho->topo->proximo;
free(lixo);
baralho->tamanho--;
}
}
void criar_cartas(int *pcartas){
int i,j;
int x=0;
for(j=0; j<4; j++){
for(i=1; i<=13; i++){
if(i<10){
*(pcartas+x)=i;
}else{
*(pcartas+x)=10;
}
x++;
}
}
}
void embaralhar_baralho(int *pcartas){
int i,temp,random;
srand(time(NULL));
for (i=0;i<52;i++){
random=rand()%52;
temp=*(pcartas+i);
*(pcartas+i)=*(pcartas+random);
*(pcartas+random)=temp;
}
}
void empilhar_baralho(){
PTR_BARALHO baralho = criar_baralho();
int *pcartas;
int cartas[52];
pcartas=cartas;
criar_cartas(pcartas);
embaralhar_baralho(pcartas);
int i;
printf("\n\n");
for(i=0;i<52;i++){
empilhador(baralho,cartas[i]);
printf("%d\t",baralho->topo->valor);//esse print serve apenas como teste para ver se ta tudo funcionando
}
}
int main(){
empilhar_baralho();
getchar();
return 0;
}
|
C | #include <stdio.h>
#include <string.h>
char *ft_strncat(char *dest, char *src, int nb) {
int i, j;
j = strlen(dest);
for (i = 0; i < nb; i++){
dest[j] = src[i];
j++;
}
dest[j] = '\0';
return dest;
}
int main () {
char src[30] = "this is the source";
char dest[30] = "this is the destination";
int nb = 10;
printf("%s\n", ft_strncat(dest, src, nb));
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstclear.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lpaulo-d <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/31 01:36:04 by lpaulo-d #+# #+# */
/* Updated: 2021/06/01 22:27:34 by lpaulo-d ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void ft_lstclear(t_list **lst, void(*del)(void *))
{
t_list *index;
if (*lst == NULL)
return ;
while (*lst)
{
index = (*lst)->next;
ft_lstdelone(*lst, del);
*lst = index;
}
*lst = NULL;
}
/*
Limpa/Deleta toda a lista.
Com uma variavael temporaria para nao perder a lista.
É passado como parametro para a função ft_lstdelone o 'del' que seria
uma função de deletar como explicado na função delone.
*/ |
C | /**
* acdat.c - Double-Array Trie implement
*
* @author James Yin <[email protected]>
*/
#include "acdat.h"
#include <alib/collections/list/segarray.h>
#include <alib/object/list.h>
/* Trie 内部接口,仅限 Double-Array Trie 使用 */
size_t trie_size(trie_t self);
size_t trie_next_state_by_binary(trie_t self, size_t iNode, unsigned char key);
// Double-Array Trie
// ========================================================
const size_t DAT_ROOT_IDX = 255;
static inline dat_node_t dat_access_node(dat_t self, size_t index) {
return segarray_access(self->node_array, index);
}
static void dat_init_segment(segarray_t segarray, void* segment, size_t seg_size, size_t start_index, void* arg) {
dat_t datrie = (dat_t)arg;
/* 节点初始化 */
memset(segment, 0, segarray->node_size * seg_size);
for (size_t i = start_index + 255; i < start_index + seg_size - 255; ++i) {
dat_node_t node = segarray_access(segarray, i);
node->dat_free_next = i + 1;
node->dat_free_last = i - 1;
}
// segarray 是分段的,为索引转指针后不溢出,需要保留pad空间(掐头去尾)
for (size_t i = 0; i < 255; ++i) {
dat_node_t node = segarray_access(segarray, start_index + i);
node->check.idx = 1;
node = segarray_access(segarray, start_index + seg_size - 255 + i);
node->check.idx = 1;
}
((dat_node_t)segarray_access(segarray, start_index + 255))->dat_free_last = datrie->_sentinel->dat_free_last;
((dat_node_t)segarray_access(segarray, datrie->_sentinel->dat_free_last))->dat_free_next = start_index + 255;
((dat_node_t)segarray_access(segarray, start_index + seg_size - 256))->dat_free_next = 0;
datrie->_sentinel->dat_free_last = start_index + seg_size - 256;
}
static dat_node_t dat_access_node_with_alloc(dat_t self, size_t index) {
dat_node_t node = segarray_access_s(self->node_array, index);
if (node == NULL) {
size_t extend_size = (index + 1) - segarray_size(self->node_array);
if (segarray_extend(self->node_array, extend_size) != extend_size) {
fprintf(stderr, "dat: alloc nodepool failed.\nexit.\n");
exit(-1);
}
node = segarray_access(self->node_array, index);
}
return node;
}
typedef struct dat_ctor_dfs_ctx {
trie_node_t pNode, pChild;
} dat_ctor_dfs_ctx_s, *dat_ctor_dfs_ctx_t;
static void dat_construct_by_trie0(dat_t self, trie_t origin) {
// set dat index of root
origin->root->trie_datidx = DAT_ROOT_IDX;
segarray_t stack = segarray_construct_with_type(dat_ctor_dfs_ctx_s);
if (segarray_extend(stack, 2) != 2) {
fprintf(stderr, "dat: alloc ctor_dfs_ctx failed.\nexit.\n");
exit(-1);
}
dat_ctor_dfs_ctx_t ctx = (dat_ctor_dfs_ctx_t)segarray_access(stack, 1);
ctx->pNode = origin->root;
ctx->pChild = NULL;
size_t stack_top = 1;
while (stack_top > 0) { // dfs
ctx = (dat_ctor_dfs_ctx_t)segarray_access(stack, stack_top);
// first visit
if (ctx->pChild == NULL) {
trie_node_t pNode = ctx->pNode;
dat_node_t pDatNode = dat_access_node(self, pNode->trie_datidx);
pDatNode->value.raw = pNode->value;
// leaf node
if (pNode->trie_child <= 0) {
pDatNode->base.idx = 0;
// pop stack
stack_top--;
continue;
}
uint8_t child[256];
size_t len = 0;
// fill key of children
trie_node_t pChild = trie_access_node(origin, pNode->trie_child);
while (pChild != origin->root) {
child[len++] = pChild->key;
pChild = trie_access_node(origin, pChild->trie_brother);
}
size_t pos = self->_sentinel->dat_free_next;
while (1) {
size_t base, i;
/* 扩容 */
if (pos == 0) {
pos = self->_sentinel->dat_free_last;
if (segarray_extend(self->node_array, 256) != 256) {
fprintf(stderr, "alloc datnodepool failed: region full.\nexit.\n");
exit(-1);
}
pos = dat_access_node(self, pos)->dat_free_next;
}
/* 检查: pos容纳第一个子节点 */
base = pos - child[0];
for (i = 0; i < len; ++i) {
if (dat_access_node_with_alloc(self, base + child[i])->check.idx != 0) {
break;
}
}
/* base 分配成功 */
if (i >= len) {
pDatNode->base.idx = base;
for (i = 0, pChild = trie_access_node(origin, pNode->trie_child); i < len;
++i, pChild = trie_access_node(origin, pChild->trie_brother)) {
pChild->trie_datidx = base + child[i];
/* 分配子节点 */
dat_node_t pDatChild = dat_access_node(self, pChild->trie_datidx);
/* remove the node from free list */
dat_access_node(self, pDatChild->dat_free_next)->dat_free_last = pDatChild->dat_free_last;
dat_access_node(self, pDatChild->dat_free_last)->dat_free_next = pDatChild->dat_free_next;
// set fields
pDatChild->check.idx = pNode->trie_datidx;
pDatChild->value.raw = NULL;
}
break;
}
pos = dat_access_node(self, pos)->dat_free_next;
}
/* 构建子树 */
ctx->pChild = trie_access_node(origin, pNode->trie_child);
if (ctx->pChild != origin->root) {
// push stack
stack_top++;
if (segarray_size(stack) <= stack_top && segarray_extend(stack, 1) != 1) {
fprintf(stderr, "dat: alloc ctor_dfs_ctx failed.\nexit.\n");
exit(-1);
}
dat_ctor_dfs_ctx_t ctx2 = (dat_ctor_dfs_ctx_t)segarray_access(stack, stack_top);
ctx2->pNode = ctx->pChild;
ctx2->pChild = NULL;
continue;
}
} else {
/* 构建子树 */
ctx->pChild = trie_access_node(origin, ctx->pChild->trie_brother);
if (ctx->pChild != origin->root) {
// push stack
stack_top++;
dat_ctor_dfs_ctx_t ctx2 = (dat_ctor_dfs_ctx_t)segarray_access(stack, stack_top);
ctx2->pNode = ctx->pChild;
ctx2->pChild = NULL;
continue;
}
}
// pop stack
stack_top--;
}
segarray_destruct(stack);
}
static void dat_post_construct(dat_t self, trie_t origin) {
/* 添加占位内存,防止匹配时出现非法访问 */
// segarray_extend(self->node_array, 256);
// convert index to pointer
size_t len = trie_size(origin);
for (size_t index = 0; index < len; index++) {
trie_node_t pNode = trie_access_node(origin, index);
dat_node_t pDatNode = dat_access_node(self, pNode->trie_datidx);
pDatNode->check.ptr = dat_access_node(self, pDatNode->check.idx);
pDatNode->base.ptr = dat_access_node(self, pDatNode->base.idx);
pDatNode->failed.ptr = dat_access_node(self, pDatNode->failed.idx);
}
if (self->enable_automation) {
// 回溯优化
self->value_array = segarray_construct(sizeof(dat_value_s), NULL, NULL);
for (size_t index = 0; index < len; index++) { // bfs
trie_node_t pNode = trie_access_node(origin, index);
dat_node_t pDatNode = dat_access_node(self, pNode->trie_datidx);
if (pDatNode->value.raw != NULL) {
if (segarray_extend(self->value_array, 1) != 1) {
fprintf(stderr, "dat: alloc dat_value_s failed.\nexit.\n");
exit(-1);
}
dat_value_t value = (dat_value_t)segarray_access(self->value_array, segarray_size(self->value_array) - 1);
value->value = pDatNode->value.raw;
value->next = pDatNode->failed.ptr->value.linked;
pDatNode->value.linked = value;
} else {
pDatNode->value.linked = pDatNode->failed.ptr->value.linked;
}
}
}
}
dat_t dat_alloc() {
dat_t datrie = (dat_t)amalloc(sizeof(dat_s));
if (datrie == NULL) {
return NULL;
}
/* 节点初始化 */
datrie->enable_automation = false;
datrie->value_array = NULL;
dat_node_s dummy_node = {0};
datrie->_sentinel = &dummy_node;
datrie->node_array = segarray_construct(sizeof(dat_node_s), dat_init_segment, datrie);
segarray_extend(datrie->node_array, DAT_ROOT_IDX + 2);
datrie->_sentinel = dat_access_node(datrie, 0);
// set root node
datrie->root = dat_access_node(datrie, DAT_ROOT_IDX);
datrie->root->check.idx = DAT_ROOT_IDX;
datrie->root->value.raw = NULL;
// init free list
dat_access_node(datrie, dummy_node.dat_free_last)->dat_free_next = 0;
dat_access_node(datrie, DAT_ROOT_IDX + 1)->dat_free_last = 0;
datrie->_sentinel->dat_free_next = DAT_ROOT_IDX + 1;
datrie->_sentinel->dat_free_last = dummy_node.dat_free_last;
return datrie;
}
void dat_build_automation(dat_t self, trie_t origin) {
size_t index;
trie_node_t pNode = origin->root;
size_t iChild = pNode->trie_child;
while (iChild != 0) {
trie_node_t pChild = trie_access_node(origin, iChild);
// must before set trie_failed
iChild = pChild->trie_brother;
/* 设置 failed 域 */
pChild->trie_failed = 0;
dat_access_node(self, pChild->trie_datidx)->failed.idx = DAT_ROOT_IDX;
}
size_t len = trie_size(origin);
for (index = 1; index < len; index++) { // bfs
pNode = trie_access_node(origin, index);
iChild = pNode->trie_child;
while (iChild != 0) {
trie_node_t pChild = trie_access_node(origin, iChild);
unsigned char key = pChild->key;
size_t iFailed = pNode->trie_failed;
size_t match = trie_next_state_by_binary(origin, iFailed, key);
while (iFailed != 0 && match == 0) {
iFailed = trie_access_node(origin, iFailed)->trie_failed;
match = trie_next_state_by_binary(origin, iFailed, key);
}
// must before set trie_failed
iChild = pChild->trie_brother;
/* 设置 failed 域 */
pChild->trie_failed = match;
dat_access_node(self, pChild->trie_datidx)->failed.idx =
match == 0 ? DAT_ROOT_IDX : trie_access_node(origin, match)->trie_datidx;
}
}
}
void dat_destruct(dat_t dat, dat_node_free_f node_free_func) {
if (dat != NULL) {
if (node_free_func != NULL) {
if (dat->enable_automation) {
for (size_t i = 0; i < segarray_size(dat->value_array); i++) {
dat_value_t value = (dat_value_t)segarray_access(dat->value_array, i);
node_free_func(dat, value->value);
}
} else {
for (size_t i = 0; i < segarray_size(dat->node_array); i++) {
dat_node_t node = dat_access_node(dat, i);
if (node->check.ptr != NULL && node->value.raw != NULL) {
node_free_func(dat, node->value.raw);
}
}
}
}
segarray_destruct(dat->node_array);
segarray_destruct(dat->value_array);
afree(dat);
}
}
dat_t dat_construct_by_trie(trie_t origin, bool enable_automation) {
dat_t dat = dat_alloc();
if (dat == NULL) {
return NULL;
}
dat_construct_by_trie0(dat, origin);
if (enable_automation) {
dat->enable_automation = true;
dat_build_automation(dat, origin); /* 建立 AC 自动机 */
}
dat_post_construct(dat, origin);
return dat;
}
// dat Context
// ===================================================
dat_ctx_t dat_alloc_context(dat_t datrie) {
dat_ctx_t ctx = amalloc(sizeof(dat_ctx_s));
if (ctx == NULL) {
return NULL;
}
ctx->trie = datrie;
return ctx;
}
bool dat_free_context(dat_ctx_t context) {
if (context != NULL) {
afree(context);
}
return true;
}
void dat_reset_context(dat_ctx_t context, char content[], size_t len) {
context->content = (strlen_s){.ptr = content, .len = len};
context->_read = 0;
context->_begin = 0;
context->_cursor = context->trie->root;
if (context->trie->enable_automation) {
context->_matched.value = NULL;
} else {
context->_matched.node = context->trie->root;
}
}
bool dat_match_end(dat_ctx_t ctx) {
return ctx->_read >= ctx->content.len;
}
static inline dat_node_t dat_forward(dat_node_t cur, dat_ctx_t ctx) {
return cur->base.ptr + ((uint8_t*)ctx->content.ptr)[ctx->_read];
}
bool dat_next_on_node(dat_ctx_t ctx) {
dat_node_t pCursor = ctx->_cursor;
for (; ctx->_read < ctx->content.len; ctx->_read++) {
dat_node_t pNext = dat_forward(pCursor, ctx);
if (pNext->check.ptr != pCursor) {
break;
}
pCursor = pNext;
if (pNext->value.raw != NULL) {
ctx->_cursor = pCursor;
ctx->_matched.node = pNext;
ctx->_read++;
return true;
}
}
for (ctx->_begin++; ctx->_begin < ctx->content.len; ctx->_begin++) {
pCursor = ctx->trie->root;
for (ctx->_read = ctx->_begin; ctx->_read < ctx->content.len; ctx->_read++) {
dat_node_t pNext = dat_forward(pCursor, ctx);
if (pNext->check.ptr != pCursor) {
break;
}
pCursor = pNext;
if (pNext->value.raw != NULL) {
ctx->_cursor = pCursor;
ctx->_matched.node = pNext;
ctx->_read++;
return true;
}
}
}
return false;
}
bool dat_prefix_next_on_node(dat_ctx_t ctx) {
/* 执行匹配 */
dat_node_t pCursor = ctx->_cursor;
for (; ctx->_read < ctx->content.len; ctx->_read++) {
dat_node_t pNext = dat_forward(pCursor, ctx);
if (pNext->check.ptr != pCursor) {
return false;
}
pCursor = pNext;
if (pNext->value.raw != NULL) {
ctx->_cursor = pCursor;
ctx->_matched.node = pNext;
ctx->_read++;
return true;
}
}
return false;
}
bool dat_ac_next_on_node(dat_ctx_t ctx) {
/* 检查当前匹配点向树根的路径上是否还有匹配的词 */
while (ctx->_matched.value != NULL) {
ctx->_matched.value = ctx->_matched.value->next;
if (ctx->_matched.value != NULL) {
return true;
}
}
/* 执行匹配 */
dat_node_t pCursor = ctx->_cursor;
for (; ctx->_read < ctx->content.len; ctx->_read++) {
dat_node_t pNext = dat_forward(pCursor, ctx);
while (pCursor != ctx->trie->root && pNext->check.ptr != pCursor) {
pCursor = pCursor->failed.ptr;
pNext = dat_forward(pCursor, ctx);
}
if (pNext->check.ptr == pCursor) {
pCursor = pNext;
if (pNext->value.linked != NULL) {
ctx->_cursor = pCursor;
ctx->_matched.value = pNext->value.linked;
ctx->_read++;
return true;
}
}
// else { pCursor == ctx->trie->root; }
}
ctx->_cursor = pCursor;
// ctx->_matched = ctx->trie->root;
return false;
}
bool dat_ac_prefix_next_on_node(dat_ctx_t ctx) {
/* 执行匹配 */
dat_node_t pCursor = ctx->_cursor;
for (; ctx->_read < ctx->content.len; ctx->_read++) {
dat_node_t pNext = dat_forward(pCursor, ctx);
if (pNext->check.ptr != pCursor) {
return false;
}
pCursor = pNext;
if (pNext->value.linked != NULL) {
ctx->_cursor = pCursor;
ctx->_matched.value = pNext->value.linked;
ctx->_read++;
return true;
}
}
return false;
}
|
C | /*#include<stdio.h>
#include<string.h>
int main()
{
//עѭڲѭʹõıĸҪһ
int s,i,j=0,k=0,l=0,m=0,n=0,d,count=0,sum=0,p,q,coun,count1,count2,count3;
char a[101];
int c[100];
scanf("%d\n",&s);
for(q=0;q<s;q++)
{
k=0;
count=0;
count1=0;
count2=0;
count3=0;
coun=0;
scanf("%s",a); //¼ַ
sum=strlen(a);
while(a[k]!='\0')
{
if(a[k++]=='P') //ѭжǷP
{
m=k-1; //k++ m
}
}
k=0;
while(a[k]!='\0') //ѭжǷT
{
if(a[k++]=='T')
{
n=k-1;
}
}
d=n-m; //P T ֮ļ
// printf("%d\n",d);
if(d<=3&&d>=2) //23
{
for(i=0;i<m;i++) //P֮ǰA
{
if(a[i]=='A'||a[i]==' ')
{
count++;
count1++;
}
}
for(i=n+1;i<sum;i++) //T֮ A
{
if(a[i]=='A'||a[i]==' ')
{
count++;
count3++;
}
}
for(i=m+1;i<n;i++) // PT֮
{
if(a[i]!='A') //A
{
coun++;
// count2++;
}
if(a[i]=='A') //A
{
count2++;
// count2++;
}
}
p=sum-d-1;
// printf("%d\n",d);
// printf("%d\n",count);
if(count==p&&coun==0&&count1*count2==count3)
{
c[l++]=1;
}else
{
c[l++]=0;
}
}else{
c[l++]=0;
}
}
for(i=0;i<l;i++)
{
if(c[i]==1)
{
printf("YES\n");
}else
{
printf("NO\n");
}
}
return 0;
}*/
#include <stdio.h>
int main(void) {
int n,sum;
int a,b,c;
//a:beforeP,b:betweenPandT,c:afterT
int i,k,j = 0;
scanf("%d",&n);
char input[n][101];
for (k = 0; k<n; k++) scanf("%s",&input[k]);
for (i = 0; i<n; i++) {
a = b = c = j = 0;
while (input[i][j] == 'A') {
a++;j++;
}
if (input[i][j++] != 'P') {
printf("NO\n");
continue;
}
while (input[i][j] == 'A') {
b++;j++;
}
if (input[i][j++] != 'T') {
printf("NO\n");
continue;
}
while (input[i][j] == 'A') {
c++;j++;
}
if (input[i][j++] != '\0') {
printf("NO\n");
continue;
}
if (a*b !=c || b==0) printf("NO\n");
else printf("YES\n");
}
}
|
C | //
// main.c
// klm
//
// Created by Can KINCAL on 14.05.2015.
// Copyright (c) 2015 Can KINCAL. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
int dizi[10]={25,22,17,19,47,3,5,98,10,124};
int a;
int gecici;
scanf("%d",&a);
for (int i=0;i<10;i++)
for (int k=0;k<10;k++)
if(dizi[k]>dizi[k+1]){
gecici=dizi[k];
dizi[k]=dizi[k+1];
dizi[k+1]=gecici;}
printf("%d",dizi[a]);
// for (int i=0;i<10;i++)
printf("Hello, World!\n");
return 0;
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include "crawler.h"
#include <pthread.h>
#include <semaphore.h>
/*void *Malloc(size_t size) {
void *r = malloc(size);
assert(r);
return r;
}
char *Strdup(const char *s) {
void *r = strdup(s);
assert(r);
return r;
}*/
#define MAX_THREADS 20
#define check(exp, msg) if(exp) {} else {\
printf("%s:%d check (" #exp ") failed: %s\n", __FILE__, __LINE__, msg);\
exit(1);}
void *Malloc(size_t size) {
void *r = malloc(size);
assert(r);
return r;
}
char *Strdup(const char *s) {
void *r = strdup(s);
assert(r);
return r;
}
char *parseURL(const char *link)
{
char *url = strdup(link);
char *saveptr;
char *token = strtok_r(url, "/", &saveptr);
char *word = token;
while(token != NULL)
{
word = token;
token = strtok_r(NULL, "/", &saveptr);
}
return word;
}
int compare(const void* line1, const void* line2)
{
char *str1 = (char *) line1;
char *str2 = (char *) line2;
//printf("%s %s %d\n", str1, str2, strcmp(str1, str2));
return strcmp(str1, str2);
}
int isDifferent(char actual[100][50], char expected[100][50], int size)
{
int i = 0;
for(i = 0; i < size; ++i)
{
if(strcmp(actual[i], expected[i]) != 0)
return 1;
}
return 0;
}
void print(char buffer[100][50], int size)
{
int i = 0;
for(i = 0; i < size; ++i)
{
printf("%s", buffer[i]);
}
}
void printData(char actual[100][50], int size1, char expected[100][50], int size2)
{
printf("Actual Output (sorted):\n\n");
print(actual, size1);
printf("\nExpected Output (sorted): \n\n");
print(expected, size2);
}
int compareOutput(char actual[100][50], int size1, char *file)
{
char expected[100][50];
FILE *fp = fopen(file, "r");
if(fp == NULL)
fprintf(stderr, "Unable to open the file %s", file);
int size2 = 0;
while(fgets(expected[size2], 50, fp) != NULL)
{
size2++;
}
qsort(actual, size1, 50, compare);
qsort(expected, size2, 50, compare);
fclose(fp);
if(size1 != size2)
{
printf("wrong size\n");
printData(actual, size1, expected, size2);
return 1;
}
else if(isDifferent(actual, expected, size1))
{
printf("mismatch\n");
printData(actual, size1, expected, size2);
return 1;
}
return 0;
}
/*char *fetch(char *link) {
int fd = open(link, O_RDONLY);
if (fd < 0) {
perror("failed to open file");
return NULL;
}
int size = lseek(fd, 0, SEEK_END);
assert(size >= 0);
char *buf = Malloc(size+1);
buf[size] = '\0';
assert(buf);
lseek(fd, 0, SEEK_SET);
char *pos = buf;
while(pos < buf+size) {
int rv = read(fd, pos, buf+size-pos);
assert(rv > 0);
pos += rv;
}
close(fd);
return buf;
}*/
/*void edge(char *from, char *to) {
printf("%s -> %s\n", from, to);
}*/
pthread_mutex_t buffer_mutex, bounded_queue_mutex;
int buffer_consumed = 0;
int fill = 0, pages_downloaded = 0;
char buffer[100][50];
char *fetch(char *link) {
pthread_mutex_lock(&bounded_queue_mutex);
unsigned long current_id = (unsigned long) pthread_self();
printf("THREAD ID :: %ld\n", current_id);
if(pages_downloaded == 1)
{
pthread_mutex_unlock(&bounded_queue_mutex);
sleep(5);
}
else
pthread_mutex_unlock(&bounded_queue_mutex);
int fd = open(link, O_RDONLY);
if (fd < 0) {
fprintf(stderr, "failed to open file: %s", link);
return NULL;
}
int size = lseek(fd, 0, SEEK_END);
assert(size >= 0);
char *buf = Malloc(size+1);
buf[size] = '\0';
assert(buf);
lseek(fd, 0, SEEK_SET);
char *pos = buf;
while(pos < buf+size) {
int rv = read(fd, pos, buf+size-pos);
assert(rv > 0);
pos += rv;
}
pthread_mutex_lock(&bounded_queue_mutex);
pages_downloaded++;
pthread_mutex_unlock(&bounded_queue_mutex);
close(fd);
return buf;
}
//140269343610624
void edge(char *from, char *to) {
if(!from || !to)
return;
char temp[50];
temp[0] = '\0';
char *fromPage = parseURL(from);
char *toPage = parseURL(to);
strcpy(temp, fromPage);
strcat(temp, "->");
strcat(temp, toPage);
strcat(temp, "\n");
pthread_mutex_lock(&buffer_mutex);
strcpy(buffer[fill++], temp);
pthread_mutex_unlock(&buffer_mutex);
pthread_mutex_lock(&bounded_queue_mutex);
if(pages_downloaded == 1 && fill > 4)
buffer_consumed = 1;
pthread_mutex_unlock(&bounded_queue_mutex);
}
int main(int argc, char *argv[]) {
pthread_mutex_init(&buffer_mutex, NULL);
pthread_mutex_init(&bounded_queue_mutex, NULL);
int rc = crawl("/u/c/s/cs537-1/ta/tests/4a/tests/files/small_buffer/pagea", 5, 1, 1, fetch, edge);
assert(rc == 0);
check(buffer_consumed == 1, "All the links should have been parsed as multiple downloader threads should have consumed the buffer\n");
return compareOutput(buffer, fill, "/u/c/s/cs537-1/ta/tests/4a/tests/files/output/small_buffer.out");
}
|
C | #include "eeprom.h"
void eeprom_write(uint8_t data,uint16_t addr ){
while(READBIT(EECR,1));
EEAR = addr;
EEDR = data;
SETBIT(EECR,2);
SETBIT(EECR,1);
}
uint8_t eeprom_read(uint16_t addr ){
while(READBIT(EECR,1));
EEAR = addr;
SETBIT(EECR,0);
return EEDR;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
FILE *fp;
void init_csv() {
fp = fopen("log.csv", "w+");
fprintf(fp, "Timestamp, TAG, WiringPi, Value\n");
}
void write_csv(char *tag, int wiringPi, int value) {
int hours, minutes, seconds, day, month, year;
time_t now = time(NULL);
struct tm *local = localtime(&now);
hours = local->tm_hour;
minutes = local->tm_min;
seconds = local->tm_sec;
day = local->tm_mday;
month = local->tm_mon + 1;
year = local->tm_year + 1900;
fprintf(fp,"%02d/%02d/%d %02d:%02d:%02d,", day, month, year, hours, minutes, seconds);
fprintf(fp,"%s,%d,%d\n", tag, wiringPi, value);
}
void close_csv() {
fclose(fp);
}
|
C | #include <stdio.h>
int main(void) {
// declare nessasary variables
int cityNum = 0;
int cityPop[100];
// create scanf to find out number of cities
scanf("%d", &cityNum);
printf("Number of cities: %d", cityNum);
// create scanfs to find out pop per city
for(int i = 0; i < cityNum; i++) {
scanf("%d", &cityPop[i]);
printf("Population of City %d is: %d", i, cityPop[i]);
}
// create if statement to see if pop is greater than limit
int cityExceed = 0;
for(int i = 0; i < cityNum; i++) {
if(cityPop > 10000) {
cityExceed = cityExceed + 1;
}
}
// printf the city_exceed
printf("%d", cityExceed);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.