<commit_before>/*************************************************************************
 *
 *  $RCSfile: rtlproto.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: pjunck $ $Date: 2004-11-02 11:57:54 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "sbstar.hxx"
#include "macfix.hxx"

#define RTLFUNC( name ) void SbRtl_##name( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite )
#define RTLNAME( name ) MEMBER(SbRtl_##name)

typedef void( *RtlCall ) ( StarBASIC* p, SbxArray& rArgs, BOOL bWrite );

// Properties

extern RTLFUNC(Date);
extern RTLFUNC(Err);
extern RTLFUNC(Erl);
extern RTLFUNC(False);
extern RTLFUNC(Nothing);
extern RTLFUNC(Null);
extern RTLFUNC(True);

extern RTLFUNC(ATTR_NORMAL);
extern RTLFUNC(ATTR_READONLY);
extern RTLFUNC(ATTR_HIDDEN);
extern RTLFUNC(ATTR_SYSTEM);
extern RTLFUNC(ATTR_VOLUME);
extern RTLFUNC(ATTR_DIRECTORY);
extern RTLFUNC(ATTR_ARCHIVE);

extern RTLFUNC(V_EMPTY);
extern RTLFUNC(V_NULL);
extern RTLFUNC(V_INTEGER);
extern RTLFUNC(V_LONG);
extern RTLFUNC(V_SINGLE);
extern RTLFUNC(V_DOUBLE);
extern RTLFUNC(V_CURRENCY);
extern RTLFUNC(V_DATE);
extern RTLFUNC(V_STRING);

extern RTLFUNC(MB_OK);
extern RTLFUNC(MB_OKCANCEL);
extern RTLFUNC(MB_ABORTRETRYIGNORE);
extern RTLFUNC(MB_YESNOCANCEL);
extern RTLFUNC(MB_YESNO);
extern RTLFUNC(MB_RETRYCANCEL);
extern RTLFUNC(MB_ICONSTOP);
extern RTLFUNC(MB_ICONQUESTION);
extern RTLFUNC(MB_ICONEXCLAMATION);
extern RTLFUNC(MB_ICONINFORMATION);
extern RTLFUNC(MB_DEFBUTTON1);
extern RTLFUNC(MB_DEFBUTTON2);
extern RTLFUNC(MB_DEFBUTTON3);
extern RTLFUNC(MB_APPLMODAL);
extern RTLFUNC(MB_SYSTEMMODAL);

extern RTLFUNC(IDOK);
extern RTLFUNC(IDCANCEL);
extern RTLFUNC(IDABORT);
extern RTLFUNC(IDRETRY);
extern RTLFUNC(IDYES);
extern RTLFUNC(IDNO);

extern RTLFUNC(CF_TEXT);
extern RTLFUNC(CF_BITMAP);
extern RTLFUNC(CF_METAFILEPICT);

extern RTLFUNC(PI);

extern RTLFUNC(SET_OFF);
extern RTLFUNC(SET_ON);
extern RTLFUNC(TOGGLE);

extern RTLFUNC(TYP_AUTHORFLD);
extern RTLFUNC(TYP_CHAPTERFLD);
extern RTLFUNC(TYP_CONDTXTFLD);
extern RTLFUNC(TYP_DATEFLD);
extern RTLFUNC(TYP_DBFLD);
extern RTLFUNC(TYP_DBNAMEFLD);
extern RTLFUNC(TYP_DBNEXTSETFLD);
extern RTLFUNC(TYP_DBNUMSETFLD);
extern RTLFUNC(TYP_DBSETNUMBERFLD);
extern RTLFUNC(TYP_DDEFLD);
extern RTLFUNC(TYP_DOCINFOFLD);
extern RTLFUNC(TYP_DOCSTATFLD);
extern RTLFUNC(TYP_EXTUSERFLD);
extern RTLFUNC(TYP_FILENAMEFLD);
extern RTLFUNC(TYP_FIXDATEFLD);
extern RTLFUNC(TYP_FIXTIMEFLD);
extern RTLFUNC(TYP_FORMELFLD);
extern RTLFUNC(TYP_GETFLD);
extern RTLFUNC(TYP_GETREFFLD);
extern RTLFUNC(TYP_HIDDENPARAFLD);
extern RTLFUNC(TYP_HIDDENTXTFLD);
extern RTLFUNC(TYP_INPUTFLD);
extern RTLFUNC(TYP_MACROFLD);
extern RTLFUNC(TYP_NEXTPAGEFLD);
extern RTLFUNC(TYP_PAGENUMBERFLD);
extern RTLFUNC(TYP_POSTITFLD);
extern RTLFUNC(TYP_PREVPAGEFLD);
extern RTLFUNC(TYP_SEQFLD);
extern RTLFUNC(TYP_SETFLD);
extern RTLFUNC(TYP_SETINPFLD);
extern RTLFUNC(TYP_SETREFFLD);
extern RTLFUNC(TYP_TEMPLNAMEFLD);
extern RTLFUNC(TYP_TIMEFLD);
extern RTLFUNC(TYP_USERFLD);
extern RTLFUNC(TYP_USRINPFLD);
extern RTLFUNC(TYP_SETREFPAGEFLD);
extern RTLFUNC(TYP_GETREFPAGEFLD);
extern RTLFUNC(TYP_INTERNETFLD);
extern RTLFUNC(TYP_JUMPEDITFLD);

extern RTLFUNC(FRAMEANCHORPAGE);
extern RTLFUNC(FRAMEANCHORPARA);
extern RTLFUNC(FRAMEANCHORCHAR);

extern RTLFUNC(CLEAR_ALLTABS);
extern RTLFUNC(CLEAR_TAB);
extern RTLFUNC(SET_TAB);

extern RTLFUNC(LINEPROP);
extern RTLFUNC(LINE_1);
extern RTLFUNC(LINE_15);
extern RTLFUNC(LINE_2);

// Methoden

extern RTLFUNC(CreateObject);
extern RTLFUNC(Error);
extern RTLFUNC(Sin);
extern RTLFUNC(Abs);
extern RTLFUNC(Asc);
extern RTLFUNC(Atn);
extern RTLFUNC(Chr);
extern RTLFUNC(Cos);
extern RTLFUNC(CurDir);
extern RTLFUNC(ChDir);  // JSM
extern RTLFUNC(ChDrive); // JSM
extern RTLFUNC(FileCopy); // JSM
extern RTLFUNC(Kill); // JSM
extern RTLFUNC(MkDir); // JSM
extern RTLFUNC(RmDir); // JSM
extern RTLFUNC(SendKeys); // JSM
extern RTLFUNC(DimArray);
extern RTLFUNC(Dir);
extern RTLFUNC(Exp);
extern RTLFUNC(FileLen);
extern RTLFUNC(Fix);
extern RTLFUNC(Hex);
extern RTLFUNC(InStr);
extern RTLFUNC(Int);
extern RTLFUNC(Join);
extern RTLFUNC(LCase);
extern RTLFUNC(Left);
extern RTLFUNC(Log);
extern RTLFUNC(LTrim);
extern RTLFUNC(Mid);
extern RTLFUNC(Oct);
extern RTLFUNC(Right);
extern RTLFUNC(RTrim);
extern RTLFUNC(Sgn);
extern RTLFUNC(Space);
extern RTLFUNC(Split);
extern RTLFUNC(Sqr);
extern RTLFUNC(Str);
extern RTLFUNC(StrComp);
extern RTLFUNC(String);
extern RTLFUNC(StrReverse);
extern RTLFUNC(Tan);
extern RTLFUNC(UCase);
extern RTLFUNC(Val);
extern RTLFUNC(Len);
extern RTLFUNC(Spc);
extern RTLFUNC(DateSerial);
extern RTLFUNC(TimeSerial);
extern RTLFUNC(DateValue);
extern RTLFUNC(TimeValue);
extern RTLFUNC(Day);
extern RTLFUNC(Hour);
extern RTLFUNC(Minute);
extern RTLFUNC(Month);
extern RTLFUNC(MonthName);
extern RTLFUNC(Now);
extern RTLFUNC(Second);
extern RTLFUNC(Time);
extern RTLFUNC(Timer);
extern RTLFUNC(Weekday);
extern RTLFUNC(WeekdayName);
extern RTLFUNC(Year);
extern RTLFUNC(Date);
extern RTLFUNC(InputBox);
extern RTLFUNC(Me);
extern RTLFUNC(MsgBox);
extern RTLFUNC(IsArray);
extern RTLFUNC(IsDate);
extern RTLFUNC(IsEmpty);
extern RTLFUNC(IsError);
extern RTLFUNC(IsNull);
extern RTLFUNC(IsNumeric);
extern RTLFUNC(IsObject);
extern RTLFUNC(IsUnoStruct);

extern RTLFUNC(FileDateTime);
extern RTLFUNC(Format);
extern RTLFUNC(GetAttr);
extern RTLFUNC(Randomize); // JSM
extern RTLFUNC(Round);
extern RTLFUNC(Rnd);
extern RTLFUNC(Shell);
extern RTLFUNC(VarType);
extern RTLFUNC(TypeName);
extern RTLFUNC(TypeLen);

extern RTLFUNC(EOF);
extern RTLFUNC(FileAttr);
extern RTLFUNC(Loc);
extern RTLFUNC(Lof);
extern RTLFUNC(Seek);
extern RTLFUNC(SetAttr); // JSM
extern RTLFUNC(Reset); // JSM

extern RTLFUNC(DDEInitiate);
extern RTLFUNC(DDETerminate);
extern RTLFUNC(DDETerminateAll);
extern RTLFUNC(DDERequest);
extern RTLFUNC(DDEExecute);
extern RTLFUNC(DDEPoke);

extern RTLFUNC(FreeFile);
extern RTLFUNC(IsMissing);
extern RTLFUNC(LBound);
extern RTLFUNC(UBound);
extern RTLFUNC(RGB);
extern RTLFUNC(QBColor);
extern RTLFUNC(StrConv);

extern RTLFUNC(Beep);

extern RTLFUNC(Load);
extern RTLFUNC(Unload);
extern RTLFUNC(AboutStarBasic);
extern RTLFUNC(LoadPicture);
extern RTLFUNC(SavePicture);

extern RTLFUNC(CBool); // JSM
extern RTLFUNC(CByte); // JSM
extern RTLFUNC(CCur); // JSM
extern RTLFUNC(CDate); // JSM
extern RTLFUNC(CDbl); // JSM
extern RTLFUNC(CInt); // JSM
extern RTLFUNC(CLng); // JSM
extern RTLFUNC(CSng); // JSM
extern RTLFUNC(CStr); // JSM
extern RTLFUNC(CVar); // JSM
extern RTLFUNC(CVErr); // JSM

extern RTLFUNC(Iif); // JSM

extern RTLFUNC(DumpAllObjects);

extern RTLFUNC(GetSystemType);
extern RTLFUNC(GetGUIType);
extern RTLFUNC(Red);
extern RTLFUNC(Green);
extern RTLFUNC(Blue);

extern RTLFUNC(Switch);
extern RTLFUNC(Wait);
extern RTLFUNC(GetGUIVersion);
extern RTLFUNC(Choose);
extern RTLFUNC(Trim);

extern RTLFUNC(DateAdd);
extern RTLFUNC(DateDiff);
extern RTLFUNC(DatePart);
extern RTLFUNC(GetSolarVersion);
extern RTLFUNC(TwipsPerPixelX);
extern RTLFUNC(TwipsPerPixelY);
extern RTLFUNC(FreeLibrary);
extern RTLFUNC(Array);
extern RTLFUNC(FindObject);
extern RTLFUNC(FindPropertyObject);
extern RTLFUNC(EnableReschedule);

extern RTLFUNC(Put);
extern RTLFUNC(Get);
extern RTLFUNC(Environ);
extern RTLFUNC(GetDialogZoomFactorX);
extern RTLFUNC(GetDialogZoomFactorY);
extern RTLFUNC(GetSystemTicks);
extern RTLFUNC(GetPathSeparator);
extern RTLFUNC(ResolvePath);
extern RTLFUNC(CreateUnoStruct);
extern RTLFUNC(CreateUnoService);
extern RTLFUNC(CreateUnoValue);
extern RTLFUNC(GetProcessServiceManager);
extern RTLFUNC(GetDefaultContext);
extern RTLFUNC(CreatePropertySet);
extern RTLFUNC(CreateUnoListener);
extern RTLFUNC(HasUnoInterfaces);
extern RTLFUNC(EqualUnoObjects);
extern RTLFUNC(CreateUnoDialog);
extern RTLFUNC(GlobalScope);
extern RTLFUNC(FileExists);
extern RTLFUNC(ConvertToUrl);
extern RTLFUNC(ConvertFromUrl);
extern RTLFUNC(CDateToIso);
extern RTLFUNC(CDateFromIso);
extern RTLFUNC(CompatibilityMode);
extern RTLFUNC(CDec);

<commit_msg>INTEGRATION: CWS texteng03 (1.9.58); FILE MERGED 2004/11/05 07:26:30 ab 1.9.58.2: #118121# RTL function InStrRev 2004/11/04 15:17:47 ab 1.9.58.1: #117765# RTL function to access RTL library explicitely<commit_after>/*************************************************************************
 *
 *  $RCSfile: rtlproto.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2004-11-15 16:37:18 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "sbstar.hxx"
#include "macfix.hxx"

#define RTLFUNC( name ) void SbRtl_##name( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite )
#define RTLNAME( name ) MEMBER(SbRtl_##name)

typedef void( *RtlCall ) ( StarBASIC* p, SbxArray& rArgs, BOOL bWrite );

// Properties

extern RTLFUNC(Date);
extern RTLFUNC(Err);
extern RTLFUNC(Erl);
extern RTLFUNC(False);
extern RTLFUNC(Nothing);
extern RTLFUNC(Null);
extern RTLFUNC(True);

extern RTLFUNC(ATTR_NORMAL);
extern RTLFUNC(ATTR_READONLY);
extern RTLFUNC(ATTR_HIDDEN);
extern RTLFUNC(ATTR_SYSTEM);
extern RTLFUNC(ATTR_VOLUME);
extern RTLFUNC(ATTR_DIRECTORY);
extern RTLFUNC(ATTR_ARCHIVE);

extern RTLFUNC(V_EMPTY);
extern RTLFUNC(V_NULL);
extern RTLFUNC(V_INTEGER);
extern RTLFUNC(V_LONG);
extern RTLFUNC(V_SINGLE);
extern RTLFUNC(V_DOUBLE);
extern RTLFUNC(V_CURRENCY);
extern RTLFUNC(V_DATE);
extern RTLFUNC(V_STRING);

extern RTLFUNC(MB_OK);
extern RTLFUNC(MB_OKCANCEL);
extern RTLFUNC(MB_ABORTRETRYIGNORE);
extern RTLFUNC(MB_YESNOCANCEL);
extern RTLFUNC(MB_YESNO);
extern RTLFUNC(MB_RETRYCANCEL);
extern RTLFUNC(MB_ICONSTOP);
extern RTLFUNC(MB_ICONQUESTION);
extern RTLFUNC(MB_ICONEXCLAMATION);
extern RTLFUNC(MB_ICONINFORMATION);
extern RTLFUNC(MB_DEFBUTTON1);
extern RTLFUNC(MB_DEFBUTTON2);
extern RTLFUNC(MB_DEFBUTTON3);
extern RTLFUNC(MB_APPLMODAL);
extern RTLFUNC(MB_SYSTEMMODAL);

extern RTLFUNC(IDOK);
extern RTLFUNC(IDCANCEL);
extern RTLFUNC(IDABORT);
extern RTLFUNC(IDRETRY);
extern RTLFUNC(IDYES);
extern RTLFUNC(IDNO);

extern RTLFUNC(CF_TEXT);
extern RTLFUNC(CF_BITMAP);
extern RTLFUNC(CF_METAFILEPICT);

extern RTLFUNC(PI);

extern RTLFUNC(SET_OFF);
extern RTLFUNC(SET_ON);
extern RTLFUNC(TOGGLE);

extern RTLFUNC(TYP_AUTHORFLD);
extern RTLFUNC(TYP_CHAPTERFLD);
extern RTLFUNC(TYP_CONDTXTFLD);
extern RTLFUNC(TYP_DATEFLD);
extern RTLFUNC(TYP_DBFLD);
extern RTLFUNC(TYP_DBNAMEFLD);
extern RTLFUNC(TYP_DBNEXTSETFLD);
extern RTLFUNC(TYP_DBNUMSETFLD);
extern RTLFUNC(TYP_DBSETNUMBERFLD);
extern RTLFUNC(TYP_DDEFLD);
extern RTLFUNC(TYP_DOCINFOFLD);
extern RTLFUNC(TYP_DOCSTATFLD);
extern RTLFUNC(TYP_EXTUSERFLD);
extern RTLFUNC(TYP_FILENAMEFLD);
extern RTLFUNC(TYP_FIXDATEFLD);
extern RTLFUNC(TYP_FIXTIMEFLD);
extern RTLFUNC(TYP_FORMELFLD);
extern RTLFUNC(TYP_GETFLD);
extern RTLFUNC(TYP_GETREFFLD);
extern RTLFUNC(TYP_HIDDENPARAFLD);
extern RTLFUNC(TYP_HIDDENTXTFLD);
extern RTLFUNC(TYP_INPUTFLD);
extern RTLFUNC(TYP_MACROFLD);
extern RTLFUNC(TYP_NEXTPAGEFLD);
extern RTLFUNC(TYP_PAGENUMBERFLD);
extern RTLFUNC(TYP_POSTITFLD);
extern RTLFUNC(TYP_PREVPAGEFLD);
extern RTLFUNC(TYP_SEQFLD);
extern RTLFUNC(TYP_SETFLD);
extern RTLFUNC(TYP_SETINPFLD);
extern RTLFUNC(TYP_SETREFFLD);
extern RTLFUNC(TYP_TEMPLNAMEFLD);
extern RTLFUNC(TYP_TIMEFLD);
extern RTLFUNC(TYP_USERFLD);
extern RTLFUNC(TYP_USRINPFLD);
extern RTLFUNC(TYP_SETREFPAGEFLD);
extern RTLFUNC(TYP_GETREFPAGEFLD);
extern RTLFUNC(TYP_INTERNETFLD);
extern RTLFUNC(TYP_JUMPEDITFLD);

extern RTLFUNC(FRAMEANCHORPAGE);
extern RTLFUNC(FRAMEANCHORPARA);
extern RTLFUNC(FRAMEANCHORCHAR);

extern RTLFUNC(CLEAR_ALLTABS);
extern RTLFUNC(CLEAR_TAB);
extern RTLFUNC(SET_TAB);

extern RTLFUNC(LINEPROP);
extern RTLFUNC(LINE_1);
extern RTLFUNC(LINE_15);
extern RTLFUNC(LINE_2);

// Methoden

extern RTLFUNC(CreateObject);
extern RTLFUNC(Error);
extern RTLFUNC(Sin);
extern RTLFUNC(Abs);
extern RTLFUNC(Asc);
extern RTLFUNC(Atn);
extern RTLFUNC(Chr);
extern RTLFUNC(Cos);
extern RTLFUNC(CurDir);
extern RTLFUNC(ChDir);  // JSM
extern RTLFUNC(ChDrive); // JSM
extern RTLFUNC(FileCopy); // JSM
extern RTLFUNC(Kill); // JSM
extern RTLFUNC(MkDir); // JSM
extern RTLFUNC(RmDir); // JSM
extern RTLFUNC(SendKeys); // JSM
extern RTLFUNC(DimArray);
extern RTLFUNC(Dir);
extern RTLFUNC(Exp);
extern RTLFUNC(FileLen);
extern RTLFUNC(Fix);
extern RTLFUNC(Hex);
extern RTLFUNC(InStr);
extern RTLFUNC(InStrRev);
extern RTLFUNC(Int);
extern RTLFUNC(Join);
extern RTLFUNC(LCase);
extern RTLFUNC(Left);
extern RTLFUNC(Log);
extern RTLFUNC(LTrim);
extern RTLFUNC(Mid);
extern RTLFUNC(Oct);
extern RTLFUNC(Right);
extern RTLFUNC(RTrim);
extern RTLFUNC(RTL);
extern RTLFUNC(Sgn);
extern RTLFUNC(Space);
extern RTLFUNC(Split);
extern RTLFUNC(Sqr);
extern RTLFUNC(Str);
extern RTLFUNC(StrComp);
extern RTLFUNC(String);
extern RTLFUNC(StrReverse);
extern RTLFUNC(Tan);
extern RTLFUNC(UCase);
extern RTLFUNC(Val);
extern RTLFUNC(Len);
extern RTLFUNC(Spc);
extern RTLFUNC(DateSerial);
extern RTLFUNC(TimeSerial);
extern RTLFUNC(DateValue);
extern RTLFUNC(TimeValue);
extern RTLFUNC(Day);
extern RTLFUNC(Hour);
extern RTLFUNC(Minute);
extern RTLFUNC(Month);
extern RTLFUNC(MonthName);
extern RTLFUNC(Now);
extern RTLFUNC(Second);
extern RTLFUNC(Time);
extern RTLFUNC(Timer);
extern RTLFUNC(Weekday);
extern RTLFUNC(WeekdayName);
extern RTLFUNC(Year);
extern RTLFUNC(Date);
extern RTLFUNC(InputBox);
extern RTLFUNC(Me);
extern RTLFUNC(MsgBox);
extern RTLFUNC(IsArray);
extern RTLFUNC(IsDate);
extern RTLFUNC(IsEmpty);
extern RTLFUNC(IsError);
extern RTLFUNC(IsNull);
extern RTLFUNC(IsNumeric);
extern RTLFUNC(IsObject);
extern RTLFUNC(IsUnoStruct);

extern RTLFUNC(FileDateTime);
extern RTLFUNC(Format);
extern RTLFUNC(GetAttr);
extern RTLFUNC(Randomize); // JSM
extern RTLFUNC(Round);
extern RTLFUNC(Rnd);
extern RTLFUNC(Shell);
extern RTLFUNC(VarType);
extern RTLFUNC(TypeName);
extern RTLFUNC(TypeLen);

extern RTLFUNC(EOF);
extern RTLFUNC(FileAttr);
extern RTLFUNC(Loc);
extern RTLFUNC(Lof);
extern RTLFUNC(Seek);
extern RTLFUNC(SetAttr); // JSM
extern RTLFUNC(Reset); // JSM

extern RTLFUNC(DDEInitiate);
extern RTLFUNC(DDETerminate);
extern RTLFUNC(DDETerminateAll);
extern RTLFUNC(DDERequest);
extern RTLFUNC(DDEExecute);
extern RTLFUNC(DDEPoke);

extern RTLFUNC(FreeFile);
extern RTLFUNC(IsMissing);
extern RTLFUNC(LBound);
extern RTLFUNC(UBound);
extern RTLFUNC(RGB);
extern RTLFUNC(QBColor);
extern RTLFUNC(StrConv);

extern RTLFUNC(Beep);

extern RTLFUNC(Load);
extern RTLFUNC(Unload);
extern RTLFUNC(AboutStarBasic);
extern RTLFUNC(LoadPicture);
extern RTLFUNC(SavePicture);

extern RTLFUNC(CBool); // JSM
extern RTLFUNC(CByte); // JSM
extern RTLFUNC(CCur); // JSM
extern RTLFUNC(CDate); // JSM
extern RTLFUNC(CDbl); // JSM
extern RTLFUNC(CInt); // JSM
extern RTLFUNC(CLng); // JSM
extern RTLFUNC(CSng); // JSM
extern RTLFUNC(CStr); // JSM
extern RTLFUNC(CVar); // JSM
extern RTLFUNC(CVErr); // JSM

extern RTLFUNC(Iif); // JSM

extern RTLFUNC(DumpAllObjects);

extern RTLFUNC(GetSystemType);
extern RTLFUNC(GetGUIType);
extern RTLFUNC(Red);
extern RTLFUNC(Green);
extern RTLFUNC(Blue);

extern RTLFUNC(Switch);
extern RTLFUNC(Wait);
extern RTLFUNC(GetGUIVersion);
extern RTLFUNC(Choose);
extern RTLFUNC(Trim);

extern RTLFUNC(DateAdd);
extern RTLFUNC(DateDiff);
extern RTLFUNC(DatePart);
extern RTLFUNC(GetSolarVersion);
extern RTLFUNC(TwipsPerPixelX);
extern RTLFUNC(TwipsPerPixelY);
extern RTLFUNC(FreeLibrary);
extern RTLFUNC(Array);
extern RTLFUNC(FindObject);
extern RTLFUNC(FindPropertyObject);
extern RTLFUNC(EnableReschedule);

extern RTLFUNC(Put);
extern RTLFUNC(Get);
extern RTLFUNC(Environ);
extern RTLFUNC(GetDialogZoomFactorX);
extern RTLFUNC(GetDialogZoomFactorY);
extern RTLFUNC(GetSystemTicks);
extern RTLFUNC(GetPathSeparator);
extern RTLFUNC(ResolvePath);
extern RTLFUNC(CreateUnoStruct);
extern RTLFUNC(CreateUnoService);
extern RTLFUNC(CreateUnoValue);
extern RTLFUNC(GetProcessServiceManager);
extern RTLFUNC(GetDefaultContext);
extern RTLFUNC(CreatePropertySet);
extern RTLFUNC(CreateUnoListener);
extern RTLFUNC(HasUnoInterfaces);
extern RTLFUNC(EqualUnoObjects);
extern RTLFUNC(CreateUnoDialog);
extern RTLFUNC(GlobalScope);
extern RTLFUNC(FileExists);
extern RTLFUNC(ConvertToUrl);
extern RTLFUNC(ConvertFromUrl);
extern RTLFUNC(CDateToIso);
extern RTLFUNC(CDateFromIso);
extern RTLFUNC(CompatibilityMode);
extern RTLFUNC(CDec);

<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright 2011-2013 The University of North Carolina at Chapel Hill
 *  All rights reserved.
 *
 *  Licensed under the MADAI Software License. You may obtain a copy of
 *  this license at
 *
 *         https://madai-public.cs.unc.edu/software/license/
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <vector>

#include "LatinHypercubeGenerator.h"
#include "Parameter.h"

void printElement( double d ) {
  std::cout << d << " ";
}

int main( int argc, char* argv[] )
{
  int numberOfTrainingPoints = 4;

  std::vector< madai::Parameter > parameters;
  parameters.push_back( madai::Parameter( "param_0", -1.0,  1.0 ) );
  parameters.push_back( madai::Parameter( "param_1",  2.1,  3.2 ) );
  parameters.push_back( madai::Parameter( "param_2", -4.7, -2.2 ) );

  madai::LatinHypercubeGenerator generator;
  std::vector< madai::Sample > samples =
    generator.Generate( numberOfTrainingPoints, parameters );

  std::cout << "Number of samples: " << samples.size() << std::endl;
  for ( size_t i = 0; i < samples.size(); ++i ) {
    madai::Sample sample = samples[i];
    for ( size_t j = 0; j < sample.m_ParameterValues.size(); ++j ) {
      std::cout << sample.m_ParameterValues[j] << ", ";
    }
    std::cout << std::endl;
  }

  // Test whether a valid latin hypercube was generated.
  std::vector< std::vector< double > > parametersForDimension;
  for ( size_t i = 0; i < parameters.size(); ++i ) {
    parametersForDimension.push_back( std::vector< double >( samples.size(), 0.0 ) );
  }

  for ( size_t i = 0; i < samples.size(); ++i ) {
    madai::Sample sample = samples[i];
    for ( size_t j = 0; j < parametersForDimension.size(); ++j ) {
      parametersForDimension[j][i] = sample.m_ParameterValues[j];
    }
  }

  // Sort the parameter vectors
  for ( size_t j = 0; j < parametersForDimension.size(); ++j ) {
    std::sort( parametersForDimension[j].begin(),
               parametersForDimension[j].end() );

    std::cout << "Sorted elements for parameter " << j << ":\n";
    std::for_each( parametersForDimension[j].begin(),
                   parametersForDimension[j].end(),
                   printElement );
    std::cout << "\n";

    // Now check that the spacing between the parameters in each
    // dimension is equal to within numerical precision.
    double expectedDiff = parametersForDimension[j][1] - parametersForDimension[j][0];
    for ( size_t i = 1; i < parametersForDimension[j].size()-1; ++i ) {
      double i1 = parametersForDimension[j][i];
      double i2 = parametersForDimension[j][i+1];
      if ( fabs( i2 - i1 - expectedDiff ) > 1e-4 ) {
        std::cerr << "Incorrect spacing between parameter samples in dimension "
                  << i << ". Should have been " << expectedDiff << ", was "
                  << (i2 - i1 ) << "\n";
        return EXIT_FAILURE;
      }
    }
  }

  return EXIT_SUCCESS;
}

<commit_msg>Added check that partitioning by percentile for uniform distributions works<commit_after>/*=========================================================================
 *
 *  Copyright 2011-2013 The University of North Carolina at Chapel Hill
 *  All rights reserved.
 *
 *  Licensed under the MADAI Software License. You may obtain a copy of
 *  this license at
 *
 *         https://madai-public.cs.unc.edu/software/license/
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <vector>

#include "LatinHypercubeGenerator.h"
#include "Parameter.h"

void printElement( double d ) {
  std::cout << d << " ";
}

void PrintSamples( const std::vector< madai::Sample > samples ) {
  std::cout << "Number of samples: " << samples.size() << std::endl;
  for ( size_t i = 0; i < samples.size(); ++i ) {
    madai::Sample sample = samples[i];
    for ( size_t j = 0; j < sample.m_ParameterValues.size(); ++j ) {
      std::cout << sample.m_ParameterValues[j] << ", ";
    }
    std::cout << std::endl;
  }
}

bool CheckForEvenSpacing( const std::vector< madai::Sample > samples ) {
  if ( samples.size() == 0 ) {
    return true;
  }

  size_t numberOfParameters = samples[0].m_ParameterValues.size();

  // Test whether a valid latin hypercube was generated.
  std::vector< std::vector< double > > parametersForDimension;
  for ( size_t i = 0; i < numberOfParameters; ++i ) {
    parametersForDimension.push_back( std::vector< double >( samples.size(), 0.0 ) );
  }

  for ( size_t i = 0; i < samples.size(); ++i ) {
    madai::Sample sample = samples[i];
    for ( size_t j = 0; j < parametersForDimension.size(); ++j ) {
      parametersForDimension[j][i] = sample.m_ParameterValues[j];
    }
  }

  // Sort the parameter vectors
  for ( size_t j = 0; j < parametersForDimension.size(); ++j ) {
    std::sort( parametersForDimension[j].begin(),
               parametersForDimension[j].end() );

    std::cout << "Sorted elements for parameter " << j << ":\n";
    std::for_each( parametersForDimension[j].begin(),
                   parametersForDimension[j].end(),
                   printElement );
    std::cout << "\n";

    // Now check that the spacing between the parameters in each
    // dimension is equal to within numerical precision.
    double expectedDiff = parametersForDimension[j][1] - parametersForDimension[j][0];
    for ( size_t i = 1; i < parametersForDimension[j].size()-1; ++i ) {
      double i1 = parametersForDimension[j][i];
      double i2 = parametersForDimension[j][i+1];
      if ( fabs( i2 - i1 - expectedDiff ) > 1e-4 ) {
        std::cerr << "Incorrect spacing between parameter samples in dimension "
                  << i << ". Should have been " << expectedDiff << ", was "
                  << (i2 - i1 ) << "\n";
        return false;
      }
    }
  }

  return true;
}

int main( int argc, char* argv[] )
{
  int numberOfTrainingPoints = 4;

  std::vector< madai::Parameter > parameters;
  parameters.push_back( madai::Parameter( "param_0", -1.0,  1.0 ) );
  parameters.push_back( madai::Parameter( "param_1",  2.1,  3.2 ) );
  parameters.push_back( madai::Parameter( "param_2", -4.7, -2.2 ) );

  // Create generator
  madai::LatinHypercubeGenerator generator;

  // Check for default values
  if ( generator.GetStandardDeviations() != 3.0 ) {
    std::cerr << "Expected default standard deviations to be 3.0, got "
              << generator.GetStandardDeviations() << " instead\n";
    return EXIT_FAILURE;
  }

  if ( generator.GetPartitionSpaceByPercentile() != false ) {
    std::cerr << "Expected default value for PartitionSpaceByPercentile to be "
              << "true, got " << generator.GetPartitionSpaceByPercentile()
              << "instead.\n";
    return EXIT_FAILURE;
  }

  std::vector< madai::Sample > samples =
    generator.Generate( numberOfTrainingPoints, parameters );
  PrintSamples( samples );

  if ( !CheckForEvenSpacing( samples ) ) {
    return EXIT_FAILURE;
  }

  // Now flip on dividing by percentile and make sure we get even spacing
  generator.SetPartitionSpaceByPercentile( true );
  samples = generator.Generate( numberOfTrainingPoints, parameters );

  PrintSamples( samples );

  if ( !CheckForEvenSpacing( samples ) ) {
    return EXIT_FAILURE;
  }

  // \todo - Test sampling of Gaussian distributions

  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pestate.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 12:08:40 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include <s2_luidl/pestate.hxx>

// NOT FULLY DEFINED SERVICES
#include <ary_i/codeinf2.hxx>
#include <s2_luidl/parsenv2.hxx>

namespace csi
{
namespace uidl
{

void
ParseEnvState::Process_Identifier( const TokIdentifier & )
{
    Process_Default();
}

void
ParseEnvState::Process_NameSeparator()
{
    Process_Default();
}

void
ParseEnvState::Process_Punctuation( const TokPunctuation & )
{
    Process_Default();
}

void
ParseEnvState::Process_BuiltInType( const TokBuiltInType & )
{
    Process_Default();
}

void
ParseEnvState::Process_TypeModifier( const TokTypeModifier & )
{
    Process_Default();
}

void
ParseEnvState::Process_MetaType( const TokMetaType &    )
{
    Process_Default();
}

void
ParseEnvState::Process_Stereotype( const TokStereotype & )
{
    Process_Default();
}

void
ParseEnvState::Process_ParameterHandling( const TokParameterHandling & )
{
    Process_Default();
}

void
ParseEnvState::Process_Raises()
{
    Process_Default();
}

void
ParseEnvState::Process_Needs()
{
    Process_Default();
}

void
ParseEnvState::Process_Observes()
{
    Process_Default();
}

void
ParseEnvState::Process_Assignment( const TokAssignment & )
{
    Process_Default();
}

void
ParseEnvState::Process_EOL()
{
    MyPE().SetResult(done,stay);
}

void
ParseEnvState::On_SubPE_Left()
{
}

void
ParseEnvState::Process_Default()
{
    if (bDefaultIsError)
        MyPE().SetResult(not_done, pop_failure);
    else    // ignore:
        MyPE().SetResult(done, stay);
}

}   // namespace uidl
}   // namespace csi

<commit_msg>INTEGRATION: CWS pchfix02 (1.3.6); FILE MERGED 2006/09/01 17:15:50 kaib 1.3.6.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pestate.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 17:12:15 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_autodoc.hxx"

#include <precomp.h>
#include <s2_luidl/pestate.hxx>

// NOT FULLY DEFINED SERVICES
#include <ary_i/codeinf2.hxx>
#include <s2_luidl/parsenv2.hxx>

namespace csi
{
namespace uidl
{

void
ParseEnvState::Process_Identifier( const TokIdentifier & )
{
    Process_Default();
}

void
ParseEnvState::Process_NameSeparator()
{
    Process_Default();
}

void
ParseEnvState::Process_Punctuation( const TokPunctuation & )
{
    Process_Default();
}

void
ParseEnvState::Process_BuiltInType( const TokBuiltInType & )
{
    Process_Default();
}

void
ParseEnvState::Process_TypeModifier( const TokTypeModifier & )
{
    Process_Default();
}

void
ParseEnvState::Process_MetaType( const TokMetaType &    )
{
    Process_Default();
}

void
ParseEnvState::Process_Stereotype( const TokStereotype & )
{
    Process_Default();
}

void
ParseEnvState::Process_ParameterHandling( const TokParameterHandling & )
{
    Process_Default();
}

void
ParseEnvState::Process_Raises()
{
    Process_Default();
}

void
ParseEnvState::Process_Needs()
{
    Process_Default();
}

void
ParseEnvState::Process_Observes()
{
    Process_Default();
}

void
ParseEnvState::Process_Assignment( const TokAssignment & )
{
    Process_Default();
}

void
ParseEnvState::Process_EOL()
{
    MyPE().SetResult(done,stay);
}

void
ParseEnvState::On_SubPE_Left()
{
}

void
ParseEnvState::Process_Default()
{
    if (bDefaultIsError)
        MyPE().SetResult(not_done, pop_failure);
    else    // ignore:
        MyPE().SetResult(done, stay);
}

}   // namespace uidl
}   // namespace csi

<|endoftext|>


<commit_before><commit_msg>Rewrite bug fix<commit_after><|endoftext|>


<commit_before>#include "Riostream.h"
#include "TROOT.h"
#include "TApplication.h"
#include "TCanvas.h"
#include "TH1.h"
#include "TSystem.h"
#include "TBrowser.h"
#include "TFile.h"
#include "TRandom.h"
#include "TMultiDimFit.h"
#include "TVectorD.h"

//____________________________________________________________________
void makeData(Double_t* x, Double_t& d, Double_t& e)
{
  // Make data points
  Double_t upp[5] = { 10, 10, 10, 10,  1 };
  Double_t low[5] = {  0,  0,  0,  0, .1 };
  for (int i = 0; i < 4; i++)
    x[i] = (upp[i] - low[i]) * gRandom->Rndm() + low[i];

  d = x[0] * TMath::Sqrt(x[1] * x[1] + x[2] * x[2] + x[3] * x[3]);

  e = gRandom->Gaus(upp[4],low[4]);
}

//____________________________________________________________________
int CompareResults(TMultiDimFit *fit)
{
   //Compare results with reference run

   // the right coefficients
  double GoodCoeffs[] = {
  -2.57988,
  43.2694,
  13.2747,
  13.4143,
  13.3844,
  13.4842,
  13.3206,
  13.3148,
  4.4177,
  -3.93429,
  4.60247,
  -4.07129,
  -3.99255,
  4.51781,
  3.45324,
  -4.15551,
  4.75041,
  4.28688,
  -3.85046,
  -4.0053,
  4.3955,
  3.59419};

// Good Powers
  int GoodPower[] = {
  1,  1,  1,  1,
  2,  1,  1,  1,
  1,  1,  1,  2,
  1,  1,  2,  1,
  1,  2,  1,  1,
  2,  2,  1,  1,
  2,  1,  1,  2,
  2,  1,  2,  1,
  1,  1,  1,  3,
  1,  2,  1,  2,
  1,  1,  3,  1,
  1,  2,  2,  1,
  1,  1,  2,  2,
  1,  3,  1,  1,
  1,  2,  2,  2,
  2,  2,  1,  2,
  2,  1,  3,  1,
  2,  1,  1,  3,
  2,  1,  2,  2,
  2,  2,  2,  1,
  2,  3,  1,  1,
  2,  2,  2,  2};

  Int_t nc = fit->GetNCoefficients();
  Int_t nv = fit->GetNVariables();
  const Int_t *powers = fit->GetPowers();
  const Int_t *pindex = fit->GetPowerIndex();
  if (nc != 22) return 1;
  const TVectorD *coeffs = fit->GetCoefficients();
  int k = 0;
  for (Int_t i=0;i<nc;i++) {
     if (TMath::Abs((*coeffs)[i] - GoodCoeffs[i]) > 5e-5) return 2;
     for (Int_t j=0;j<nv;j++) {
        if (powers[pindex[i]*nv+j] != GoodPower[k]) return 3;
        k++;
     }
  }
  return 0;
}

//____________________________________________________________________
Int_t multidimfit()
{

  cout << "*************************************************" << endl;
  cout << "*             Multidimensional Fit              *" << endl;
  cout << "*                                               *" << endl;
  cout << "* By Christian Holm <cholm@nbi.dk> 14/10/00     *" << endl;
  cout << "*************************************************" << endl;
  cout << endl;

  // Initialize global TRasnom object.
  gRandom = new TRandom();

  // Open output file
  TFile* output = new TFile("mdf.root", "RECREATE");

  // Global data parameters
  Int_t nVars       = 4;
  Int_t nData       = 500;

  // make fit object and set parameters on it.
  TMultiDimFit* fit = new TMultiDimFit(nVars, TMultiDimFit::kMonomials,"v");

  Int_t mPowers[]   = { 6 , 6, 6, 6 };
  fit->SetMaxPowers(mPowers);
  fit->SetMaxFunctions(1000);
  fit->SetMaxStudy(1000);
  fit->SetMaxTerms(30);
  fit->SetPowerLimit(1);
  fit->SetMinAngle(10);
  fit->SetMaxAngle(10);
  fit->SetMinRelativeError(.01);

  // variables to hold the temporary input data
  Double_t d;
  Double_t e;
  Double_t *x = new Double_t[nVars];

  // Print out the start parameters
  fit->Print("p");

  // Create training sample
  Int_t i;
  for (i = 0; i < nData ; i++) {

    // Make some data
    makeData(x,d,e);

    // Add the row to the fit object
    fit->AddRow(x,d,e);
  }

  // Print out the statistics
  fit->Print("s");

  // Book histograms
  fit->MakeHistograms();

  // Find the parameterization
  fit->FindParameterization();

  // Print coefficents
  fit->Print("rc");

  // Get the min and max of variables from the training sample, used
  // for cuts in test sample.
  Double_t *xMax = new Double_t[nVars];
  Double_t *xMin = new Double_t[nVars];
  for (i = 0; i < nVars; i++) {
    xMax[i] = (*fit->GetMaxVariables())(i);
    xMin[i] = (*fit->GetMinVariables())(i);
  }

  nData = fit->GetNCoefficients() * 100;
  Int_t j;

  // Create test sample
  for (i = 0; i < nData ; i++) {
    // Make some data
    makeData(x,d,e);

    for (j = 0; j < nVars; j++)
      if (x[j] < xMin[j] || x[j] > xMax[j])
	break;

    // If we get through the loop above, all variables are in range
    if (j == nVars)
      // Add the row to the fit object
      fit->AddTestRow(x,d,e);
    else
      i--;
  }
  delete gRandom;

  // Test the parameterizatio and coefficents using the test sample.
  fit->Fit();

  // Print result
  fit->Print("fc");

  // Write code to file
  fit->MakeCode();

  // Write histograms to disk, and close file
  output->Write();
  output->Close();
  delete output;

  // Compare results with reference run
  Int_t compare = CompareResults(fit);
  if (!compare) {
     printf("\nmultidimfit ..............................................  OK\n");
  } else {
     printf("\nmultidimfit ..............................................  fails case %d\n",compare);
  }

  // We're done
  delete fit;
  return compare;
}
<commit_msg>Add an additional test in the tutorial multidimfit.C. The generated function MDF.C is loaded and the function MDF is evaluated at one point and the result compared with a reference value.<commit_after>#include "Riostream.h"
#include "TROOT.h"
#include "TApplication.h"
#include "TCanvas.h"
#include "TH1.h"
#include "TSystem.h"
#include "TBrowser.h"
#include "TFile.h"
#include "TRandom.h"
#include "TMultiDimFit.h"
#include "TVectorD.h"

//____________________________________________________________________
void makeData(Double_t* x, Double_t& d, Double_t& e)
{
  // Make data points
  Double_t upp[5] = { 10, 10, 10, 10,  1 };
  Double_t low[5] = {  0,  0,  0,  0, .1 };
  for (int i = 0; i < 4; i++)
    x[i] = (upp[i] - low[i]) * gRandom->Rndm() + low[i];

  d = x[0] * TMath::Sqrt(x[1] * x[1] + x[2] * x[2] + x[3] * x[3]);

  e = gRandom->Gaus(upp[4],low[4]);
}

//____________________________________________________________________
int CompareResults(TMultiDimFit *fit)
{
   //Compare results with reference run

   // the right coefficients
  double GoodCoeffs[] = {
  -2.57988,
  43.2694,
  13.2747,
  13.4143,
  13.3844,
  13.4842,
  13.3206,
  13.3148,
  4.4177,
  -3.93429,
  4.60247,
  -4.07129,
  -3.99255,
  4.51781,
  3.45324,
  -4.15551,
  4.75041,
  4.28688,
  -3.85046,
  -4.0053,
  4.3955,
  3.59419};

// Good Powers
  int GoodPower[] = {
  1,  1,  1,  1,
  2,  1,  1,  1,
  1,  1,  1,  2,
  1,  1,  2,  1,
  1,  2,  1,  1,
  2,  2,  1,  1,
  2,  1,  1,  2,
  2,  1,  2,  1,
  1,  1,  1,  3,
  1,  2,  1,  2,
  1,  1,  3,  1,
  1,  2,  2,  1,
  1,  1,  2,  2,
  1,  3,  1,  1,
  1,  2,  2,  2,
  2,  2,  1,  2,
  2,  1,  3,  1,
  2,  1,  1,  3,
  2,  1,  2,  2,
  2,  2,  2,  1,
  2,  3,  1,  1,
  2,  2,  2,  2};

  Int_t nc = fit->GetNCoefficients();
  Int_t nv = fit->GetNVariables();
  const Int_t *powers = fit->GetPowers();
  const Int_t *pindex = fit->GetPowerIndex();
  if (nc != 22) return 1;
  const TVectorD *coeffs = fit->GetCoefficients();
  int k = 0;
  for (Int_t i=0;i<nc;i++) {
     if (TMath::Abs((*coeffs)[i] - GoodCoeffs[i]) > 5e-5) return 2;
     for (Int_t j=0;j<nv;j++) {
        if (powers[pindex[i]*nv+j] != GoodPower[k]) return 3;
        k++;
     }
  }

  // now test the result of the generated function
  gROOT->ProcessLine(".L MDF.C");
  Double_t x[]    = {5,5,5,5};
  Double_t refMDF = 43.4507;
  Double_t rMDF   = MDF(x);
  if (TMath::Abs(rMDF -43.4507) > 1e-4) return 4;
  return 0;
}

//____________________________________________________________________
Int_t multidimfit()
{

  cout << "*************************************************" << endl;
  cout << "*             Multidimensional Fit              *" << endl;
  cout << "*                                               *" << endl;
  cout << "* By Christian Holm <cholm@nbi.dk> 14/10/00     *" << endl;
  cout << "*************************************************" << endl;
  cout << endl;

  // Initialize global TRannom object.
  gRandom = new TRandom();

  // Open output file
  TFile* output = new TFile("mdf.root", "RECREATE");

  // Global data parameters
  Int_t nVars       = 4;
  Int_t nData       = 500;
  Double_t x[4];

  // make fit object and set parameters on it.
  TMultiDimFit* fit = new TMultiDimFit(nVars, TMultiDimFit::kMonomials,"v");

  Int_t mPowers[]   = { 6 , 6, 6, 6 };
  fit->SetMaxPowers(mPowers);
  fit->SetMaxFunctions(1000);
  fit->SetMaxStudy(1000);
  fit->SetMaxTerms(30);
  fit->SetPowerLimit(1);
  fit->SetMinAngle(10);
  fit->SetMaxAngle(10);
  fit->SetMinRelativeError(.01);

  // variables to hold the temporary input data
  Double_t d;
  Double_t e;

  // Print out the start parameters
  fit->Print("p");

  // Create training sample
  Int_t i;
  for (i = 0; i < nData ; i++) {

    // Make some data
    makeData(x,d,e);

    // Add the row to the fit object
    fit->AddRow(x,d,e);
  }

  // Print out the statistics
  fit->Print("s");

  // Book histograms
  fit->MakeHistograms();

  // Find the parameterization
  fit->FindParameterization();

  // Print coefficents
  fit->Print("rc");

  // Get the min and max of variables from the training sample, used
  // for cuts in test sample.
  Double_t *xMax = new Double_t[nVars];
  Double_t *xMin = new Double_t[nVars];
  for (i = 0; i < nVars; i++) {
    xMax[i] = (*fit->GetMaxVariables())(i);
    xMin[i] = (*fit->GetMinVariables())(i);
  }

  nData = fit->GetNCoefficients() * 100;
  Int_t j;

  // Create test sample
  for (i = 0; i < nData ; i++) {
    // Make some data
    makeData(x,d,e);

    for (j = 0; j < nVars; j++)
      if (x[j] < xMin[j] || x[j] > xMax[j])
	break;

    // If we get through the loop above, all variables are in range
    if (j == nVars)
      // Add the row to the fit object
      fit->AddTestRow(x,d,e);
    else
      i--;
  }
  delete gRandom;

  // Test the parameterizatio and coefficents using the test sample.
  fit->Fit();

  // Print result
  fit->Print("fc");

  // Write code to file
  fit->MakeCode();

  // Write histograms to disk, and close file
  output->Write();
  output->Close();
  delete output;

  // Compare results with reference run
  Int_t compare = CompareResults(fit);
  if (!compare) {
     printf("\nmultidimfit ..............................................  OK\n");
  } else {
     printf("\nmultidimfit ..............................................  fails case %d\n",compare);
  }

  // We're done
  delete fit;
  return compare;
}
<|endoftext|>


<commit_before><commit_msg>Minor changes in UI button and button icon rendering function<commit_after><|endoftext|>


<commit_before>#include "repo_log.h"

#if BOOST_VERSION > 105700
#include <boost/core/null_deleter.hpp>
#else
#include <boost/utility/empty_deleter.hpp>
#endif

#include <boost/iostreams/stream.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <ctime>

using namespace repo::lib;

using text_sink = boost::log::sinks::synchronous_sink < boost::log::sinks::text_ostream_backend >;

// Cannot use repo_utils.h -> for some reason it switches the headers for :toupper.
std::string getEnvString(std::string const & envVarName)
{
	char* value = getenv(envVarName.c_str());
	return (value && strlen(value) > 0) ? value : "";
}

RepoLog::RepoLog()
{
	std::string logDir = getEnvString("REPO_LOG_DIR").empty() ? "./log/" : logDir;
	this->logToFile(logDir);

	std::string debug = getEnvString("REPO_DEBUG");
	std::string verbose = getEnvString("REPO_VERBOSE");
	if (!verbose.empty())
	{
		this->setLoggingLevel(repo::lib::RepoLog::RepoLogLevel::TRACE);
	}
	else if (!debug.empty())
	{
		this->setLoggingLevel(repo::lib::RepoLog::RepoLogLevel::DEBUG);
	}
	else
	{
		this->setLoggingLevel(repo::lib::RepoLog::RepoLogLevel::INFO);
	}
}
RepoLog::~RepoLog()
{
}

void RepoLog::log(
	const RepoLogLevel &severity,
	const std::string  &msg)
{
	switch (severity)
	{
	case RepoLogLevel::TRACE:
		repoTrace << msg;
		break;
	case RepoLogLevel::DEBUG:
		repoDebug << msg;
		break;
	case RepoLogLevel::INFO:
		repoInfo << msg;
		break;
	case RepoLogLevel::WARNING:
		repoWarning << msg;
		break;
	case RepoLogLevel::ERR:
		repoError << msg;
		break;
	case RepoLogLevel::FATAL:
		repoFatal << msg;
	}
}

BOOST_LOG_ATTRIBUTE_KEYWORD(timestamp, "TimeStamp", boost::posix_time::ptime)
BOOST_LOG_ATTRIBUTE_KEYWORD(threadid, "ThreadID", boost::log::attributes::current_thread_id::value_type)

static std::string getTimeAsString()
{
	time_t rawtime;
	struct tm * timeinfo;
	char buffer[80];

	time(&rawtime);
	timeinfo = localtime(&rawtime);

	strftime(buffer, 80, "%Y-%m-%d_%Hh%Mm%S", timeinfo);
	return std::string(buffer);
}

void RepoLog::logToFile(const std::string &filePath)
{
	boost::filesystem::path logPath(filePath);
	std::string fileName;
	// a directory is given
	std::string name = getTimeAsString() + "_%N.log";
	fileName = (logPath / name).string();

	boost::log::add_file_log
	(
		boost::log::keywords::file_name = fileName,
		boost::log::keywords::rotation_size = 10 * 1024 * 1024,
		boost::log::keywords::time_based_rotation = boost::log::sinks::file::rotation_at_time_point(0, 0, 0),
		boost::log::keywords::auto_flush = true,
		boost::log::keywords::format = (
			boost::log::expressions::stream
			<< "[" << boost::log::expressions::format_date_time(timestamp, "%Y-%m-%d %H:%M:%S") << "]"
			<< "(" << threadid << ") <" << boost::log::trivial::severity
			<< ">"
			<< ": " << boost::log::expressions::smessage
			));
	boost::log::add_common_attributes();

	repoInfo << "Log file registered: " << filePath;
}

void RepoLog::setLoggingLevel(const RepoLogLevel &level)
{
	boost::log::trivial::severity_level loggingLevel;
	switch (level)
	{
	case repo::lib::RepoLog::RepoLogLevel::TRACE:
		loggingLevel = boost::log::trivial::trace;
		break;
	case repo::lib::RepoLog::RepoLogLevel::DEBUG:
		loggingLevel = boost::log::trivial::debug;
		break;
	case repo::lib::RepoLog::RepoLogLevel::INFO:
		loggingLevel = boost::log::trivial::info;
		break;
	case repo::lib::RepoLog::RepoLogLevel::WARNING:
		loggingLevel = boost::log::trivial::warning;
		break;
	case repo::lib::RepoLog::RepoLogLevel::ERR:
		loggingLevel = boost::log::trivial::error;
		break;
	case repo::lib::RepoLog::RepoLogLevel::FATAL:
		loggingLevel = boost::log::trivial::fatal;
		break;
	default:
		repoError << "Unknown log level: " << (int)level;
		return;
	}

	boost::log::core::get()->set_filter(
		boost::log::trivial::severity >= loggingLevel);
}

void RepoLog::subscribeBroadcaster(RepoBroadcaster *broadcaster) {
	boost::iostreams::stream<RepoBroadcaster> *streamptr =
		new boost::iostreams::stream<RepoBroadcaster>(*broadcaster);

#if BOOST_VERSION > 105700
	boost::shared_ptr< std::ostream > stream(
		streamptr, boost::null_deleter());
#else
	boost::shared_ptr< std::ostream > stream(
		streamptr, boost::empty_deleter());
#endif

	boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >();

	sink->set_filter(boost::log::trivial::severity >= boost::log::trivial::trace);
	//FIXME: better format!
	sink->set_formatter
	(
		boost::log::expressions::stream
		<< "%" << boost::log::trivial::severity << "%"
		<< boost::log::expressions::smessage);

	sink->locked_backend()->add_stream(stream);
	sink->locked_backend()->auto_flush(true);

	// Register the sink in the logging core
	boost::log::core::get()->add_sink(sink);
}

void RepoLog::subscribeListeners(
	const std::vector<RepoAbstractListener*> &listeners)
{
	/*
		FIXME: ideally, we should have a single broadcaster for the application
		and you should only need to add the listeners when you subscribe
		But the whole hackery of making a broadcaster to be a ostream
		to tap into the boost logger made this really difficult
		so for now, instantiate a new broadcaster everytime.
		And I will review this on a braver day...
		*/
	RepoBroadcaster *broadcaster = new RepoBroadcaster();

	for (auto listener : listeners)
		broadcaster->subscribe(listener);

	subscribeBroadcaster(broadcaster);
}<commit_msg>ISSUE #519 dump out log dir to stdout<commit_after>#include "repo_log.h"

#if BOOST_VERSION > 105700
#include <boost/core/null_deleter.hpp>
#else
#include <boost/utility/empty_deleter.hpp>
#endif

#include <boost/iostreams/stream.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <ctime>

using namespace repo::lib;

using text_sink = boost::log::sinks::synchronous_sink < boost::log::sinks::text_ostream_backend >;

// Cannot use repo_utils.h -> for some reason it switches the headers for :toupper.
std::string getEnvString(std::string const & envVarName)
{
	char* value = getenv(envVarName.c_str());
	return (value && strlen(value) > 0) ? value : "";
}

RepoLog::RepoLog()
{
	std::string logDir = getEnvString("REPO_LOG_DIR").empty() ? "./log/" : logDir;
	std::cout << "Logging directory is set to " << logDir;
	this->logToFile(logDir);

	std::string debug = getEnvString("REPO_DEBUG");
	std::string verbose = getEnvString("REPO_VERBOSE");
	if (!verbose.empty())
	{
		this->setLoggingLevel(repo::lib::RepoLog::RepoLogLevel::TRACE);
	}
	else if (!debug.empty())
	{
		this->setLoggingLevel(repo::lib::RepoLog::RepoLogLevel::DEBUG);
	}
	else
	{
		this->setLoggingLevel(repo::lib::RepoLog::RepoLogLevel::INFO);
	}
}
RepoLog::~RepoLog()
{
}

void RepoLog::log(
	const RepoLogLevel &severity,
	const std::string  &msg)
{
	switch (severity)
	{
	case RepoLogLevel::TRACE:
		repoTrace << msg;
		break;
	case RepoLogLevel::DEBUG:
		repoDebug << msg;
		break;
	case RepoLogLevel::INFO:
		repoInfo << msg;
		break;
	case RepoLogLevel::WARNING:
		repoWarning << msg;
		break;
	case RepoLogLevel::ERR:
		repoError << msg;
		break;
	case RepoLogLevel::FATAL:
		repoFatal << msg;
	}
}

BOOST_LOG_ATTRIBUTE_KEYWORD(timestamp, "TimeStamp", boost::posix_time::ptime)
BOOST_LOG_ATTRIBUTE_KEYWORD(threadid, "ThreadID", boost::log::attributes::current_thread_id::value_type)

static std::string getTimeAsString()
{
	time_t rawtime;
	struct tm * timeinfo;
	char buffer[80];

	time(&rawtime);
	timeinfo = localtime(&rawtime);

	strftime(buffer, 80, "%Y-%m-%d_%Hh%Mm%S", timeinfo);
	return std::string(buffer);
}

void RepoLog::logToFile(const std::string &filePath)
{
	boost::filesystem::path logPath(filePath);
	std::string fileName;
	// a directory is given
	std::string name = getTimeAsString() + "_%N.log";
	fileName = (logPath / name).string();

	boost::log::add_file_log
	(
		boost::log::keywords::file_name = fileName,
		boost::log::keywords::rotation_size = 10 * 1024 * 1024,
		boost::log::keywords::time_based_rotation = boost::log::sinks::file::rotation_at_time_point(0, 0, 0),
		boost::log::keywords::auto_flush = true,
		boost::log::keywords::format = (
			boost::log::expressions::stream
			<< "[" << boost::log::expressions::format_date_time(timestamp, "%Y-%m-%d %H:%M:%S") << "]"
			<< "(" << threadid << ") <" << boost::log::trivial::severity
			<< ">"
			<< ": " << boost::log::expressions::smessage
			));
	boost::log::add_common_attributes();

	repoInfo << "Log file registered: " << filePath;
}

void RepoLog::setLoggingLevel(const RepoLogLevel &level)
{
	boost::log::trivial::severity_level loggingLevel;
	switch (level)
	{
	case repo::lib::RepoLog::RepoLogLevel::TRACE:
		loggingLevel = boost::log::trivial::trace;
		break;
	case repo::lib::RepoLog::RepoLogLevel::DEBUG:
		loggingLevel = boost::log::trivial::debug;
		break;
	case repo::lib::RepoLog::RepoLogLevel::INFO:
		loggingLevel = boost::log::trivial::info;
		break;
	case repo::lib::RepoLog::RepoLogLevel::WARNING:
		loggingLevel = boost::log::trivial::warning;
		break;
	case repo::lib::RepoLog::RepoLogLevel::ERR:
		loggingLevel = boost::log::trivial::error;
		break;
	case repo::lib::RepoLog::RepoLogLevel::FATAL:
		loggingLevel = boost::log::trivial::fatal;
		break;
	default:
		repoError << "Unknown log level: " << (int)level;
		return;
	}

	boost::log::core::get()->set_filter(
		boost::log::trivial::severity >= loggingLevel);
}

void RepoLog::subscribeBroadcaster(RepoBroadcaster *broadcaster) {
	boost::iostreams::stream<RepoBroadcaster> *streamptr =
		new boost::iostreams::stream<RepoBroadcaster>(*broadcaster);

#if BOOST_VERSION > 105700
	boost::shared_ptr< std::ostream > stream(
		streamptr, boost::null_deleter());
#else
	boost::shared_ptr< std::ostream > stream(
		streamptr, boost::empty_deleter());
#endif

	boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >();

	sink->set_filter(boost::log::trivial::severity >= boost::log::trivial::trace);
	//FIXME: better format!
	sink->set_formatter
	(
		boost::log::expressions::stream
		<< "%" << boost::log::trivial::severity << "%"
		<< boost::log::expressions::smessage);

	sink->locked_backend()->add_stream(stream);
	sink->locked_backend()->auto_flush(true);

	// Register the sink in the logging core
	boost::log::core::get()->add_sink(sink);
}

void RepoLog::subscribeListeners(
	const std::vector<RepoAbstractListener*> &listeners)
{
	/*
		FIXME: ideally, we should have a single broadcaster for the application
		and you should only need to add the listeners when you subscribe
		But the whole hackery of making a broadcaster to be a ostream
		to tap into the boost logger made this really difficult
		so for now, instantiate a new broadcaster everytime.
		And I will review this on a braver day...
		*/
	RepoBroadcaster *broadcaster = new RepoBroadcaster();

	for (auto listener : listeners)
		broadcaster->subscribe(listener);

	subscribeBroadcaster(broadcaster);
}<|endoftext|>


<commit_before>/**
 *  @file api_tests.cpp
 *  @copyright defined in eos/LICENSE.txt
 */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsign-compare"
#include <boost/test/unit_test.hpp>
#pragma GCC diagnostic pop

#include <eosio/testing/tester.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/resource_limits.hpp>

#include <fc/exception/exception.hpp>
#include <fc/variant_object.hpp>

#include "eosio_system_tester.hpp"

#include <test_ram_limit/test_ram_limit.abi.hpp>
#include <test_ram_limit/test_ram_limit.wast.hpp>

#define DISABLE_EOSLIB_SERIALIZE
#include <test_api/test_api_common.hpp>

/*
 * register test suite `ram_tests`
 */
BOOST_AUTO_TEST_SUITE(ram_tests)

/*************************************************************************************
 * ram_tests test case
 *************************************************************************************/
BOOST_FIXTURE_TEST_CASE(ram_tests, eosio_system::eosio_system_tester) { try {
   auto init_request_bytes = 80000;
   const auto increment_contract_bytes = 10000;
   const auto table_allocation_bytes = 12000;
   BOOST_REQUIRE_MESSAGE(table_allocation_bytes > increment_contract_bytes, "increment_contract_bytes must be less than table_allocation_bytes for this test setup to work");
   buyrambytes(N(eosio), N(eosio), 70000);
   produce_blocks(10);
   create_account_with_resources(N(testram11111),N(eosio), init_request_bytes);
   create_account_with_resources(N(testram22222),N(eosio), init_request_bytes);
   produce_blocks(10);
   BOOST_REQUIRE_EQUAL( success(), stake( "eosio", "testram11111", core_from_string("10.0000"), core_from_string("5.0000") ) );
   produce_blocks(10);

   for (auto i = 0; i < 10; ++i) {
      try {
         set_code( N(testram11111), test_ram_limit_wast );
         break;
      } catch (const ram_usage_exceeded&) {
         init_request_bytes += increment_contract_bytes;
         buyrambytes(N(eosio), N(testram11111), increment_contract_bytes);
         buyrambytes(N(eosio), N(testram22222), increment_contract_bytes);
      }
   }
   produce_blocks(10);

   for (auto i = 0; i < 10; ++i) {
      try {
         set_abi( N(testram11111), test_ram_limit_abi );
         break;
      } catch (const ram_usage_exceeded&) {
         init_request_bytes += increment_contract_bytes;
         buyrambytes(N(eosio), N(testram11111), increment_contract_bytes);
         buyrambytes(N(eosio), N(testram22222), increment_contract_bytes);
      }
   }
   produce_blocks(10);
   set_code( N(testram22222), test_ram_limit_wast );
   set_abi( N(testram22222), test_ram_limit_abi );
   produce_blocks(10);

   auto total = get_total_stake( N(testram11111) );
   const auto init_bytes =  total["ram_bytes"].as_uint64();

   auto rlm = control->get_resource_limits_manager();
   auto initial_ram_usage = rlm.get_account_ram_usage(N(testram11111));

   // calculate how many more bytes we need to have table_allocation_bytes for database stores
   auto more_ram = table_allocation_bytes + init_bytes - init_request_bytes;
   BOOST_REQUIRE_MESSAGE(more_ram >= 0, "Underlying understanding changed, need to reduce size of init_request_bytes");
   wdump((init_bytes)(initial_ram_usage)(init_request_bytes)(more_ram) );
   buyrambytes(N(eosio), N(testram11111), more_ram);
   buyrambytes(N(eosio), N(testram22222), more_ram);

   TESTER* tester = this;
   // allocate just under the allocated bytes
   tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                        ("payer", "testram11111")
                        ("from", 1)
                        ("to", 10)
                        ("size", 1910));
   produce_blocks(1);
   auto ram_usage = rlm.get_account_ram_usage(N(testram11111));

   total = get_total_stake( N(testram11111) );
   const auto ram_bytes =  total["ram_bytes"].as_uint64();
   wdump((ram_bytes)(ram_usage)(initial_ram_usage)(init_bytes)(ram_usage - initial_ram_usage)(init_bytes - ram_usage) );

   wlog("ram_tests 1    %%%%%%");
   // allocate just beyond the allocated bytes
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                           ("payer", "testram11111")
                           ("from", 1)
                           ("to", 10)
                           ("size", 1920)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram11111 has insufficient ram"));
   wlog("ram_tests 2    %%%%%%");
   produce_blocks(1);
   BOOST_REQUIRE_EQUAL(ram_usage, rlm.get_account_ram_usage(N(testram11111)));

   // update the entries with smaller allocations so that we can verify space is freed and new allocations can be made
   tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                        ("payer", "testram11111")
                        ("from", 1)
                        ("to", 10)
                        ("size", 1810));
   produce_blocks(1);
   BOOST_REQUIRE_EQUAL(ram_usage - 1000, rlm.get_account_ram_usage(N(testram11111)));

   // verify the added entry is beyond the allocation bytes limit
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                           ("payer", "testram11111")
                           ("from", 1)
                           ("to", 11)
                           ("size", 1810)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram11111 has insufficient ram"));
   produce_blocks(1);
   BOOST_REQUIRE_EQUAL(ram_usage - 1000, rlm.get_account_ram_usage(N(testram11111)));

   // verify the new entry's bytes minus the freed up bytes for existing entries still exceeds the allocation bytes limit
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                           ("payer", "testram11111")
                           ("from", 1)
                           ("to", 11)
                           ("size", 1760)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram11111 has insufficient ram"));
   produce_blocks(1);
   BOOST_REQUIRE_EQUAL(ram_usage - 1000, rlm.get_account_ram_usage(N(testram11111)));

   // verify the new entry's bytes minus the freed up bytes for existing entries are under the allocation bytes limit
   tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                        ("payer", "testram11111")
                        ("from", 1)
                        ("to", 11)
                        ("size", 1720));
   produce_blocks(1);

   tester->push_action( N(testram11111), N(rmentry), N(testram11111), mvo()
                        ("from", 3)
                        ("to", 3));
   produce_blocks(1);

   // verify that the new entry will exceed the allocation bytes limit
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                           ("payer", "testram11111")
                           ("from", 12)
                           ("to", 12)
                           ("size", 1900)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram11111 has insufficient ram"));
   produce_blocks(1);

   // verify that the new entry is under the allocation bytes limit
   tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                        ("payer", "testram11111")
                        ("from", 12)
                        ("to", 12)
                        ("size", 1720));
   produce_blocks(1);

   // verify that anoth new entry will exceed the allocation bytes limit, to setup testing of new payer
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                           ("payer", "testram11111")
                           ("from", 13)
                           ("to", 13)
                           ("size", 1720)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram11111 has insufficient ram"));
   produce_blocks(1);

   // verify that the new entry is under the allocation bytes limit
   tester->push_action( N(testram11111), N(setentry), {N(testram11111),N(testram22222)}, mvo()
                        ("payer", "testram22222")
                        ("from", 12)
                        ("to", 12)
                        ("size", 1720));
   produce_blocks(1);

   // verify that another new entry that is too big will exceed the allocation bytes limit, to setup testing of new payer
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                           ("payer", "testram11111")
                           ("from", 13)
                           ("to", 13)
                           ("size", 1900)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram11111 has insufficient ram"));
   produce_blocks(1);

   wlog("ram_tests 18    %%%%%%");
   // verify that the new entry is under the allocation bytes limit, because entry 12 is now charged to testram22222
   tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                        ("payer", "testram11111")
                        ("from", 13)
                        ("to", 13)
                        ("size", 1720));
   produce_blocks(1);

   // verify that new entries for testram22222 exceed the allocation bytes limit
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), {N(testram11111),N(testram22222)}, mvo()
                           ("payer", "testram22222")
                           ("from", 12)
                           ("to", 21)
                           ("size", 1930)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram22222 has insufficient ram"));
   produce_blocks(1);

   // verify that new entries for testram22222 are under the allocation bytes limit
   tester->push_action( N(testram11111), N(setentry), {N(testram11111),N(testram22222)}, mvo()
                        ("payer", "testram22222")
                        ("from", 12)
                        ("to", 21)
                        ("size", 1910));
   produce_blocks(1);

   // verify that new entry for testram22222 exceed the allocation bytes limit
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), {N(testram11111),N(testram22222)}, mvo()
                           ("payer", "testram22222")
                           ("from", 22)
                           ("to", 22)
                           ("size", 1910)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram22222 has insufficient ram"));
   produce_blocks(1);

   tester->push_action( N(testram11111), N(rmentry), N(testram11111), mvo()
                        ("from", 20)
                        ("to", 20));
   produce_blocks(1);

   // verify that new entry for testram22222 are under the allocation bytes limit
   tester->push_action( N(testram11111), N(setentry), {N(testram11111),N(testram22222)}, mvo()
                        ("payer", "testram22222")
                        ("from", 22)
                        ("to", 22)
                        ("size", 1910));
   produce_blocks(1);
} FC_LOG_AND_RETHROW() }

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fixed part of ram_tests<commit_after>/**
 *  @file api_tests.cpp
 *  @copyright defined in eos/LICENSE.txt
 */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsign-compare"
#include <boost/test/unit_test.hpp>
#pragma GCC diagnostic pop

#include <eosio/testing/tester.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/resource_limits.hpp>

#include <fc/exception/exception.hpp>
#include <fc/variant_object.hpp>

#include "eosio_system_tester.hpp"

#include <test_ram_limit/test_ram_limit.abi.hpp>
#include <test_ram_limit/test_ram_limit.wast.hpp>

#define DISABLE_EOSLIB_SERIALIZE
#include <test_api/test_api_common.hpp>

/*
 * register test suite `ram_tests`
 */
BOOST_AUTO_TEST_SUITE(ram_tests)

/*************************************************************************************
 * ram_tests test case
 *************************************************************************************/
BOOST_FIXTURE_TEST_CASE(ram_tests, eosio_system::eosio_system_tester) { try {
   auto init_request_bytes = 80000;
   const auto increment_contract_bytes = 10000;
   const auto table_allocation_bytes = 12000;
   BOOST_REQUIRE_MESSAGE(table_allocation_bytes > increment_contract_bytes, "increment_contract_bytes must be less than table_allocation_bytes for this test setup to work");
   buyrambytes(N(eosio), N(eosio), 70000);
   produce_blocks(10);
   create_account_with_resources(N(testram11111),N(eosio), init_request_bytes);
   create_account_with_resources(N(testram22222),N(eosio), init_request_bytes);
   produce_blocks(10);
   BOOST_REQUIRE_EQUAL( success(), stake( "eosio.stake", "testram11111", core_from_string("10.0000"), core_from_string("5.0000") ) );
   produce_blocks(10);

   for (auto i = 0; i < 10; ++i) {
      try {
         set_code( N(testram11111), test_ram_limit_wast );
         break;
      } catch (const ram_usage_exceeded&) {
         init_request_bytes += increment_contract_bytes;
         buyrambytes(N(eosio), N(testram11111), increment_contract_bytes);
         buyrambytes(N(eosio), N(testram22222), increment_contract_bytes);
      }
   }
   produce_blocks(10);

   for (auto i = 0; i < 10; ++i) {
      try {
         set_abi( N(testram11111), test_ram_limit_abi );
         break;
      } catch (const ram_usage_exceeded&) {
         init_request_bytes += increment_contract_bytes;
         buyrambytes(N(eosio), N(testram11111), increment_contract_bytes);
         buyrambytes(N(eosio), N(testram22222), increment_contract_bytes);
      }
   }
   produce_blocks(10);
   set_code( N(testram22222), test_ram_limit_wast );
   set_abi( N(testram22222), test_ram_limit_abi );
   produce_blocks(10);

   auto total = get_total_stake( N(testram11111) );
   const auto init_bytes =  total["ram_bytes"].as_uint64();

   auto rlm = control->get_resource_limits_manager();
   auto initial_ram_usage = rlm.get_account_ram_usage(N(testram11111));

   // calculate how many more bytes we need to have table_allocation_bytes for database stores
   auto more_ram = table_allocation_bytes + init_bytes - init_request_bytes;
   BOOST_REQUIRE_MESSAGE(more_ram >= 0, "Underlying understanding changed, need to reduce size of init_request_bytes");
   wdump((init_bytes)(initial_ram_usage)(init_request_bytes)(more_ram) );
   buyrambytes(N(eosio), N(testram11111), more_ram);
   buyrambytes(N(eosio), N(testram22222), more_ram);

   TESTER* tester = this;
   // allocate just under the allocated bytes
   tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                        ("payer", "testram11111")
                        ("from", 1)
                        ("to", 10)
                        ("size", 1780 /*1910*/));
   produce_blocks(1);
   auto ram_usage = rlm.get_account_ram_usage(N(testram11111));

   total = get_total_stake( N(testram11111) );
   const auto ram_bytes =  total["ram_bytes"].as_uint64();
   wdump((ram_bytes)(ram_usage)(initial_ram_usage)(init_bytes)(ram_usage - initial_ram_usage)(init_bytes - ram_usage) );

   wlog("ram_tests 1    %%%%%%");
   // allocate just beyond the allocated bytes
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                           ("payer", "testram11111")
                           ("from", 1)
                           ("to", 10)
                           ("size", 1790 /*1920*/)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram11111 has insufficient ram"));
   wlog("ram_tests 2    %%%%%%");
   produce_blocks(1);
   BOOST_REQUIRE_EQUAL(ram_usage, rlm.get_account_ram_usage(N(testram11111)));

   // update the entries with smaller allocations so that we can verify space is freed and new allocations can be made
   tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                        ("payer", "testram11111")
                        ("from", 1)
                        ("to", 10)
                        ("size", 1680/*1810*/));
   produce_blocks(1);
   BOOST_REQUIRE_EQUAL(ram_usage - 1000, rlm.get_account_ram_usage(N(testram11111)));

   // verify the added entry is beyond the allocation bytes limit
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                           ("payer", "testram11111")
                           ("from", 1)
                           ("to", 11)
                           ("size", 1680/*1810*/)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram11111 has insufficient ram"));
   produce_blocks(1);
   BOOST_REQUIRE_EQUAL(ram_usage - 1000, rlm.get_account_ram_usage(N(testram11111)));

   // verify the new entry's bytes minus the freed up bytes for existing entries still exceeds the allocation bytes limit
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                           ("payer", "testram11111")
                           ("from", 1)
                           ("to", 11)
                           ("size", 1760)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram11111 has insufficient ram"));
   produce_blocks(1);
   BOOST_REQUIRE_EQUAL(ram_usage - 1000, rlm.get_account_ram_usage(N(testram11111)));

   // verify the new entry's bytes minus the freed up bytes for existing entries are under the allocation bytes limit
   tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                        ("payer", "testram11111")
                        ("from", 1)
                        ("to", 11)
                        ("size", 1600/*1720*/));
   produce_blocks(1);

   tester->push_action( N(testram11111), N(rmentry), N(testram11111), mvo()
                        ("from", 3)
                        ("to", 3));
   produce_blocks(1);

   // verify that the new entry will exceed the allocation bytes limit
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                           ("payer", "testram11111")
                           ("from", 12)
                           ("to", 12)
                           ("size", 1780)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram11111 has insufficient ram"));
   produce_blocks(1);

   // verify that the new entry is under the allocation bytes limit
   tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                        ("payer", "testram11111")
                        ("from", 12)
                        ("to", 12)
                        ("size", 1620/*1720*/));
   produce_blocks(1);

   // verify that anoth new entry will exceed the allocation bytes limit, to setup testing of new payer
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                           ("payer", "testram11111")
                           ("from", 13)
                           ("to", 13)
                           ("size", 1660)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram11111 has insufficient ram"));
   produce_blocks(1);

#if 0
   // verify that the new entry is under the allocation bytes limit
   tester->push_action( N(testram11111), N(setentry), {N(testram11111),N(testram22222)}, mvo()
                        ("payer", "testram22222")
                        ("from", 12)
                        ("to", 12)
                        ("size", 1720));
   produce_blocks(1);

   // verify that another new entry that is too big will exceed the allocation bytes limit, to setup testing of new payer
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                           ("payer", "testram11111")
                           ("from", 13)
                           ("to", 13)
                           ("size", 1900)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram11111 has insufficient ram"));
   produce_blocks(1);

   wlog("ram_tests 18    %%%%%%");
   // verify that the new entry is under the allocation bytes limit, because entry 12 is now charged to testram22222
   tester->push_action( N(testram11111), N(setentry), N(testram11111), mvo()
                        ("payer", "testram11111")
                        ("from", 13)
                        ("to", 13)
                        ("size", 1720));
   produce_blocks(1);

   // verify that new entries for testram22222 exceed the allocation bytes limit
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), {N(testram11111),N(testram22222)}, mvo()
                           ("payer", "testram22222")
                           ("from", 12)
                           ("to", 21)
                           ("size", 1930)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram22222 has insufficient ram"));
   produce_blocks(1);

   // verify that new entries for testram22222 are under the allocation bytes limit
   tester->push_action( N(testram11111), N(setentry), {N(testram11111),N(testram22222)}, mvo()
                        ("payer", "testram22222")
                        ("from", 12)
                        ("to", 21)
                        ("size", 1910));
   produce_blocks(1);

   // verify that new entry for testram22222 exceed the allocation bytes limit
   BOOST_REQUIRE_EXCEPTION(
      tester->push_action( N(testram11111), N(setentry), {N(testram11111),N(testram22222)}, mvo()
                           ("payer", "testram22222")
                           ("from", 22)
                           ("to", 22)
                           ("size", 1910)),
                           ram_usage_exceeded,
                           fc_exception_message_starts_with("account testram22222 has insufficient ram"));
   produce_blocks(1);

   tester->push_action( N(testram11111), N(rmentry), N(testram11111), mvo()
                        ("from", 20)
                        ("to", 20));
   produce_blocks(1);

   // verify that new entry for testram22222 are under the allocation bytes limit
   tester->push_action( N(testram11111), N(setentry), {N(testram11111),N(testram22222)}, mvo()
                        ("payer", "testram22222")
                        ("from", 22)
                        ("to", 22)
                        ("size", 1910));
   produce_blocks(1);
#endif
} FC_LOG_AND_RETHROW() }

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include <algorithm>
#include "dxcpp.h"
#include "SimpleHttp.h"

// Example environment variables
//
// APISERVER_PORT=8124
// APISERVER_HOST=localhost
// SECURITY_CONTEXT='{"auth_token":"outside","auth_token_type":"Bearer"}'

using namespace std;
using namespace dx;

bool g_ENV_LOADED = false;

string g_APISERVER_HOST;
string g_APISERVER_PORT;
string g_APISERVER;
JSON g_SECURITY_CONTEXT;

JSON DXHTTPRequest(const string &resource, const string &data,
		   const map<string, string> &headers) {
  if (!g_ENV_LOADED) {
    loadFromEnvironment();
    g_ENV_LOADED = true;
  }

  string url = g_APISERVER + resource;

  HttpHeaders req_headers;
  JSON secContext = g_SECURITY_CONTEXT;
  req_headers["Authorization"] = secContext["auth_token_type"].get<string>() +
    " " + secContext["auth_token"].get<string>();

  string headername;
  bool content_type_set = false;
  for (map<string, string>::const_iterator iter = headers.begin();
       iter != headers.end();
       iter++) {
    headername = iter->first;
    req_headers[headername] = iter->second;

    transform(headername.begin(), headername.end(), headername.begin(), ::tolower);
    if (headername == "content-type")
      content_type_set = true;
  }

  if (!content_type_set)
    req_headers["Content-Type"] = "application/json";

  HttpClientRequest req;

  // Attempt a POST request
  req.setUrl(url);
  req.setReqData(data.data(), data.size());
  req.setMethod("POST");
  req.setHeaders(req_headers);
  req.send();

  if (req.responseCode != 200) {
    JSON respJSON = JSON::parse(req.respData);
    throw DXAPIError(respJSON["error"]["type"].get<string>(),
    		     respJSON["error"]["message"].get<string>(),
    		     req.responseCode);
  }

  return JSON::parse(req.respData);
}

void setAPIServerInfo(const string &host,
		      int port,
		      const string &protocol) {
  g_APISERVER_HOST = host;
  char portstr[10];
  sprintf(portstr, "%d", port);
  g_APISERVER_PORT = string(portstr);
  g_APISERVER = protocol + "://" + host + ":" + g_APISERVER_PORT;
}

void setSecurityContext(const JSON &security_context) {
  g_SECURITY_CONTEXT = security_context;
}

void loadFromEnvironment() {
  if ((getenv("APISERVER_HOST") != NULL) and
      (getenv("APISERVER_PORT") != NULL))
    setAPIServerInfo(getenv("APISERVER_HOST"),
		     atoi(getenv("APISERVER_PORT")));

  if (getenv("SECURITY_CONTEXT") != NULL)
    g_SECURITY_CONTEXT = JSON::parse(getenv("SECURITY_CONTEXT"));
}
<commit_msg>complains now if apiserver info not set<commit_after>#include <algorithm>
#include "dxcpp.h"
#include "SimpleHttp.h"

// Example environment variables
//
// APISERVER_PORT=8124
// APISERVER_HOST=localhost
// SECURITY_CONTEXT='{"auth_token":"outside","auth_token_type":"Bearer"}'

using namespace std;
using namespace dx;

bool g_APISERVER_SET = false;
bool g_SECURITY_CONTEXT_SET = false;

string g_APISERVER_HOST;
string g_APISERVER_PORT;
string g_APISERVER;
JSON g_SECURITY_CONTEXT;

JSON DXHTTPRequest(const string &resource, const string &data,
		   const map<string, string> &headers) {
  if (!g_APISERVER_SET || !g_SECURITY_CONTEXT_SET) {
    loadFromEnvironment();
  }
  if (!g_APISERVER_SET || !g_SECURITY_CONTEXT_SET) {
    std::cerr << "Error: API server information and/or security context not set." << std::endl;
    throw;
  }

  string url = g_APISERVER + resource;

  HttpHeaders req_headers;
  JSON secContext = g_SECURITY_CONTEXT;
  req_headers["Authorization"] = secContext["auth_token_type"].get<string>() +
    " " + secContext["auth_token"].get<string>();

  string headername;
  bool content_type_set = false;
  for (map<string, string>::const_iterator iter = headers.begin();
       iter != headers.end();
       iter++) {
    headername = iter->first;
    req_headers[headername] = iter->second;

    transform(headername.begin(), headername.end(), headername.begin(), ::tolower);
    if (headername == "content-type")
      content_type_set = true;
  }

  if (!content_type_set)
    req_headers["Content-Type"] = "application/json";

  HttpClientRequest req;

  // Attempt a POST request
  req.setUrl(url);
  req.setReqData(data.data(), data.size());
  req.setMethod("POST");
  req.setHeaders(req_headers);
  req.send();

  if (req.responseCode != 200) {
    JSON respJSON = JSON::parse(req.respData);
    throw DXAPIError(respJSON["error"]["type"].get<string>(),
    		     respJSON["error"]["message"].get<string>(),
    		     req.responseCode);
  }

  return JSON::parse(req.respData);
}

void setAPIServerInfo(const string &host,
		      int port,
		      const string &protocol) {
  g_APISERVER_HOST = host;
  char portstr[10];
  sprintf(portstr, "%d", port);
  g_APISERVER_PORT = string(portstr);
  g_APISERVER = protocol + "://" + host + ":" + g_APISERVER_PORT;

  g_APISERVER_SET = true;
}

void setSecurityContext(const JSON &security_context) {
  g_SECURITY_CONTEXT = security_context;

  g_SECURITY_CONTEXT_SET = true;
}

void loadFromEnvironment() {
  if (!g_APISERVER_SET &&
      (getenv("APISERVER_HOST") != NULL) &&
      (getenv("APISERVER_PORT") != NULL))
    setAPIServerInfo(getenv("APISERVER_HOST"),
		     atoi(getenv("APISERVER_PORT")));

  if (!g_SECURITY_CONTEXT_SET &&
      getenv("SECURITY_CONTEXT") != NULL)
    setSecurityContext(JSON::parse(getenv("SECURITY_CONTEXT")));
}
<|endoftext|>


<commit_before>#define WIN32_LEAN_AND_MEAN
#define STRICT
#define STRICT_GS_ENABLED
#define _CRTDBG_MAP_ALLOC
#include <windows.h>
#include <atlbase.h>
#include <pathcch.h>
#include <shlwapi.h>
#include <winioctl.h>
#include <clocale>
#include <cstdio>
#include <memory>
#include <crtdbg.h>
#include "banned.h"
#pragma comment(lib, "pathcch")
#pragma comment(lib, "shlwapi")
#pragma comment(lib, "user32")

std::unique_ptr<WCHAR[]> GetWindowsError( ULONG error_code = GetLastError() )
{
	auto msg = std::make_unique<WCHAR[]>( USHRT_MAX );
	if( FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error_code, 0, msg.get(), USHRT_MAX, nullptr ) )
	{
		return msg;
	}
	return nullptr;
}
void PrintfWindowsError( ULONG error_code = GetLastError() )
{
	if( auto error_msg = GetWindowsError( error_code ) )
	{
		fprintf( stderr, "%ls\n", error_msg.get() );
	}
}
void PrintUsage()
{
	fprintf(
		stderr,
		"Copy file without actual data write.\n"
		"\n"
		"%ls source destination\n"
		"\n"
		"source       Specifies a file to copy.\n"
		"             source must have placed on the ReFS volume.\n"
		"destination  Specifies new file name.\n"
		"             destination must have placed on the same volume as source.\n",
		PathFindFileNameW( __wargv[0] )
		);
}
std::unique_ptr<bool> CheckReFSVersion( _In_z_ PCWSTR on_volume_path )
{
	auto mount_point = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
	if( !GetVolumePathNameW( on_volume_path, mount_point.get(), PATHCCH_MAX_CCH ) )
	{
		PrintfWindowsError();
		return nullptr;
	}
	WCHAR guid_path[50];
	if( !GetVolumeNameForVolumeMountPointW( mount_point.get(), guid_path, ARRAYSIZE( guid_path ) ) )
	{
		PrintfWindowsError();
		return nullptr;
	}
	PWCHAR end_bslash;
	if( FAILED( PathCchRemoveBackslashEx( guid_path, ARRAYSIZE( guid_path ), &end_bslash, nullptr ) ) )
	{
		PrintfWindowsError();
		return nullptr;
	}
	*end_bslash = L'\0';
	HANDLE volume = CreateFileW( guid_path, FILE_EXECUTE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr );
	if( volume == INVALID_HANDLE_VALUE )
	{
		PrintfWindowsError();
		return nullptr;
	}
	ATL::CHandle c_volume( volume );
	ULONG dummy;
	REFS_VOLUME_DATA_BUFFER refs_info;
	if( DeviceIoControl( volume, FSCTL_GET_REFS_VOLUME_DATA, nullptr, 0, &refs_info, sizeof refs_info, &dummy, nullptr ) )
	{
		fprintf( stderr, "%ls is ReFS %lu.%lu\n", mount_point.get(), refs_info.MajorVersion, refs_info.MinorVersion );
		if( refs_info.MajorVersion < 1 || ( refs_info.MajorVersion == 1 && refs_info.MinorVersion <= 2 ) )
		{
			return std::make_unique<bool>( false );
		}
		else
		{
			return std::make_unique<bool>( true );
		}
	}
	WCHAR fs_name_buffer[MAX_PATH + 1];
	if( GetVolumeInformationByHandleW( volume, nullptr, 0, nullptr, nullptr, nullptr, fs_name_buffer, ARRAYSIZE( fs_name_buffer ) ) )
	{
		fprintf( stderr, "%ls is %ls\n", mount_point.get(), fs_name_buffer );
	}
	return nullptr;
}
BOOL reflink( _In_z_ PCWSTR oldpath, _In_z_ PCWSTR newpath )
{
	HANDLE source = CreateFileW( oldpath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr );
	if( source == INVALID_HANDLE_VALUE )
	{
		return FALSE;
	}
	ATL::CHandle c_source( source );
	FILE_STANDARD_INFO file_standard;
	if( !GetFileInformationByHandleEx( source, FileStandardInfo, &file_standard, sizeof file_standard ) )
	{
		return FALSE;
	}
	FILE_BASIC_INFO file_basic;
	if( !GetFileInformationByHandleEx( source, FileBasicInfo, &file_basic, sizeof file_basic ) )
	{
		return FALSE;
	}

	HANDLE destination = CreateFileW( newpath, GENERIC_WRITE | DELETE, 0, nullptr, CREATE_NEW, 0, source );
	if( destination == INVALID_HANDLE_VALUE )
	{
		return FALSE;
	}
	ATL::CHandle c_destination( destination );
	FILE_DISPOSITION_INFO dispose = { TRUE };
	if( !SetFileInformationByHandle( destination, FileDispositionInfo, &dispose, sizeof dispose ) )
	{
		return FALSE;
	}

	if( file_basic.FileAttributes & FILE_ATTRIBUTE_SPARSE_FILE )
	{
		ULONG dummy;
		if( !DeviceIoControl( destination, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &dummy, nullptr ) )
		{
			return FALSE;
		}
	}
	FILE_END_OF_FILE_INFO end_of_file = { file_standard.EndOfFile };
	if( !SetFileInformationByHandle( destination, FileEndOfFileInfo, &end_of_file, sizeof end_of_file ) )
	{
		return FALSE;
	}
	DUPLICATE_EXTENTS_DATA dup_extent = { source, { 0 }, { 0 }, file_standard.AllocationSize };
	ULONG dummy;
	if( !DeviceIoControl( destination, FSCTL_DUPLICATE_EXTENTS_TO_FILE, &dup_extent, sizeof dup_extent, nullptr, 0, &dummy, nullptr ) )
	{
		return FALSE;
	}
	else
	{
#pragma warning( suppress: 4838 )
		FILETIME atime = { file_basic.LastAccessTime.LowPart, file_basic.LastAccessTime.HighPart };
#pragma warning( suppress: 4838 )
		FILETIME mtime = { file_basic.LastWriteTime.LowPart, file_basic.LastWriteTime.HighPart };
		SetFileTime( destination, nullptr, &atime, &mtime );
		dispose.DeleteFile = FALSE;
		return SetFileInformationByHandle( destination, FileDispositionInfo, &dispose, sizeof dispose );
	}
}
int __cdecl wmain( int argc, PWSTR argv[] )
{
	_CrtSetDbgFlag( _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ) | _CRTDBG_LEAK_CHECK_DF );
	_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
	_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE );
	setlocale( LC_ALL, "" );

	if( argc != 3 )
	{
		PrintUsage();
		return EXIT_FAILURE;
	}
	auto source = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
	auto destination = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
	if( FAILED( PathCchCanonicalizeEx( source.get(), PATHCCH_MAX_CCH, argv[1], PATHCCH_ALLOW_LONG_PATHS ) )
		|| FAILED( PathCchCanonicalizeEx( destination.get(), PATHCCH_MAX_CCH, argv[2], PATHCCH_ALLOW_LONG_PATHS ) ) )
	{
		PrintfWindowsError();
		return EXIT_FAILURE;
	}
	auto refs_capability = CheckReFSVersion( source.get() );
	if( !refs_capability || !*refs_capability )
	{
		fputs( "reflink may fail.\n", stderr );
	}
	if( !reflink( source.get(), destination.get() ) )
	{
		PrintfWindowsError();
		return EXIT_FAILURE;
	}
}<commit_msg>replace BOOL to bool<commit_after>#define WIN32_LEAN_AND_MEAN
#define STRICT
#define STRICT_GS_ENABLED
#define _CRTDBG_MAP_ALLOC
#include <windows.h>
#include <atlbase.h>
#include <pathcch.h>
#include <shlwapi.h>
#include <winioctl.h>
#include <clocale>
#include <cstdio>
#include <memory>
#include <crtdbg.h>
#include "banned.h"
#pragma comment(lib, "pathcch")
#pragma comment(lib, "shlwapi")
#pragma comment(lib, "user32")

std::unique_ptr<WCHAR[]> GetWindowsError( ULONG error_code = GetLastError() )
{
	auto msg = std::make_unique<WCHAR[]>( USHRT_MAX );
	if( FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error_code, 0, msg.get(), USHRT_MAX, nullptr ) )
	{
		return msg;
	}
	return nullptr;
}
void PrintfWindowsError( ULONG error_code = GetLastError() )
{
	if( auto error_msg = GetWindowsError( error_code ) )
	{
		fprintf( stderr, "%ls\n", error_msg.get() );
	}
}
void PrintUsage()
{
	fprintf(
		stderr,
		"Copy file without actual data write.\n"
		"\n"
		"%ls source destination\n"
		"\n"
		"source       Specifies a file to copy.\n"
		"             source must have placed on the ReFS volume.\n"
		"destination  Specifies new file name.\n"
		"             destination must have placed on the same volume as source.\n",
		PathFindFileNameW( __wargv[0] )
		);
}
std::unique_ptr<bool> CheckReFSVersion( _In_z_ PCWSTR on_volume_path )
{
	auto mount_point = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
	if( !GetVolumePathNameW( on_volume_path, mount_point.get(), PATHCCH_MAX_CCH ) )
	{
		PrintfWindowsError();
		return nullptr;
	}
	WCHAR guid_path[50];
	if( !GetVolumeNameForVolumeMountPointW( mount_point.get(), guid_path, ARRAYSIZE( guid_path ) ) )
	{
		PrintfWindowsError();
		return nullptr;
	}
	PWCHAR end_bslash;
	if( FAILED( PathCchRemoveBackslashEx( guid_path, ARRAYSIZE( guid_path ), &end_bslash, nullptr ) ) )
	{
		PrintfWindowsError();
		return nullptr;
	}
	*end_bslash = L'\0';
	HANDLE volume = CreateFileW( guid_path, FILE_EXECUTE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr );
	if( volume == INVALID_HANDLE_VALUE )
	{
		PrintfWindowsError();
		return nullptr;
	}
	ATL::CHandle c_volume( volume );
	ULONG dummy;
	REFS_VOLUME_DATA_BUFFER refs_info;
	if( DeviceIoControl( volume, FSCTL_GET_REFS_VOLUME_DATA, nullptr, 0, &refs_info, sizeof refs_info, &dummy, nullptr ) )
	{
		fprintf( stderr, "%ls is ReFS %lu.%lu\n", mount_point.get(), refs_info.MajorVersion, refs_info.MinorVersion );
		if( refs_info.MajorVersion < 1 || ( refs_info.MajorVersion == 1 && refs_info.MinorVersion <= 2 ) )
		{
			return std::make_unique<bool>( false );
		}
		else
		{
			return std::make_unique<bool>( true );
		}
	}
	WCHAR fs_name_buffer[MAX_PATH + 1];
	if( GetVolumeInformationByHandleW( volume, nullptr, 0, nullptr, nullptr, nullptr, fs_name_buffer, ARRAYSIZE( fs_name_buffer ) ) )
	{
		fprintf( stderr, "%ls is %ls\n", mount_point.get(), fs_name_buffer );
	}
	return nullptr;
}
bool reflink( _In_z_ PCWSTR oldpath, _In_z_ PCWSTR newpath )
{
	HANDLE source = CreateFileW( oldpath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr );
	if( source == INVALID_HANDLE_VALUE )
	{
		return false;
	}
	ATL::CHandle c_source( source );
	FILE_STANDARD_INFO file_standard;
	if( !GetFileInformationByHandleEx( source, FileStandardInfo, &file_standard, sizeof file_standard ) )
	{
		return false;
	}
	FILE_BASIC_INFO file_basic;
	if( !GetFileInformationByHandleEx( source, FileBasicInfo, &file_basic, sizeof file_basic ) )
	{
		return false;
	}

	HANDLE destination = CreateFileW( newpath, GENERIC_WRITE | DELETE, 0, nullptr, CREATE_NEW, 0, source );
	if( destination == INVALID_HANDLE_VALUE )
	{
		return false;
	}
	ATL::CHandle c_destination( destination );
	FILE_DISPOSITION_INFO dispose = { TRUE };
	if( !SetFileInformationByHandle( destination, FileDispositionInfo, &dispose, sizeof dispose ) )
	{
		return false;
	}

	if( file_basic.FileAttributes & FILE_ATTRIBUTE_SPARSE_FILE )
	{
		ULONG dummy;
		if( !DeviceIoControl( destination, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &dummy, nullptr ) )
		{
			return false;
		}
	}
	FILE_END_OF_FILE_INFO end_of_file = { file_standard.EndOfFile };
	if( !SetFileInformationByHandle( destination, FileEndOfFileInfo, &end_of_file, sizeof end_of_file ) )
	{
		return false;
	}
	DUPLICATE_EXTENTS_DATA dup_extent = { source, { 0 }, { 0 }, file_standard.AllocationSize };
	ULONG dummy;
	if( !DeviceIoControl( destination, FSCTL_DUPLICATE_EXTENTS_TO_FILE, &dup_extent, sizeof dup_extent, nullptr, 0, &dummy, nullptr ) )
	{
		return false;
	}
	else
	{
#pragma warning( suppress: 4838 )
		FILETIME atime = { file_basic.LastAccessTime.LowPart, file_basic.LastAccessTime.HighPart };
#pragma warning( suppress: 4838 )
		FILETIME mtime = { file_basic.LastWriteTime.LowPart, file_basic.LastWriteTime.HighPart };
		SetFileTime( destination, nullptr, &atime, &mtime );
		dispose.DeleteFile = FALSE;
		return SetFileInformationByHandle( destination, FileDispositionInfo, &dispose, sizeof dispose ) != 0;
	}
}
int __cdecl wmain( int argc, PWSTR argv[] )
{
	_CrtSetDbgFlag( _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ) | _CRTDBG_LEAK_CHECK_DF );
	_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
	_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE );
	setlocale( LC_ALL, "" );

	if( argc != 3 )
	{
		PrintUsage();
		return EXIT_FAILURE;
	}
	auto source = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
	auto destination = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
	if( FAILED( PathCchCanonicalizeEx( source.get(), PATHCCH_MAX_CCH, argv[1], PATHCCH_ALLOW_LONG_PATHS ) )
		|| FAILED( PathCchCanonicalizeEx( destination.get(), PATHCCH_MAX_CCH, argv[2], PATHCCH_ALLOW_LONG_PATHS ) ) )
	{
		PrintfWindowsError();
		return EXIT_FAILURE;
	}
	auto refs_capability = CheckReFSVersion( source.get() );
	if( !refs_capability || !*refs_capability )
	{
		fputs( "reflink may fail.\n", stderr );
	}
	if( !reflink( source.get(), destination.get() ) )
	{
		PrintfWindowsError();
		return EXIT_FAILURE;
	}
}<|endoftext|>