hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
425d2a724c3d5b91385c065199075392ac4744c4 | 57,201 | cpp | C++ | net/snmp/subagent/snmpevnt/evntagnt/snmptrlg.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | net/snmp/subagent/snmpevnt/evntagnt/snmptrlg.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | net/snmp/subagent/snmpevnt/evntagnt/snmptrlg.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1994 Microsoft Corporation
Module Name:
SNMPTRLG.CPP
Abstract:
This module is the tracing and logging routines for the SNMP Event Log
Extension Agent DLL.
Author:
Randy G. Braze (Braze Computing Services) Created 7 February 1996
Revision History:
--*/
extern "C" {
#include <windows.h> // windows definitions
#include <stdio.h> // standard I/O functions
#include <stdlib.h> // standard library definitions
#include <stdarg.h> // variable length arguments stuff
#include <string.h> // string declarations
#include <time.h> // time declarations
#include <snmp.h> // snmp definitions
#include "snmpelea.h" // global dll definitions
#include "snmptrlg.h" // module specific definitions
#include "snmpelmg.h" // message definitions
}
VOID
TraceWrite(
IN CONST BOOL fDoFormat, // flag for message formatting
IN CONST BOOL fDoTime, // flag for date/time prefixing
IN CONST LPSTR szFormat, // trace message to write
IN OPTIONAL ... // other printf type operands
)
/*++
Routine Description:
TraceWrite will write information provided to the trace file. Optionally,
it will prepend the date and timestamp to the information. If requested,
printf type arguments can be passed and they will be substituted just as
printf builds the message text. Sometimes this routine is called from
WriteTrace and sometimes it is called from other functions that need to
generate a trace file record. When called from WriteTrace, no formatting
is done on the buffer (WriteTrace has already performed the required
formatting). When called from other functions, the message text may or
may not require formatting, as specified by the calling function.
Arguments:
fDoFormat - TRUE or FALSE, indicating if the message text provided
requires formatting as a printf type function.
fDoTime - TRUE or FALSE, indicating if the date/timestamp should be
added to the beginning of the message text.
szFormat - NULL terminated string containing the message text to be
written to the trace file. If fDoFormat is true, then this
text will be in the format of a printf statement and will
contain substitution parameters strings and variable names
to be substituted will follow.
... - Optional parameters that are used to complete the printf
type statement. These are variables that are substituted
for strings specified in szFormat. These parameters will
only be specified and processed if fDoFormat is TRUE.
Return Value:
None
--*/
{
static CHAR szBuffer[LOG_BUF_SIZE];
static FILE *FFile;
static SYSTEMTIME NowTime;
va_list arglist;
// don't even attempt to open the trace file if
// the name is ""
if (szTraceFileName[0] == TEXT('\0'))
return;
FFile = fopen(szTraceFileName,"a"); // open trace file in append mode
if ( FFile != NULL ) // if file opened okay
{
if ( fDoTime ) // are we adding time?
{
GetLocalTime(&NowTime); // yep, get it
fprintf(FFile, "%02i/%02i/%02i %02i:%02i:%02i ",
NowTime.wMonth,
NowTime.wDay,
NowTime.wYear,
NowTime.wHour,
NowTime.wMinute,
NowTime.wSecond); // file printf to add date/time
}
if ( fDoFormat ) // if we need to format the buffer
{
szBuffer[LOG_BUF_SIZE-1] = 0;
va_start(arglist, szFormat);
_vsnprintf(szBuffer, LOG_BUF_SIZE-1, szFormat, arglist); // perform substitution
va_end(arglist);
fwrite(szBuffer, strlen(szBuffer), 1, FFile); // write data to the trace file
}
else // if no formatting required
{
fwrite(szFormat, strlen(szFormat), 1, FFile); // write message to the trace file
}
fflush(FFile); // flush buffers first
fclose(FFile); // close the trace file
}
} // end TraceWrite function
VOID LoadMsgDLL(
IN VOID
)
/*++
Routine Description:
LoadMsgDLL is called to load the SNMPELMG.DLL module which contains the
message and format information for all messages in the SNMP extension agent DLL.
It is necessary to call this routine only in the event that an event log
record cannot be written. If this situation occurs, then the DLL will be
loaded in an attempt to call FormatMessage and write this same information
to the trace file. This routine is called only once and only if the
event log write fails.
Arguments:
None
Return Value:
None
--*/
{
TCHAR szXMsgModuleName[MAX_PATH+1]; // space for DLL message module
DWORD nFile = sizeof(szXMsgModuleName)-sizeof(TCHAR); // max size for DLL message module name in bytes
DWORD dwType; // type of message module name
DWORD status; // status from registry calls
DWORD cbExpand; // byte count for REG_EXPAND_SZ parameters
HKEY hkResult; // handle to registry information
// ensure null terminated string
szXMsgModuleName[MAX_PATH] = 0;
if ( (status = RegOpenKeyEx( // open the registry to read the name
HKEY_LOCAL_MACHINE, // of the message module DLL
EVENTLOG_SERVICE,
0,
KEY_READ,
&hkResult) ) != ERROR_SUCCESS)
{
TraceWrite(TRUE, TRUE, // if we can't find it
"LoadMessageDLL: Unable to open EventLog service registry key; RegOpenKeyEx returned %lu\n",
status); // write trace event record
hMsgModule = (HMODULE) NULL; // set handle null
return; // return
}
else
{
if ( (status = RegQueryValueEx( // look up module name
hkResult, // handle to registry key
EXTENSION_MSG_MODULE, // key to look up
0, // ignored
&dwType, // address to return type value
(LPBYTE) szXMsgModuleName, // where to return message module name
&nFile) ) != ERROR_SUCCESS) // size of message module name field
{
TraceWrite(TRUE, TRUE, // if we can't find it
"LoadMessageDLL: Unable to open EventMessageFile registry key; RegQueryValueEx returned %lu\n",
status); // write trace event record
hMsgModule = (HMODULE) NULL; // set handle null
RegCloseKey(hkResult); // close the registry key
return; // return
}
RegCloseKey(hkResult); // close the registry key
cbExpand = ExpandEnvironmentStrings( // expand the DLL name
szXMsgModuleName, // unexpanded DLL name
szelMsgModuleName, // expanded DLL name
MAX_PATH+1); // max size of expanded DLL name in TCHARs
if (cbExpand == 0 || cbExpand > MAX_PATH+1) // if it didn't expand correctly
{
TraceWrite(TRUE, TRUE, // didn't have enough space
"LoadMessageDLL: Unable to expand message module %s; expanded size required is %lu bytes\n",
szXMsgModuleName, cbExpand); // log error message
hMsgModule = (HMODULE) NULL; // set handle null
return; // and exit
}
if ( (hMsgModule = (HMODULE) LoadLibraryEx(szelMsgModuleName, NULL, LOAD_LIBRARY_AS_DATAFILE) ) // load the message module name
== (HMODULE) NULL ) // if module didn't load
{
TraceWrite(TRUE, TRUE, // can't load message dll
"LoadMessageDLL: Unable to load message module %s; LoadLibraryEx returned %lu\n",
szelMsgModuleName, GetLastError() ); // log error message
}
}
return; // exit routine
}
VOID
FormatTrace(
IN CONST NTSTATUS nMsg, // message number to format
IN CONST LPVOID lpArguments // strings to insert
)
/*++
Routine Description:
FormatTrace will write the message text specified by nMsg to the trace
file. If supplied, the substitution arguments supplied by lpArguments
will be inserted in the message. FormatMessage is called to format the
message text and insert the substitution arguments into the text. The
text of the message is loaded from the SNMPELMG.DLL message module as
specified in the Eventlog\Application\Snmpelea registry entry under the key of
EventMessageFile. This information is read, the file name is expanded and
the message module is loaded. If the message cannot be formatted, then
a record is written to the trace file indicating the problem.
Arguments:
nMsg - This is the message number in SNMPELMG.H in NTSTATUS format
that is to be written.
lpArguments - This is a pointer to an array of strings that will be
substituted in the message text specified. If this value
is NULL, there are no substitution values to insert.
Return Value:
None
--*/
{
static DWORD nBytes; // return value from FormatMessage
static LPTSTR lpBuffer = NULL; // temporary message buffer
if ( !fMsgModule ) { // if we don't have dll loaded yet
fMsgModule = TRUE; // indicate we've looked now
LoadMsgDLL(); // load the DLL
}
if ( hMsgModule ) {
nBytes = FormatMessage( // see if we can format the message
FORMAT_MESSAGE_ALLOCATE_BUFFER | // let api build buffer
FORMAT_MESSAGE_ARGUMENT_ARRAY | // indicate an array of string inserts
FORMAT_MESSAGE_FROM_HMODULE, // look thru message DLL
(LPVOID) hMsgModule, // handle to message module
nMsg, // message number to get
(ULONG) NULL, // specify no language
(LPTSTR) &lpBuffer, // address for buffer pointer
80, // minimum space to allocate
(va_list* )lpArguments); // address of array of pointers
if (nBytes == 0) { // format is not okay
TraceWrite(TRUE, TRUE,
"FormatTrace: Error formatting message number %08X is %lu\n",
nMsg, GetLastError() ); // trace the problem
}
else { // format is okay
TraceWrite(FALSE, TRUE, lpBuffer); // log the message in the trace file
}
// LocalFree ignores NULL parameter
if ( LocalFree(lpBuffer) != NULL ) { // free buffer storage
TraceWrite(TRUE, TRUE,
"FormatTrace: Error freeing FormatMessage buffer is %lu\n",
GetLastError() );
}
lpBuffer = NULL;
}
else {
TraceWrite(TRUE, TRUE,
"FormatTrace: Unable to format message number %08X; message DLL handle is null.\n",
nMsg); // trace the problem
}
return; // exit routine
}
USHORT
MessageType(
IN CONST NTSTATUS nMsg
)
/*++
Routine Description:
MessageType is used to return the severity type of an NTSTATUS formatted
message number. This information is needed to log the appropriate event
log information when writing a record to the system event log. Acceptable
message types are defined in NTELFAPI.H.
Arguments:
nMsg - This is the message number in SNMPELMG.H in NTSTATUS format
that is to be analyzed.
Return Value:
Unsigned short integer containing the message severity as described in
NTELFAPI.H. If no message type is matched, the default of informational
is returned.
--*/
{
switch ((ULONG) nMsg >> 30) { // get message type
case (SNMPELEA_SUCCESS) :
return(EVENTLOG_SUCCESS); // success message
case (SNMPELEA_INFORMATIONAL) :
return(EVENTLOG_INFORMATION_TYPE); // informational message
case (SNMPELEA_WARNING) :
return(EVENTLOG_WARNING_TYPE); // warning message
case (SNMPELEA_ERROR) :
return(EVENTLOG_ERROR_TYPE); // error message
default:
return(EVENTLOG_INFORMATION_TYPE); // default to informational
}
}
VOID
WriteLog(
IN NTSTATUS nMsgNumber
)
/*++
Routine Description:
WriteLog is called to write message text to the system event log. This is
a C++ overloaded function. In case a log record cannot be written
to the system event log, TraceWrite is called to write the appropriate
message text to the trace file.
Arguments:
nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format
that is to be written to the event log.
Return Value:
None
--*/
{
static USHORT wLogType; // to hold event log type
static BOOL fReportEvent; // return flag from report event
if (hWriteEvent != NULL) // if we have previous log access ability
{
wLogType = MessageType(nMsgNumber); // get message type
fReportEvent = ReportEvent( // write message
hWriteEvent, // handle to log file
wLogType, // message type
0, // message category
nMsgNumber, // message number
NULL, // user sid
0, // number of strings
0, // data length
0, // pointer to string array
(PVOID) NULL); // data address
if ( !fReportEvent ) // did the event log okay?
{ // not if we get here.....
TraceWrite(TRUE, TRUE, // show error in trace file
"WriteLog: Error writing to system event log is %lu\n",
GetLastError() );
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
else // if we can't write to event log
{
TraceWrite(FALSE, TRUE, // show error in trace file
"WriteLog: Unable to write to system event log; handle is null\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
return; // exit the function
}
VOID
WriteLog(
IN NTSTATUS nMsgNumber, // message number to log
IN DWORD dwCode // code to pass to message
)
/*++
Routine Description:
WriteLog is called to write message text to the system event log. This is
a C++ overloaded function. In case a log record cannot be written
to the system event log, TraceWrite is called to write the appropriate
message text to the trace file.
Arguments:
nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format
that is to be written to the event log.
dwCode - This is a double word code that is to be converted to a
string and substituted appropriately in the message text.
Return Value:
None
--*/
{
static USHORT wLogType; // to hold event log type
static TCHAR *lpszEventString[1]; // array of strings to pass to event logger
static BOOL fReportEvent; // return flag from report event
lpszEventString[0] = new TCHAR[34]; // allocate space for string conversion
if (hWriteEvent != NULL) // if we have previous log access ability
{
if ( lpszEventString[0] != (TCHAR *) NULL ) // if storage allocated
{
wLogType = MessageType(nMsgNumber); // get message type
_ultoa(dwCode, lpszEventString[0], 10); // convert to string
fReportEvent = ReportEvent( // write message
hWriteEvent, // handle to log file
wLogType, // message type
0, // message category
nMsgNumber, // message number
NULL, // user sid
1, // number of strings
0, // data length
(const char **) lpszEventString, // pointer to string array
NULL); // data address
if ( !fReportEvent ) // did the event log okay?
{ // not if we get here.....
TraceWrite(TRUE, TRUE, // write trace file record
"WriteLog: Error writing to system event log is %lu\n",
GetLastError() );
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
}
else // if we can't allocate memory
{
TraceWrite(FALSE, TRUE, // write trace file record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
else // if we can't write to system log
{
TraceWrite(FALSE, TRUE, // write trace file record
"WriteLog: Unable to write to system event log; handle is null\n");
if ( lpszEventString[0] != (TCHAR *) NULL ) // if storage allocated
{
_ultoa(dwCode, lpszEventString[0], 10); // convert to string
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
else // if we can't allocate memory
{
TraceWrite(FALSE, TRUE, // write trace file record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
delete [] lpszEventString[0]; // free storage
return; // exit function
}
VOID
WriteLog(
IN NTSTATUS nMsgNumber,
IN DWORD dwCode1,
IN DWORD dwCode2
)
/*++
Routine Description:
WriteLog is called to write message text to the system event log. This is
a C++ overloaded function. In case a log record cannot be written
to the system event log, TraceWrite is called to write the appropriate
message text to the trace file.
Arguments:
nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format
that is to be written to the event log.
dwCode1 - This is a double word code that is to be converted to a
string and substituted appropriately in the message text.
dwCode2 - This is a double word code that is to be converted to a
string and substituted appropriately in the message text.
Return Value:
None
--*/
{
static USHORT wLogType; // to hold event log type
static TCHAR *lpszEventString[2]; // array of strings to pass to event logger
static BOOL fReportEvent; // return flag from report event
lpszEventString[0] = new TCHAR[34]; // allocate space for string conversion
lpszEventString[1] = new TCHAR[34]; // allocate space for string conversion
if (hWriteEvent != NULL) // if we have previous log access ability
{
if ( (lpszEventString[0] != (TCHAR *) NULL) &&
(lpszEventString[1] != (TCHAR *) NULL) ) // if storage allocated
{
wLogType = MessageType(nMsgNumber); // get message type
_ultoa(dwCode1, lpszEventString[0], 10); // convert to string
_ultoa(dwCode2, lpszEventString[1], 10); // convert to string
fReportEvent = ReportEvent( // write message
hWriteEvent, // handle to log file
wLogType, // message type
0, // message category
nMsgNumber, // message number
NULL, // user sid
2, // number of strings
0, // data length
(const char **) lpszEventString, // pointer to string array
NULL); // data address
if ( !fReportEvent ) // did the event log okay?
{ // not if we get here.....
TraceWrite(TRUE, TRUE, // write a trace file entry
"WriteLog: Error writing to system event log is %lu\n",
GetLastError() );
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
}
else // if we can't allocate memory
{
TraceWrite(FALSE, TRUE, // write trace file record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
else // if we can't write to system log
{
TraceWrite(FALSE, TRUE, // write trace file entry
"WriteLog: Unable to write to system event log; handle is null\n");
if ( (lpszEventString[0] != (TCHAR *) NULL) &&
(lpszEventString[1] != (TCHAR *) NULL) ) // if storage allocated
{
_ultoa(dwCode1, lpszEventString[0], 10); // convert to string
_ultoa(dwCode2, lpszEventString[1], 10); // convert to string
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
else // if we can't allocate memory
{
TraceWrite(FALSE, TRUE, // write trace file record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
delete [] lpszEventString[0]; // free storage
delete [] lpszEventString[1]; // free storage
return; // exit function
}
VOID
WriteLog(
IN NTSTATUS nMsgNumber,
IN DWORD dwCode1,
IN LPTSTR lpszText1,
IN LPTSTR lpszText2,
IN DWORD dwCode2
)
/*++
Routine Description:
WriteLog is called to write message text to the system event log. This is
a C++ overloaded function. In case a log record cannot be written
to the system event log, TraceWrite is called to write the appropriate
message text to the trace file.
Arguments:
nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format
that is to be written to the event log.
dwCode1 - This is a double word code that is to be converted to a
string and substituted appropriately in the message text.
lpszText1 - This contains a string parameter that is to be substituted
into the message text.
lpszText2 - This contains a string parameter that is to be substituted
into the message text.
dwCode2 - This is a double word code that is to be converted to a
string and substituted appropriately in the message text.
Return Value:
None
--*/
{
static USHORT wLogType; // to hold event log type
static TCHAR *lpszEventString[4]; // array of strings to pass to event logger
static BOOL fReportEvent; // return flag from report event
lpszEventString[0] = new TCHAR[34]; // allocate space for string conversion
lpszEventString[1] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion
lpszEventString[2] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion
lpszEventString[3] = new TCHAR[34]; // allocate space for string conversion
if (hWriteEvent != NULL) // if we have previous log access ability
{
if ( (lpszEventString[0] != (TCHAR *) NULL) &&
(lpszEventString[1] != (TCHAR *) NULL) &&
(lpszEventString[2] != (TCHAR *) NULL) &&
(lpszEventString[3] != (TCHAR *) NULL) ) // if storage allocated
{
// ensures null terminated strings
lpszEventString[1][MAX_PATH] = 0;
lpszEventString[2][MAX_PATH] = 0;
wLogType = MessageType(nMsgNumber); // get message type
_ultoa(dwCode1, lpszEventString[0], 10); // convert to string
strncpy(lpszEventString[1],lpszText1,MAX_PATH); // copy the string
strncpy(lpszEventString[2],lpszText2,MAX_PATH); // copy the string
_ultoa(dwCode2, lpszEventString[3], 10); // convert to string
fReportEvent = ReportEvent( // write message
hWriteEvent, // handle to log file
wLogType, // message type
0, // message category
nMsgNumber, // message number
NULL, // user sid
4, // number of strings
0, // data length
(const char **) lpszEventString, // pointer to string array
NULL); // data address
if ( !fReportEvent ) // did the event log okay?
{ // not if we get here.....
TraceWrite(TRUE, TRUE, // write trace file record
"WriteLog: Error writing to system event log is %lu\n",
GetLastError() );
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
}
else // if we can't allocate memory
{
TraceWrite(FALSE, TRUE, // write trace file record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
else // if we can't write to system log
{
TraceWrite(FALSE, TRUE, // write trace file record
"WriteLog: Unable to write to system event log; handle is null\n");
if ( (lpszEventString[0] != (TCHAR *) NULL) &&
(lpszEventString[1] != (TCHAR *) NULL) &&
(lpszEventString[2] != (TCHAR *) NULL) &&
(lpszEventString[3] != (TCHAR *) NULL) ) // if storage allocated
{
// ensures null terminated strings
lpszEventString[1][MAX_PATH] = 0;
lpszEventString[2][MAX_PATH] = 0;
_ultoa(dwCode1, lpszEventString[0], 10); // convert to string
strncpy(lpszEventString[1],lpszText1,MAX_PATH); // copy the string
strncpy(lpszEventString[2],lpszText2,MAX_PATH); // copy the string
_ultoa(dwCode2, lpszEventString[3], 10); // convert to string
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
else // if we can't allocate memory
{
TraceWrite(FALSE, TRUE, // write trace file record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
delete [] lpszEventString[0]; // free storage
delete [] lpszEventString[1]; // free storage
delete [] lpszEventString[2]; // free storage
delete [] lpszEventString[3]; // free storage
return; // exit function
}
VOID
WriteLog(
IN NTSTATUS nMsgNumber,
IN DWORD dwCode1,
IN LPTSTR lpszText,
IN DWORD dwCode2,
IN DWORD dwCode3
)
/*++
Routine Description:
WriteLog is called to write message text to the system event log. This is
a C++ overloaded function. In case a log record cannot be written
to the system event log, TraceWrite is called to write the appropriate
message text to the trace file.
Arguments:
nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format
that is to be written to the event log.
dwCode1 - This is a double word code that is to be converted to a
string and substituted appropriately in the message text.
lpszText - This contains a string parameter that is to be substituted
into the message text.
dwCode2 - This is a double word code that is to be converted to a
string and substituted appropriately in the message text.
dwCode3 - This is a double word code that is to be converted to a
string and substituted appropriately in the message text.
Return Value:
None
--*/
{
static USHORT wLogType; // to hold event log type
static TCHAR *lpszEventString[4]; // array of strings to pass to event logger
static BOOL fReportEvent; // return flag from report event
lpszEventString[0] = new TCHAR[34]; // allocate space for string conversion
lpszEventString[1] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion
lpszEventString[2] = new TCHAR[34]; // allocate space for string conversion
lpszEventString[3] = new TCHAR[34]; // allocate space for string conversion
if (hWriteEvent != NULL) // if we have previous log access ability
{
if ( (lpszEventString[0] != (TCHAR *) NULL) &&
(lpszEventString[1] != (TCHAR *) NULL) &&
(lpszEventString[2] != (TCHAR *) NULL) &&
(lpszEventString[3] != (TCHAR *) NULL) ) // if storage allocated
{
lpszEventString[1][MAX_PATH] = 0; // ensures null terminated string
wLogType = MessageType(nMsgNumber); // get message type
_ultoa(dwCode1, lpszEventString[0], 10); // convert to string
strncpy(lpszEventString[1],lpszText,MAX_PATH); // copy the string
_ultoa(dwCode2, lpszEventString[2], 10); // convert to string
_ultoa(dwCode3, lpszEventString[3], 10); // convert to string
fReportEvent = ReportEvent( // write message
hWriteEvent, // handle to log file
wLogType, // message type
0, // message category
nMsgNumber, // message number
NULL, // user sid
4, // number of strings
0, // data length
(const char **) lpszEventString, // pointer to string array
NULL); // data address
if ( !fReportEvent ) // did the event log okay?
{ // not if we get here.....
TraceWrite(TRUE, TRUE, // write trace file record
"WriteLog: Error writing to system event log is %lu\n",
GetLastError() );
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
}
else // if we can't allocate memory
{
TraceWrite(FALSE, TRUE, // write trace file record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
else // if we can't write to system log
{
TraceWrite(FALSE, TRUE, // write trace file record
"WriteLog: Unable to write to system event log; handle is null\n");
if ( (lpszEventString[0] != (TCHAR *) NULL) &&
(lpszEventString[1] != (TCHAR *) NULL) &&
(lpszEventString[2] != (TCHAR *) NULL) &&
(lpszEventString[3] != (TCHAR *) NULL) ) // if storage allocated
{
lpszEventString[1][MAX_PATH] = 0; // ensures null terminated string
_ultoa(dwCode1, lpszEventString[0], 10); // convert to string
strncpy(lpszEventString[1],lpszText,MAX_PATH); // copy the string
_ultoa(dwCode2, lpszEventString[2], 10); // convert to string
_ultoa(dwCode3, lpszEventString[3], 10); // convert to string
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
else // if we can't allocate memory
{
TraceWrite(FALSE, TRUE, // write trace file record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
delete [] lpszEventString[0]; // free storage
delete [] lpszEventString[1]; // free storage
delete [] lpszEventString[2]; // free storage
delete [] lpszEventString[3]; // free storage
return; // exit the function
}
VOID
WriteLog(
IN NTSTATUS nMsgNumber,
IN LPTSTR lpszText,
IN DWORD dwCode1,
IN DWORD dwCode2
)
/*++
Routine Description:
WriteLog is called to write message text to the system event log. This is
a C++ overloaded function. In case a log record cannot be written
to the system event log, TraceWrite is called to write the appropriate
message text to the trace file.
Arguments:
nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format
that is to be written to the event log.
lpszText - This contains a string parameter that is to be substituted
into the message text.
dwCode1 - This is a double word code that is to be converted to a
string and substituted appropriately in the message text.
dwCode2 - This is a double word code that is to be converted to a
string and substituted appropriately in the message text.
Return Value:
None
--*/
{
static USHORT wLogType; // to hold event log type
static TCHAR *lpszEventString[3]; // array of strings to pass to event logger
static BOOL fReportEvent; // return flag from report event
lpszEventString[0] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion
lpszEventString[1] = new TCHAR[34]; // allocate space for string conversion
lpszEventString[2] = new TCHAR[34]; // allocate space for string conversion
if (hWriteEvent != NULL) // if we have previous log access ability
{
if ( (lpszEventString[0] != (TCHAR *) NULL) &&
(lpszEventString[1] != (TCHAR *) NULL) &&
(lpszEventString[2] != (TCHAR *) NULL) ) // if storage allocated
{
lpszEventString[0][MAX_PATH] = 0; // ensures null terminated string
wLogType = MessageType(nMsgNumber); // get message type
strncpy(lpszEventString[0],lpszText,MAX_PATH); // copy the string
_ultoa(dwCode1, lpszEventString[1], 10); // convert to string
_ultoa(dwCode2, lpszEventString[2], 10); // convert to string
fReportEvent = ReportEvent( // write message
hWriteEvent, // handle to log file
wLogType, // message type
0, // message category
nMsgNumber, // message number
NULL, // user sid
3, // number of strings
0, // data length
(const char **) lpszEventString, // pointer to string array
NULL); // data address
if ( !fReportEvent ) // did the event log okay?
{ // not if we get here.....
TraceWrite(TRUE, TRUE, // write trace file record
"WriteLog: Error writing to system event log is %lu\n",
GetLastError() );
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
}
else // if we can't allocate memory
{
TraceWrite(FALSE, TRUE, // write trace file record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
else // if we can't write to system log
{
TraceWrite(FALSE, TRUE, // write trace file record
"WriteLog: Unable to write to system event log; handle is null\n");
if ( (lpszEventString[0] != (TCHAR *) NULL) &&
(lpszEventString[1] != (TCHAR *) NULL) &&
(lpszEventString[2] != (TCHAR *) NULL) ) // if storage allocated
{
lpszEventString[0][MAX_PATH] = 0; // ensures null terminated string
strncpy(lpszEventString[0],lpszText,MAX_PATH); // copy the string
_ultoa(dwCode1, lpszEventString[1], 10); // convert to string
_ultoa(dwCode2, lpszEventString[2], 10); // convert to string
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
else // if we can't allocate memory
{
TraceWrite(FALSE, TRUE, // write trace file record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
delete [] lpszEventString[0]; // free storage
delete [] lpszEventString[1]; // free storage
delete [] lpszEventString[2]; // free storage
return; // exit the function
}
VOID
WriteLog(
IN NTSTATUS nMsgNumber,
IN LPTSTR lpszText,
IN DWORD dwCode
)
/*++
Routine Description:
WriteLog is called to write message text to the system event log. This is
a C++ overloaded function. In case a log record cannot be written
to the system event log, TraceWrite is called to write the appropriate
message text to the trace file.
Arguments:
nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format
that is to be written to the event log.
lpszText - This contains a string parameter that is to be substituted
into the message text.
dwCode - This is a double word code that is to be converted to a
string and substituted appropriately in the message text.
Return Value:
None
--*/
{
static USHORT wLogType; // to hold event log type
static TCHAR *lpszEventString[2]; // array of strings to pass to event logger
static BOOL fReportEvent; // return flag from report event
lpszEventString[0] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion
lpszEventString[1] = new TCHAR[34]; // allocate space for string conversion
if (hWriteEvent != NULL) // if we have previous log access ability
{
if ( (lpszEventString[0] != (TCHAR *) NULL) &&
(lpszEventString[1] != (TCHAR *) NULL) ) // if storage allocated
{
lpszEventString[0][MAX_PATH] = 0; // ensures null terminated string
wLogType = MessageType(nMsgNumber); // get message type
strncpy(lpszEventString[0],lpszText,MAX_PATH); // copy the string
_ultoa(dwCode, lpszEventString[1], 10); // convert to string
fReportEvent = ReportEvent( // write message
hWriteEvent, // handle to log file
wLogType, // message type
0, // message category
nMsgNumber, // message number
NULL, // user sid
2, // number of strings
0, // data length
(const char **) lpszEventString, // pointer to string array
NULL); // data address
if ( !fReportEvent ) // did the event log okay?
{ // not if we get here.....
TraceWrite(TRUE, TRUE, // write trace record
"WriteLog: Error writing to system event log is %lu\n",
GetLastError() );
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
}
else // if we can't allocate memory
{
TraceWrite(FALSE, TRUE, // write trace record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
else // if we can't write to system log
{
TraceWrite(FALSE, TRUE, // write trace record
"WriteLog: Unable to write to system event log; handle is null\n");
if ( (lpszEventString[0] != (TCHAR *) NULL) &&
(lpszEventString[1] != (TCHAR *) NULL) ) // if storage allocated
{
lpszEventString[0][MAX_PATH] = 0; // ensures null terminated string
strncpy(lpszEventString[0],lpszText,MAX_PATH); // copy the string
_ultoa(dwCode, lpszEventString[1], 10); // convert to string
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
else // if we can't allocate memory
{
TraceWrite(FALSE, TRUE, // write trace record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
delete [] lpszEventString[0]; // free storage
delete [] lpszEventString[1]; // free storage
return; // exit function
}
VOID
WriteLog(
IN NTSTATUS nMsgNumber,
IN LPTSTR lpszText
)
/*++
Routine Description:
WriteLog is called to write message text to the system event log. This is
a C++ overloaded function. In case a log record cannot be written
to the system event log, TraceWrite is called to write the appropriate
message text to the trace file.
Arguments:
nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format
that is to be written to the event log.
lpszText - This contains a string parameter that is to be substituted
into the message text.
Return Value:
None
--*/
{
static USHORT wLogType; // to hold event log type
static TCHAR *lpszEventString[1]; // array of strings to pass to event logger
static BOOL fReportEvent; // return flag from report event
lpszEventString[0] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion
if (hWriteEvent != NULL) // if we have previous log access ability
{
if ( lpszEventString[0] != (TCHAR *) NULL ) // if storage allocated
{
lpszEventString[0][MAX_PATH] = 0; // ensures null terminated string
wLogType = MessageType(nMsgNumber); // get message type
strncpy(lpszEventString[0],lpszText,MAX_PATH); // copy the string
fReportEvent = ReportEvent( // write message
hWriteEvent, // handle to log file
wLogType, // message type
0, // message category
nMsgNumber, // message number
NULL, // user sid
1, // number of strings
0, // data length
(const char **) lpszEventString, // pointer to string array
NULL); // data address
if ( !fReportEvent ) // did the event log okay?
{ // not if we get here.....
TraceWrite(TRUE, TRUE, // write trace file record
"WriteLog: Error writing to system event log is %lu\n",
GetLastError() );
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
}
else // if we can't allocate memory
{
TraceWrite(FALSE, TRUE, // write trace record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
else // if we can't write to system log
{
TraceWrite(FALSE, TRUE, // write trace record
"WriteLog: Unable to write to system event log; handle is null\n");
if ( lpszEventString[0] != (TCHAR *) NULL ) // if storage allocated
{
lpszEventString[0][MAX_PATH] = 0; // ensures null terminated string
strncpy(lpszEventString[0],lpszText,MAX_PATH); // copy the string
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
else
{
TraceWrite(FALSE, TRUE, // write trace record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
delete [] lpszEventString[0]; // free storage
return; // exit function
}
VOID
WriteLog(
IN NTSTATUS nMsgNumber,
IN LPCTSTR lpszText1,
IN LPCTSTR lpszText2
)
/*++
Routine Description:
WriteLog is called to write message text to the system event log. This is
a C++ overloaded function. In case a log record cannot be written
to the system event log, TraceWrite is called to write the appropriate
message text to the trace file.
Arguments:
nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format
that is to be written to the event log.
lpszText - This contains a string parameter that is to be substituted
into the message text.
Return Value:
None
--*/
{
static USHORT wLogType; // to hold event log type
static TCHAR *lpszEventString[2]; // array of strings to pass to event logger
static BOOL fReportEvent; // return flag from report event
lpszEventString[0] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion
lpszEventString[1] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion
if (hWriteEvent != NULL) // if we have previous log access ability
{
if ( (lpszEventString[0] != (TCHAR *) NULL ) &&
(lpszEventString[1] != (TCHAR *) NULL ) ) // if storage allocated
{
// ensures null terminated strings
lpszEventString[0][MAX_PATH] = 0;
lpszEventString[1][MAX_PATH] = 0;
wLogType = MessageType(nMsgNumber); // get message type
strncpy(lpszEventString[0],lpszText1,MAX_PATH); // copy the string
strncpy(lpszEventString[1],lpszText2,MAX_PATH); // copy the string
fReportEvent = ReportEvent( // write message
hWriteEvent, // handle to log file
wLogType, // message type
0, // message category
nMsgNumber, // message number
NULL, // user sid
2, // number of strings
0, // data length
(const char **) lpszEventString, // pointer to string array
NULL); // data address
if ( !fReportEvent ) // did the event log okay?
{ // not if we get here.....
TraceWrite(TRUE, TRUE, // write trace file record
"WriteLog: Error writing to system event log is %lu\n",
GetLastError() );
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
}
else // if we can't allocate memory
{
TraceWrite(FALSE, TRUE, // write trace record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
else // if we can't write to system log
{
TraceWrite(FALSE, TRUE, // write trace record
"WriteLog: Unable to write to system event log; handle is null\n");
if ( (lpszEventString[0] != (TCHAR *) NULL) && // if storage allocated
(lpszEventString[1] != (TCHAR *) NULL ) )
{
// ensures null terminated strings
lpszEventString[0][MAX_PATH] = 0;
lpszEventString[1][MAX_PATH] = 0;
strncpy(lpszEventString[0],lpszText1,MAX_PATH); // copy the string
strncpy(lpszEventString[1],lpszText2,MAX_PATH); // copy the string
FormatTrace(nMsgNumber, lpszEventString); // format trace information
}
else
{
TraceWrite(FALSE, TRUE, // write trace record
"WriteLog: Error allocating memory for system event log write\n");
FormatTrace(nMsgNumber, NULL); // format trace information
}
}
delete [] lpszEventString[0]; // free storage
delete [] lpszEventString[1]; // free storage
return; // exit function
}
extern "C" {
VOID
WriteTrace(
IN CONST UINT nLevel, // level of trace message
IN CONST LPSTR szFormat, // trace message to write
IN ... // other printf type operands
)
/*++
Routine Description:
WriteTrace is called to write the requested trace information to the trace
file specified in the configuration registry. The key to the trace file
name is \SOFTWARE\Microsoft\SNMP_EVENTS\EventLog\Parameters\TraceFile.
The registry information is only read for the first time WriteTrace is called.
The TraceLevel parameter is also used to determine if the level of this
message is part of a group of messages being traced. If the level of this
message is greater than or equal the TraceLevel parameter, then this
message will be sent to the file, otherwise the message is ignored.
Arguments:
nLevel - This is the trace level of the message being logged.
szFormat - This is the string text of the message to write to the
trace file. This string is in the format of printf strings
and will be formatted accordingly.
Return Value:
None
--*/
{
static CHAR szBuffer[LOG_BUF_SIZE];
static TCHAR szFile[MAX_PATH+1];
static DWORD nFile = sizeof(szFile)-sizeof(TCHAR); // size in bytes for RegQueryValueEx
static DWORD dwLevel;
static DWORD dwType;
static DWORD nLvl = sizeof(DWORD);
static DWORD status;
static HKEY hkResult;
static DWORD cbExpand;
va_list arglist;
if ( !fTraceFileName ) // if we haven't yet read registry
{
szFile[MAX_PATH] = 0;
fTraceFileName = TRUE; // set flag to not open registry info again
if ( (status = RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
EXTENSION_PARM,
0,
KEY_READ,
&hkResult) ) != ERROR_SUCCESS)
{
WriteLog(SNMPELEA_NO_REGISTRY_PARAMETERS,status); // write log/trace event record
}
else
{
if ( (status = RegQueryValueEx( // look up trace file name
hkResult,
EXTENSION_TRACE_FILE,
0,
&dwType,
(LPBYTE) szFile,
&nFile) ) == ERROR_SUCCESS)
{
if (dwType != REG_SZ) // we have a bad value.
{
WriteLog(SNMPELEA_REGISTRY_TRACE_FILE_PARAMETER_TYPE, szTraceFileName); // write log/trace event record
}
else
strncpy(szTraceFileName, szFile,MAX_PATH);
}
else
{
WriteLog(SNMPELEA_NO_REGISTRY_TRACE_FILE_PARAMETER,szTraceFileName); // write log/trace event record
}
if ( (status = RegQueryValueEx( // look up trace level
hkResult,
EXTENSION_TRACE_LEVEL,
0,
&dwType,
(LPBYTE) &dwLevel,
&nLvl) ) == ERROR_SUCCESS)
{
if (dwType == REG_DWORD)
nTraceLevel = dwLevel; // copy registry trace level
else
WriteLog(SNMPELEA_REGISTRY_TRACE_LEVEL_PARAMETER_TYPE, nTraceLevel); // write log/trace event record
}
else
{
WriteLog(SNMPELEA_NO_REGISTRY_TRACE_LEVEL_PARAMETER,nTraceLevel); // write log/trace event record
}
status = RegCloseKey(hkResult);
} // end else registry lookup successful
} // end Trace information registry processing
// return if we are not supposed to trace this message
if ( nLevel < nTraceLevel ) // are we tracing this message
{
return; // nope, just exit
}
// if the value could not be read from the registry (we still have the default value)
// then we have no file name, so return.
if (szTraceFileName[0] == TEXT('\0'))
return;
szBuffer[LOG_BUF_SIZE-1] = 0;
va_start(arglist, szFormat);
_vsnprintf(szBuffer, LOG_BUF_SIZE-1, szFormat, arglist);
va_end(arglist);
if (nLevel == MAXDWORD)
{
TraceWrite(FALSE, FALSE, szBuffer);
}
else
{
TraceWrite(FALSE, TRUE, szBuffer);
}
}
}
| 39.098428 | 138 | 0.542665 |
425f7cffba510b1b9021dcb5f89123bd5c20110c | 72 | cpp | C++ | utils/globals.cpp | RapidsAtHKUST/ContinuousSubgraphMatching | f786d19561c8ae13cc7aa2af6e4d41a52aa2aba5 | [
"MIT"
] | null | null | null | utils/globals.cpp | RapidsAtHKUST/ContinuousSubgraphMatching | f786d19561c8ae13cc7aa2af6e4d41a52aa2aba5 | [
"MIT"
] | null | null | null | utils/globals.cpp | RapidsAtHKUST/ContinuousSubgraphMatching | f786d19561c8ae13cc7aa2af6e4d41a52aa2aba5 | [
"MIT"
] | null | null | null | #include "utils/globals.h"
std::atomic<bool> reach_time_limit = false;
| 18 | 43 | 0.75 |
425f925acdc49fd521e74e7d0237aea88e107117 | 470 | hpp | C++ | Results.hpp | h-g-s/ddtree | 4941baf6d66374f5a7c3b7eadd994c2ff8ae55f4 | [
"MIT"
] | 1 | 2019-11-30T14:48:40.000Z | 2019-11-30T14:48:40.000Z | Results.hpp | h-g-s/ddtree | 4941baf6d66374f5a7c3b7eadd994c2ff8ae55f4 | [
"MIT"
] | null | null | null | Results.hpp | h-g-s/ddtree | 4941baf6d66374f5a7c3b7eadd994c2ff8ae55f4 | [
"MIT"
] | null | null | null | /*
* Results.hpp
*
* Created on: 27 de fev de 2019
* Author: haroldo
*/
#ifndef RESULTS_HPP_
#define RESULTS_HPP_
#include <string>
#include <vector>
#include "InstanceSet.hpp"
class Results
{
public:
Results( const InstanceSet &_iset, const char *resFile );
const std::vector< std::string > &algorithms() const;
virtual ~Results ();
private:
const InstanceSet &iset_;
std::vector< std::string > algs_;
};
#endif /* RESULTS_HPP_ */
| 15.666667 | 61 | 0.659574 |
42659843db1fe95995440df1b137db6d97ff4dfe | 16,470 | cpp | C++ | Windows Pin/Windows Pin.cpp | barty32/windows-pin | d89fb0352c5934c403efcfb6518979717920876c | [
"MIT"
] | null | null | null | Windows Pin/Windows Pin.cpp | barty32/windows-pin | d89fb0352c5934c403efcfb6518979717920876c | [
"MIT"
] | null | null | null | Windows Pin/Windows Pin.cpp | barty32/windows-pin | d89fb0352c5934c403efcfb6518979717920876c | [
"MIT"
] | null | null | null | // Windows Pin.cpp : Defines the entry point for the application.
//
#include "Windows Pin.h"
#include "PinDll.h"
bool g_bPinning = false;
HCURSOR g_hPinCursor = NULL;
std::list<HWND> g_pinnedWnds;
// Global Variables:
HINSTANCE hInst;
HWND hWndMain;
const UINT WM_TASKBARCREATED = RegisterWindowMessageW(L"TaskbarCreated");
HHOOK hHook = NULL;
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow){
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
hInst = hInstance;
g_hPinCursor = LoadCursorW(hInst, MAKEINTRESOURCEW(IDI_PIN_CURSOR));
// Register main window class (hidden)
WNDCLASSEXW wcex = {0};
wcex.cbSize = sizeof(WNDCLASSEXW);
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.lpszClassName = L"WindowsPinWndClass";
if(!RegisterClassExW(&wcex)){
ErrorHandler(L"Class registration failed", GetLastError());
return false;
}
hWndMain = CreateWindowExW(WS_EX_LAYERED, L"WindowsPinWndClass", L"Windows Pin", WS_POPUP, 0, 0, 0, 0, 0, 0, hInstance, 0);
if(!hWndMain){
ErrorHandler(L"Window creation failed", GetLastError());
return false;
}
NOTIFYICONDATAW* nid = CreateTrayIcon(hWndMain);
if(!Shell_NotifyIconW(NIM_ADD, (PNOTIFYICONDATAW)GetPropW(hWndMain, L"trayIcon"))){
ErrorHandler(L"Tray icon creation failed", GetLastError());
return false;
}
// Prepare tray popup menu
HMENU hPopMenu = CreatePopupMenu();
InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_BYPOSITION | MF_STRING, IDM_ABOUT, L"About");
InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_BYPOSITION | MF_STRING, IDM_PIN, L"Pin a window");
InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_BYPOSITION | MF_STRING, IDM_UNPIN, L"Unpin all pinned windows");
InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_SEPARATOR, 0, NULL);
InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_BYPOSITION | MF_STRING, IDM_EXIT, L"Exit");
SetPropW(hWndMain, L"hPopMenu", hPopMenu);
// Inject DLL to all 32-bit processes
hHook = SetWindowsHookExW(WH_GETMESSAGE, ExportHookProc, GetModuleHandleW(L"PinDll32"), 0);
if(!hHook){
ErrorHandler(L"32-bit hooking failed", GetLastError());
return false;
}
HANDLE currentProcess = nullptr;
if(Is64BitWindows()){
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
currentProcess = OpenProcess(SYNCHRONIZE, TRUE, GetCurrentProcessId());
std::wstring cmd = L"Inject64.exe --handle " + std::to_wstring((int)currentProcess);
// Start the child process.
if(!CreateProcessW(nullptr,
(LPWSTR)cmd.data(),
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
TRUE, // Handle inheritance
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
){
ErrorHandler(L"64-bit hook execution failed", GetLastError());
return false;
}
WaitForSingleObject(pi.hProcess, 500);
DWORD dwExitCode;
GetExitCodeProcess(pi.hProcess, &dwExitCode);
if(dwExitCode != STILL_ACTIVE && dwExitCode > 0){
ErrorHandler(L"64-bit hook error", dwExitCode);
return false;
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
MSG msg;
while(GetMessageW(&msg, NULL, 0, 0)){
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
delete nid;
DestroyMenu(hPopMenu);
if(currentProcess){
CloseHandle(currentProcess);
}
//UnhookWindowsHookEx(hook);
return (int)msg.wParam;
}
//LRESULT CALLBACK LowLevelMouseProc(
// _In_ int nCode,
// _In_ WPARAM wParam,
// _In_ LPARAM lParam
//){
// static bool bCaptured = false;
// if(nCode >= HC_ACTION){
// LPMSLLHOOKSTRUCT mss = (LPMSLLHOOKSTRUCT)lParam;
// if(g_bPinning){
// switch(wParam){
// case WM_LBUTTONDOWN:
// if(!bCaptured){
// //CallNextHookEx(NULL, nCode, WM_LBUTTONDOWN, lParam);
// //DefWindowProcW(hWndMain, WM_LBUTTONDOWN, 0, MAKELPARAM(mss->pt.x, mss->pt.y));
// //SetCursorPos(mss->pt.x, mss->pt.y);
// SetCursor(g_hPinCursor);
// SetCapture(hWndMain);
// bCaptured = true;
// return false;
// }
// //case WM_LBUTTONDOWN:
// //case WM_MOUSEMOVE:
// //SetCursorPos(100, 100);
//
// //SetCapture(hWndMain);
// //return true;
//
// }
// }
// }
// return CallNextHookEx(NULL, nCode, wParam, lParam);
//}
bool StartPin(HWND hWnd){
g_bPinning = true;
POINT pos;
GetCursorPos(&pos);
// Hacky solution to set mouse capture without clicking
SetWindowPos(hWnd, HWND_TOPMOST, pos.x - 10, pos.y - 10, 20, 20, SWP_SHOWWINDOW);
SetLayeredWindowAttributes(hWnd, RGB(255, 0, 0), 200, LWA_COLORKEY | LWA_ALPHA);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
SetCursor(LoadCursorW(hInst, MAKEINTRESOURCEW(IDI_PIN_CURSOR)));
SetCapture(hWnd);
SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_HIDEWINDOW);
return true;
}
bool EndPin(){
g_bPinning = false;
// Determine the window that lies underneath the mouse cursor.
POINT pt;
GetCursorPos(&pt);
HWND hWnd = FindParent(WindowFromPoint(pt));
ReleaseCapture();
InvalidateRect(NULL, NULL, FALSE);
if(CheckWindowValidity(hWnd)){
//WCHAR title[120];
//GetWindowTextW(hWnd, title, 120);
//WCHAR result[200];
//_snwprintf_s(result, 200, L"Handle: 0x%08X\nTitle: %s", (int)hWnd, title);
//MessageBoxW(NULL, result, L"Info", MB_ICONINFORMATION);
PinWindow(hWnd);
return true;
}
return false;
}
bool MovePin(){
static HWND lastWnd = NULL;
POINT pt;
GetCursorPos(&pt);
// Determine the window that lies underneath the mouse cursor.
HWND hWnd = FindParent(WindowFromPoint(pt));
if(lastWnd == hWnd){
return false;
}
// If there was a previously found window, we must instruct it to refresh itself.
if(lastWnd){
InvalidateRect(NULL, NULL, TRUE);
UpdateWindow(lastWnd);
RedrawWindow(lastWnd, NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
}
// Indicate that this found window is now the current found window.
lastWnd = hWnd;
// Check first for validity.
if(CheckWindowValidity(hWnd)){
return HighlightWindow(hWnd);
}
return false;
}
bool HighlightWindow(HWND hWnd){
HDC hdcScreen = GetWindowDC(NULL);
if(!hdcScreen){
TRACE(L"Highligt window failed - HDC is null");
return false;
}
RECT rcWnd;
if(FAILED(DwmGetWindowAttribute(hWnd, DWMWA_EXTENDED_FRAME_BOUNDS, &rcWnd, sizeof(rcWnd)))){
//TRACE(L"Highligt window failed - GetWindowAttr failed");
GetWindowRect(hWnd, &rcWnd);
}
HPEN hPen = CreatePen(PS_SOLID, 10, RGB(255, 0, 0));
HGDIOBJ oldBrush = SelectObject(hdcScreen, GetStockObject(HOLLOW_BRUSH));
HGDIOBJ oldPen = SelectObject(hdcScreen, hPen);
Rectangle(hdcScreen, rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom);
// Cleanup
SelectObject(hdcScreen, oldBrush);
SelectObject(hdcScreen, oldPen);
DeleteObject(hPen);
ReleaseDC(NULL, hdcScreen);
return true;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam){
if(message == WM_TASKBARCREATED){
Shell_NotifyIconW(NIM_ADD, (PNOTIFYICONDATAW)GetPropW(hWnd, L"trayIcon"));
}
switch(message){
case WM_COMMAND:
// Parse the menu selections:
switch(LOWORD(wParam)){
case IDM_PIN:
//PinActiveWindow(hWnd);
StartPin(hWnd);
break;
case IDM_UNPIN:
for(auto wnd : g_pinnedWnds){
UnpinWindow(wnd);
}
g_pinnedWnds.clear();
break;
case IDM_ABOUT:
return DialogBoxParamW(hInst, MAKEINTRESOURCEW(IDD_ABOUTBOX), hWnd, About, 0);
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProcW(hWnd, message, wParam, lParam);
}
break;
case WM_LBUTTONUP:
if(g_bPinning){
EndPin();
return false;
}
break;
case WM_MOUSEMOVE:
if(g_bPinning){
MovePin();
return false;
}
break;
case WM_USER_SHELLICON:
switch(LOWORD(lParam)){
case WM_RBUTTONUP:
{
POINT lpClickPoint;
UINT uFlag = MF_BYPOSITION | MF_STRING;
GetCursorPos(&lpClickPoint);
TrackPopupMenu((HMENU)GetPropW(hWnd, L"hPopMenu"), TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_BOTTOMALIGN, lpClickPoint.x, lpClickPoint.y, 0, hWnd, NULL);
return true;
}
case WM_LBUTTONUP:
StartPin(hWnd);
return false;
}
break;
case WM_DESTROY:
UnhookWindowsHookEx(hHook);
Shell_NotifyIconW(NIM_DELETE, (PNOTIFYICONDATAW)GetPropW(hWnd, L"trayIcon"));
PostQuitMessage(0);
break;
default:
return DefWindowProcW(hWnd, message, wParam, lParam);
}
return DefWindowProcW(hWnd, message, wParam, lParam);
}
bool PinWindow(HWND hWnd){
LONG dwExStyle = GetWindowLongW(hWnd, GWL_EXSTYLE);
dwExStyle |= WS_EX_TOPMOST;
SetWindowLongW(hWnd, GWL_EXSTYLE, dwExStyle);
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOREDRAW | SWP_NOREPOSITION | SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_SHOWWINDOW);
g_pinnedWnds.push_back(hWnd);
return true;
}
bool UnpinWindow(HWND hWnd){
LONG dwExStyle = GetWindowLongW(hWnd, GWL_EXSTYLE);
dwExStyle &= ~WS_EX_TOPMOST;
SetWindowLongW(hWnd, GWL_EXSTYLE, dwExStyle);
SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOREDRAW | SWP_NOREPOSITION | SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_SHOWWINDOW);
return true;
}
NOTIFYICONDATAW* CreateTrayIcon(HWND hWnd){
// Create tray icon
NOTIFYICONDATAW* nidApp = new NOTIFYICONDATAW;
if(!nidApp) return nullptr;
nidApp->cbSize = sizeof(NOTIFYICONDATAW);
nidApp->hWnd = hWnd; //handle of the window which will process this app. messages
nidApp->uID = IDI_WINDOWSPIN; //ID of the icon that will appear in the system tray
nidApp->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
nidApp->hIcon = LoadIconW(hInst, MAKEINTRESOURCEW(IDI_WINDOWSPIN));
nidApp->uCallbackMessage = WM_USER_SHELLICON;
LoadStringW(hInst, IDS_APPTOOLTIP, nidApp->szTip, _countof(nidApp->szTip));
SetPropW(hWnd, L"trayIcon", nidApp);
return nidApp;
}
bool CheckWindowValidity(HWND hWnd){
if(!hWnd || !IsWindow(hWnd) || hWnd == GetShellWindow() || hWnd == FindWindowW(L"Shell_TrayWnd", NULL)){
return false;
}
return true;
}
HWND FindParent(HWND hWnd){
DWORD dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
if(dwStyle & WS_CHILD){
return FindParent(GetParent(hWnd));
}
return hWnd;
}
bool Is64BitWindows(){
#if defined(_WIN64)
return true; // 64-bit programs run only on Win64
#elif defined(_WIN32)
// 32-bit programs run on both 32-bit and 64-bit Windows, so must sniff
BOOL f64 = FALSE;
return IsWow64Process(GetCurrentProcess(), &f64) && f64;
#else
return false; // Win64 does not support Win16
#endif
}
void ErrorHandler(LPCWSTR errMsg, DWORD errCode, DWORD dwType){
std::wstring msg(errMsg);
if(errCode){
msg.append(L"\nError code: " + std::to_wstring(errCode));
}
MessageBoxW(NULL, msg.c_str(), L"Windows Pin - Error", dwType | MB_OK);
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam){
UNREFERENCED_PARAMETER(lParam);
switch (message){
case WM_INITDIALOG:
return true;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL){
EndDialog(hDlg, LOWORD(wParam));
return true;
}
break;
}
return false;
}
//void PinActiveWindow(HWND hWndApp){
// HWND hwndWindow = GetWindow(GetDesktopWindow(), GW_HWNDFIRST);// GetForegroundWindow();
// LONG dwExStyle = GetWindowLongPtrW(hwndWindow, GWL_EXSTYLE);
// HWND hInsertAfter = NULL;
// if(dwExStyle & WS_EX_TOPMOST){
// dwExStyle &= ~WS_EX_TOPMOST;
// hInsertAfter = HWND_NOTOPMOST;
// ModifyMenuW((HMENU)GetPropW(hWndApp, L"hPopMenu"), IDM_PIN, MF_BYCOMMAND, IDM_PIN, L"Pin current window");
// }
// else{
// dwExStyle |= WS_EX_TOPMOST;
// hInsertAfter = HWND_TOPMOST;
// ModifyMenuW((HMENU)GetPropW(hWndApp, L"hPopMenu"), IDM_PIN, MF_BYCOMMAND, IDM_PIN, L"Unpin current window");
// }
// SetWindowLongPtrW(hwndWindow, GWL_EXSTYLE, dwExStyle);
// SetWindowPos(hwndWindow, hInsertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOREDRAW | SWP_NOREPOSITION | SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_SHOWWINDOW);
//}
//---------------------------------------------------------------------------------------------InitInstance
//BOOL InitInstance(HINSTANCE hInstance){
// obtain msghook library functions
/*HINSTANCE g_hInstLib = LoadLibraryW(L"WindowPinDll.dll");
if(g_hInstLib == NULL){
return FALSE;
}
pfnSetMsgHook = (SetMsgHookT)GetProcAddress(g_hInstLib, "SetMsgHook");
if(NULL == pfnSetMsgHook){
FreeLibrary(g_hInstLib);
return FALSE;
}
pfnUnsetMsgHook = (UnsetMsgHookT)GetProcAddress(g_hInstLib, "UnsetMsgHook");
if(NULL == pfnUnsetMsgHook){
FreeLibrary(g_hInstLib);
return FALSE;
}
pfnSetMsgHook();*/
//(SetMsgHookT)GetProcAddress(g_hInstLib, "SetMsgHook");
//hHook = SetWindowsHookExW(WH_CALLWNDPROC, /*(HOOKPROC)*/HookProc/*GetProcAddress(g_hInstLib, "HookProc")*/, g_hInstLib/*GetModuleHandleW(L"WindowPinDll.dll")*/, 0);
//if(hHook == NULL){
// int error = GetLastError();
//}
//hHook64 = SetWindowsHookExW(WH_CALLWNDPROC, (HOOKPROC)HookProc, GetModuleHandleW(L"WindowPinDll64"), 0);
//hHookCbt = SetWindowsHookExW(WH_CBT, (HOOKPROC)/*CBTProc*/GetProcAddress(g_hInstLib, "CBTProc"), g_hInstLib/*GetModuleHandleW(L"WindowPinDll.dll")*/, 0);
//bPump = TRUE;
//MSG msg;
//while(bPump){
// // Keep pumping...
// PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE);
// TranslateMessage(&msg);
// DispatchMessageW(&msg);
// Sleep(10);
//}
//int error = GetLastError();
//WinExec("notepad.exe", 1);
//}
/*
bool HighlightWindow(HWND hWndIn){
HWND hWnd = hWndIn;//FindParent(hWndIn);
//OutputDebugStringW(std::format(L"Highlighting current window {}\n", (int)hWndIn).c_str());
HDC hdcScreen = GetWindowDC(NULL);
if(!hdcScreen){
ErrorHandler(L"DC is null", GetLastError());
return false;
}
RECT rcWnd;
//GetWindowRect(hWnd, &rcWnd);
DwmGetWindowAttribute(hWnd, DWMWA_EXTENDED_FRAME_BOUNDS, &rcWnd, sizeof(rcWnd));
//RECT rcScreen = {0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)};
//int scrW = GetSystemMetrics(SM_CXSCREEN);
//int scrH = GetSystemMetrics(SM_CYSCREEN);
//RedrawWindow(GetDesktopWindow(), NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
//if(bRefresh){
// InvalidateRect(NULL, NULL, false);
//}
//WCHAR ss[100];
//GetWindowTextW(hWnd, ss, 100);
//HDC tempDC = CreateCompatibleDC(NULL);
//BitBlt(tempDC, 0, 0, rcWnd.right - rcWnd.left, rcWnd.bottom - rcWnd.top, hdc, )
//ExcludeClipRect(hdc, rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom);
//HDC tmpDC = CreateCompatibleDC(g_hdcScreen);
//HBITMAP hBmp = CreateCompatibleBitmap(tmpDC, scrW, scrH);
//SelectObject(tmpDC, hBmp);
//BitBlt(tmpDC, 0, 0, scrW, scrH, g_hdcScreen, 0, 0, SRCCOPY);
//FillRect(tmpDC, &rcWnd, (HBRUSH)CreateSolidBrush(RGB(255, 255, 255)));
//FillRect(tmpDC, &rcWnd, (HBRUSH)GetStockObject(HOLLOW_BRUSH));
HGDIOBJ oldBrush = SelectObject(hdcScreen, GetStockObject(HOLLOW_BRUSH));
HGDIOBJ oldPen = SelectObject(hdcScreen, CreatePen(PS_SOLID, 10, RGB(255, 0, 0)));
////Rectangle(hdc, 0, 0, scrW, scrH);
Rectangle(hdcScreen, rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom);
//InvalidateRect(hWnd, NULL, FALSE);
//FillRect(hdc, &rcWnd, (HBRUSH)GetStockObject(HOLLOW_BRUSH));
//SelectObject(hdc, )
//FillRect(hdc, &rcScreen, );
//BLENDFUNCTION bf = {0};
//bf.SourceConstantAlpha = 200;
//bf.AlphaFormat = AC_SRC_ALPHA;
//if(!AlphaBlend(hdc, 0, 0, scrW, scrH, tmpDC, 0, 0, scrW, scrH, bf)){
// OutputDebugStringW(L"AplhaBlend failed");
//}
//TransparentBlt(hdcScreen, 0, 0, scrW, scrH, tmpDC, 0, 0, scrW, scrH, RGB(255, 255, 255));
SelectObject(hdcScreen, oldBrush);
SelectObject(hdcScreen, oldPen);
ReleaseDC(NULL, hdcScreen);
return true;
}
*/
// Create snapshot of current screen
//int sw = GetSystemMetrics(SM_CXSCREEN);
//int sy = GetSystemMetrics(SM_CYSCREEN);
//HDC hdc = GetWindowDC(NULL);
//g_hdcScreen = CreateCompatibleDC(hdc);
//HBITMAP hBmp = CreateCompatibleBitmap(hdc, sw, sy);
//SelectObject(g_hdcScreen, hBmp);
//BitBlt(g_hdcScreen, 0, 0, sw, sy, hdc, 0, 0, SRCCOPY);
//ReleaseDC(NULL, hdc);
//case WM_PAINT:
//{
// PAINTSTRUCT ps;
// HDC hdc = BeginPaint(hWnd, &ps);
// RECT rc;
// GetWindowRect(hWnd, &rc);
// FillRect(hdc, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH));
// EndPaint(hWnd, &ps);
// return false;
//} | 29.253996 | 167 | 0.702975 |
4266219ebae7d643ef0606185beb79535329e25e | 54 | cpp | C++ | source/framework/algorithm/src/local_operation/cos.cpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 2 | 2021-02-26T22:45:56.000Z | 2021-05-02T10:28:48.000Z | source/framework/algorithm/src/local_operation/cos.cpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 131 | 2020-10-27T13:09:16.000Z | 2022-03-29T10:24:26.000Z | source/framework/algorithm/src/local_operation/cos.cpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | null | null | null | #include "lue/framework/algorithm/definition/cos.hpp"
| 27 | 53 | 0.814815 |
4267171e4f2224965ac76a9a6d9575f74ce643b2 | 1,640 | cpp | C++ | Source/SHOOTACUBE/Accessories/Gun/Ammo.cpp | marvkey/SHOOTACUBE | b98665dec593d2a5b33b66bcb1ebb5a4b896b23f | [
"Apache-2.0"
] | null | null | null | Source/SHOOTACUBE/Accessories/Gun/Ammo.cpp | marvkey/SHOOTACUBE | b98665dec593d2a5b33b66bcb1ebb5a4b896b23f | [
"Apache-2.0"
] | null | null | null | Source/SHOOTACUBE/Accessories/Gun/Ammo.cpp | marvkey/SHOOTACUBE | b98665dec593d2a5b33b66bcb1ebb5a4b896b23f | [
"Apache-2.0"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "Ammo.h"
#include "SHOOTACUBE/Player/Player1.h"
#include "Components/BoxComponent.h"
AAmmo::AAmmo(){}
void AAmmo::BeginPlay(){
Super::BeginPlay();
Collider->OnComponentBeginOverlap.AddDynamic(this,&AAmmo::OnOverlapBegin);
if(AmmoTypeToBeSpawned==AmmoType::SmallAmmo){
AmmoToBeSpawned =FMath::RandRange(10,50);
} else if(AmmoTypeToBeSpawned==AmmoType::MediumAmmo){
AmmoToBeSpawned =FMath::RandRange(10,50);
} else{
AmmoToBeSpawned =FMath::RandRange(1,3);
}
}
void AAmmo::Tick(float DeltaSeconds){
Super::Tick(DeltaSeconds);
}
AmmoType AAmmo::GetAmmoTypeToBeSpawned(){
return AmmoTypeToBeSpawned;
}
void AAmmo::OnOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp,int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult){
if(OtherActor && OtherActor != this){
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Overlap Begin"));
if(OtherActor->IsA(APlayer1::StaticClass())){
APlayer1 * FirstPlayer =Cast<APlayer1>(OtherActor);
if(FirstPlayer->bIsAi == true){return;}
if(this->AmmoTypeToBeSpawned ==AmmoType::SmallAmmo){
FirstPlayer->SmallBulletsAmmo+=AmmoToBeSpawned;
}else if(AmmoTypeToBeSpawned ==AmmoType::MediumAmmo){
FirstPlayer->MediumBulletAmmo+=AmmoToBeSpawned;
}else{
FirstPlayer->RocketLuncherBulletAmmo+=AmmoToBeSpawned;
}
this->Destroy();
}
}
} | 37.272727 | 185 | 0.679268 |
4268bcd1f8b0cd8277ad4667a37fc5336fd20f47 | 8,184 | cpp | C++ | realm/realm-library/src/main/cpp/io_realm_internal_objectstore_OsSubscriptionSet.cpp | Mr4Mike4/realm-java | da732419708d1583fb9c3a13b499dee5b383c465 | [
"Apache-2.0"
] | null | null | null | realm/realm-library/src/main/cpp/io_realm_internal_objectstore_OsSubscriptionSet.cpp | Mr4Mike4/realm-java | da732419708d1583fb9c3a13b499dee5b383c465 | [
"Apache-2.0"
] | null | null | null | realm/realm-library/src/main/cpp/io_realm_internal_objectstore_OsSubscriptionSet.cpp | Mr4Mike4/realm-java | da732419708d1583fb9c3a13b499dee5b383c465 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2022 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* 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 "io_realm_internal_objectstore_OsSubscriptionSet.h"
#include "java_network_transport.hpp"
#include "util.hpp"
#include "jni_util/java_global_weak_ref.hpp"
#include "jni_util/java_method.hpp"
#include "jni_util/jni_utils.hpp"
#include <realm/object-store/shared_realm.hpp>
#include <realm/object-store/binding_callback_thread_observer.hpp>
#include <realm/object-store/sync/app.hpp>
#include <realm/object-store/sync/sync_manager.hpp>
#include <realm/sync/subscriptions.hpp>
#include <jni_util/bson_util.hpp>
using namespace realm;
using namespace realm::app;
using namespace realm::jni_util;
using namespace realm::_impl;
static void finalize_subscription_set(jlong ptr) {
delete reinterpret_cast<sync::SubscriptionSet*>(ptr);
}
JNIEXPORT jlong JNICALL
Java_io_realm_internal_objectstore_OsSubscriptionSet_nativeGetFinalizerMethodPtr(JNIEnv*, jclass) {
return reinterpret_cast<jlong>(&finalize_subscription_set);
}
JNIEXPORT void JNICALL Java_io_realm_internal_objectstore_OsSubscriptionSet_nativeRelease(JNIEnv*, jclass, jlong j_subscription_set_ptr) {
delete reinterpret_cast<sync::SubscriptionSet*>(j_subscription_set_ptr);
}
JNIEXPORT jlong JNICALL Java_io_realm_internal_objectstore_OsSubscriptionSet_nativeSize(JNIEnv* env, jclass, jlong j_subscription_set_ptr)
{
try {
auto subscriptions = reinterpret_cast<sync::SubscriptionSet*>(j_subscription_set_ptr);
return subscriptions->size();
}
CATCH_STD()
return 0;
}
JNIEXPORT jbyte JNICALL Java_io_realm_internal_objectstore_OsSubscriptionSet_nativeState(JNIEnv* env, jclass, jlong j_subscription_set_ptr)
{
try {
auto subscriptions = reinterpret_cast<sync::SubscriptionSet*>(j_subscription_set_ptr);
sync::SubscriptionSet::State state = subscriptions->state();
switch(state) {
case sync::SubscriptionSet::State::Uncommitted:
return io_realm_internal_objectstore_OsSubscriptionSet_STATE_VALUE_UNCOMMITTED;
case sync::SubscriptionSet::State::Pending:
return io_realm_internal_objectstore_OsSubscriptionSet_STATE_VALUE_PENDING;
case sync::SubscriptionSet::State::Bootstrapping:
return io_realm_internal_objectstore_OsSubscriptionSet_STATE_VALUE_BOOTSTRAPPING;
case sync::SubscriptionSet::State::Complete:
return io_realm_internal_objectstore_OsSubscriptionSet_STATE_VALUE_COMPLETE;
case sync::SubscriptionSet::State::Error:
return io_realm_internal_objectstore_OsSubscriptionSet_STATE_VALUE_ERROR;
case sync::SubscriptionSet::State::Superceded:
return io_realm_internal_objectstore_OsSubscriptionSet_STATE_VALUE_SUPERSEDED;
}
}
CATCH_STD()
return 0;
}
JNIEXPORT jlong JNICALL Java_io_realm_internal_objectstore_OsSubscriptionSet_nativeCreateMutableSubscriptionSet(JNIEnv* env, jclass, jlong j_subscription_set_ptr)
{
try {
auto subscriptions = reinterpret_cast<sync::SubscriptionSet*>(j_subscription_set_ptr);
return reinterpret_cast<jlong>(new sync::MutableSubscriptionSet(subscriptions->make_mutable_copy()));
}
CATCH_STD()
return 0;
}
JNIEXPORT jlong JNICALL Java_io_realm_internal_objectstore_OsSubscriptionSet_nativeSubscriptionAt(JNIEnv *env, jclass,
jlong j_subscription_set_ptr,
jint j_index)
{
try {
auto subscriptions = reinterpret_cast<sync::SubscriptionSet*>(j_subscription_set_ptr);
return reinterpret_cast<jlong>(new sync::Subscription(subscriptions->at(j_index)));
}
CATCH_STD()
return 0;
}
JNIEXPORT void JNICALL Java_io_realm_internal_objectstore_OsSubscriptionSet_nativeWaitForSynchronization(JNIEnv *env,
jclass,
jlong j_subscription_set_ptr,
jobject j_callback)
{
try {
auto subscriptions = reinterpret_cast<sync::SubscriptionSet *>(j_subscription_set_ptr);
util::Future<sync::SubscriptionSet::State> result = subscriptions->get_state_change_notification(
sync::SubscriptionSet::State::Complete);
static JavaClass callback_class(env, "io/realm/internal/objectstore/OsSubscriptionSet$StateChangeCallback");
static JavaMethod onchange_method(env, callback_class, "onChange", "(B)V", false);
JavaGlobalWeakRef j_callback_weak(env, j_callback);
std::move(result).get_async([j_callback_weak](StatusOrStatusWith<sync::SubscriptionSet::State> status) noexcept {
JNIEnv* env = JniUtils::get_env(false);
j_callback_weak.call_with_local_ref(env, [&](JNIEnv* env, jobject obj) {
if (status.is_ok()) {
env->CallVoidMethod(obj, onchange_method, static_cast<jbyte>(status.get_value()));
} else {
env->CallVoidMethod(obj, onchange_method, static_cast<jbyte>(sync::SubscriptionSet::State::Error));
}
});
});
}
CATCH_STD()
}
JNIEXPORT jlong JNICALL
Java_io_realm_internal_objectstore_OsSubscriptionSet_nativeFindByName(JNIEnv *env, jclass,
jlong j_subscription_set_ptr,
jstring j_name)
{
try {
auto subscriptions = reinterpret_cast<sync::SubscriptionSet*>(j_subscription_set_ptr);
JStringAccessor name(env, j_name);
sync::SubscriptionSet::const_iterator iter = subscriptions->find(name);
if (iter != subscriptions->end()) {
return reinterpret_cast<jlong>(new sync::Subscription(std::move(*iter)));
} else {
return -1;
}
}
CATCH_STD()
return 0;
}
JNIEXPORT jlong JNICALL Java_io_realm_internal_objectstore_OsSubscriptionSet_nativeFindByQuery(JNIEnv *env, jclass,
jlong j_subscription_set_ptr,
jlong j_query_ptr)
{
try {
auto subscriptions = reinterpret_cast<sync::SubscriptionSet*>(j_subscription_set_ptr);
auto query = reinterpret_cast<Query*>(j_query_ptr);
sync::SubscriptionSet::const_iterator iter = subscriptions->find(*query);
if (iter != subscriptions->end()) {
return reinterpret_cast<jlong>(new sync::Subscription(std::move(*iter)));
} else {
return -1;
}
}
CATCH_STD()
return 0;
}
JNIEXPORT jstring JNICALL Java_io_realm_internal_objectstore_OsSubscriptionSet_nativeErrorMessage(JNIEnv *env, jclass,
jlong j_subscription_set_ptr)
{
try {
auto subscriptions = reinterpret_cast<sync::SubscriptionSet*>(j_subscription_set_ptr);
return to_jstring(env, subscriptions->error_str());
}
CATCH_STD()
return nullptr;
}
JNIEXPORT void JNICALL
Java_io_realm_internal_objectstore_OsSubscriptionSet_nativeRefresh(JNIEnv *env, jclass, jlong j_subscription_set_ptr) {
try {
auto subscriptions = reinterpret_cast<sync::SubscriptionSet *>(j_subscription_set_ptr);
subscriptions->refresh();
}
CATCH_STD()
}
| 43.073684 | 162 | 0.669844 |
4269de30fa7cfb72d6b42b76f5231eb530d0a6ee | 12,518 | cpp | C++ | src/samples/aiff/aiff.cpp | eriser/hivetrekkr | bac051e587fb53fc47bbd18066059c2c402b5720 | [
"BSD-2-Clause"
] | 1 | 2018-10-22T11:32:30.000Z | 2018-10-22T11:32:30.000Z | src/samples/aiff/aiff.cpp | eriser/hivetrekkr | bac051e587fb53fc47bbd18066059c2c402b5720 | [
"BSD-2-Clause"
] | null | null | null | src/samples/aiff/aiff.cpp | eriser/hivetrekkr | bac051e587fb53fc47bbd18066059c2c402b5720 | [
"BSD-2-Clause"
] | 1 | 2019-03-05T15:39:57.000Z | 2019-03-05T15:39:57.000Z | // ------------------------------------------------------
// Protrekkr
// Based on Juan Antonio Arguelles Rius's NoiseTrekker.
//
// Copyright (C) 2008-2014 Franck Charlet.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL FRANCK CHARLET OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
// ------------------------------------------------------
// TODO: add support for AIFC
// ------------------------------------------------------
// Includes
#include "include/aiff.h"
AIFFFile::AIFFFile()
{
file = NULL;
Base_Note = 0;
SustainLoop.PlayMode = NoLooping;
Use_Floats = 0;
Loop_Start = 0;
Loop_End = 0;
}
AIFFFile::~AIFFFile()
{
Close();
}
unsigned long AIFFFile::FourCC(const char *ChunkName)
{
long retbuf = 0x20202020; // four spaces (padding)
char *p = ((char *) &retbuf);
// Remember, this is Intel format!
// The first character goes in the LSB
for (int i = 0; i < 4 && ChunkName[i]; i++)
{
*p++ = ChunkName[i];
}
return retbuf;
}
// ------------------------------------------------------
// Look for a chunk inside the file
// Return it's length (with file pointing to it's data) or 0
int AIFFFile::SeekChunk(const char *ChunkName)
{
int Chunk;
int Chunk_To_Find_Lo;
int Chunk_To_Find = FourCC(ChunkName);
int i;
int size;
i = 0;
Chunk_To_Find_Lo = tolower(Chunk_To_Find & 0xff);
Chunk_To_Find_Lo |= tolower((Chunk_To_Find >> 8) & 0xff) << 8;
Chunk_To_Find_Lo |= tolower((Chunk_To_Find >> 16) & 0xff) << 16;
Chunk_To_Find_Lo |= tolower((Chunk_To_Find >> 24) & 0xff) << 24;
Seek(i);
while(!feof(file))
{
Chunk = 0;
Seek(i);
Read(&Chunk, 4);
if(Chunk == Chunk_To_Find ||
Chunk == Chunk_To_Find_Lo)
{
Read(&size, 4);
return(Mot_Swap_32(size));
}
// Skip the data part to speed up the process
if(Chunk == SoundDataID)
{
Read(&size, 4);
size = Mot_Swap_32(size);
i += size + 4 + 4 - 1;
}
i++;
}
return(0);
}
int AIFFFile::Open(const char *Filename)
{
int chunk_size;
int Padding;
int Phony_Byte;
short Phony_Short;
file = fopen(Filename, "rb");
if(file)
{
// Those compression schemes are not supported
chunk_size = SeekChunk("ALAW");
if(chunk_size) return 0;
chunk_size = SeekChunk("ULAW");
if(chunk_size) return 0;
chunk_size = SeekChunk("G722");
if(chunk_size) return 0;
chunk_size = SeekChunk("G726");
if(chunk_size) return 0;
chunk_size = SeekChunk("G728");
if(chunk_size) return 0;
chunk_size = SeekChunk("GSM ");
if(chunk_size) return 0;
chunk_size = SeekChunk("COMM");
if(chunk_size)
{
Read(&CommDat.numChannels, sizeof(short));
CommDat.numChannels = Mot_Swap_16(CommDat.numChannels);
Read(&CommDat.numSampleFrames, sizeof(unsigned long));
CommDat.numSampleFrames = Mot_Swap_32(CommDat.numSampleFrames);
Read(&CommDat.sampleSize, sizeof(short));
CommDat.sampleSize = Mot_Swap_16(CommDat.sampleSize);
chunk_size = SeekChunk("INST");
// (Not mandatory)
if(chunk_size)
{
Read(&Base_Note, sizeof(char));
Read(&Phony_Byte, sizeof(char)); // detune
Read(&Phony_Byte, sizeof(char)); // lowNote
Read(&Phony_Byte, sizeof(char)); // highNote
Read(&Phony_Byte, sizeof(char)); // lowVelocity
Read(&Phony_Byte, sizeof(char)); // highVelocity
Read(&Phony_Short, sizeof(short)); // gain
Read(&SustainLoop, sizeof(Loop)); // sustainLoop
SustainLoop.PlayMode = Mot_Swap_16(SustainLoop.PlayMode);
SustainLoop.beginLoop = Mot_Swap_16(SustainLoop.beginLoop);
SustainLoop.endLoop = Mot_Swap_16(SustainLoop.endLoop);
if(SustainLoop.beginLoop < SustainLoop.endLoop)
{
// Find loop points
Loop_Start = Get_Marker(SustainLoop.beginLoop);
Loop_End = Get_Marker(SustainLoop.endLoop);
// Messed up data
if(Loop_Start >= Loop_End)
{
SustainLoop.PlayMode = NoLooping;
}
}
else
{
// Doc specifies that begin must be smaller
// otherwise there's no loop
SustainLoop.PlayMode = NoLooping;
}
}
chunk_size = SeekChunk("FL32");
if(chunk_size) Use_Floats = 1;
chunk_size = SeekChunk("FL64");
if(chunk_size) Use_Floats = 1;
chunk_size = SeekChunk("SSND");
if(chunk_size)
{
// Dummy reads
Read(&Padding, sizeof(unsigned long));
Read(&Block_Size, sizeof(unsigned long));
Seek(CurrentFilePosition() + Padding);
// File pos now points on waveform data
return 1;
}
}
}
return 0;
}
long AIFFFile::CurrentFilePosition()
{
return ftell(file);
}
int AIFFFile::Seek(long offset)
{
fflush(file);
if(fseek(file, offset, SEEK_SET))
{
return(0);
}
else
{
return(1);
}
}
int AIFFFile::Read(void *Data, unsigned NumBytes)
{
return fread(Data, NumBytes, 1, file);
}
void AIFFFile::Close()
{
if(file) fclose(file);
file = NULL;
}
int AIFFFile::BitsPerSample()
{
return CommDat.sampleSize;
}
int AIFFFile::NumChannels()
{
return CommDat.numChannels;
}
unsigned long AIFFFile::LoopStart()
{
return Loop_Start;
}
unsigned long AIFFFile::LoopEnd()
{
return Loop_End;
}
unsigned long AIFFFile::NumSamples()
{
return CommDat.numSampleFrames;
}
int AIFFFile::BaseNote()
{
return Base_Note;
}
int AIFFFile::LoopType()
{
return SustainLoop.PlayMode;
}
int AIFFFile::ReadMonoSample(short *Sample)
{
int retcode;
float y;
double y64;
unsigned long int_y;
Uint64 int_y64;
switch(CommDat.sampleSize)
{
case 8:
unsigned char x;
retcode = Read(&x, 1);
*Sample = (short(x) << 8);
break;
case 12:
case 16:
retcode = Read(Sample, 2);
*Sample = Mot_Swap_16(*Sample);
break;
case 24:
int_y = 0;
retcode = Read(&int_y, 3);
int_y = Mot_Swap_32(int_y);
*Sample = (short) (int_y / 65536);
break;
case 32:
retcode = Read(&int_y, 4);
int_y = Mot_Swap_32(int_y);
if(Use_Floats)
{
IntToFloat((int *) &y, int_y);
*Sample = (short) (y * 32767.0f);
}
else
{
*Sample = (short) (int_y / 65536);
}
break;
case 64:
retcode = Read(&int_y64, 8);
int_y64 = Mot_Swap_64(int_y64);
Int64ToDouble((Uint64 *) &y64, int_y64);
*Sample = (short) (y64 * 32767.0);
break;
default:
retcode = 0;
}
return retcode;
}
int AIFFFile::ReadStereoSample(short *L, short *R)
{
int retcode = 0;
unsigned char x[2];
short y[2];
float z[2];
double z64[2];
long int_z[2];
Uint64 int_z64[2];
switch(CommDat.sampleSize)
{
case 8:
retcode = Read(x, 2);
*L = (short (x[0]) << 8);
*R = (short (x[1]) << 8);
break;
case 12:
case 16:
retcode = Read(y, 4);
y[0] = Mot_Swap_16(y[0]);
y[1] = Mot_Swap_16(y[1]);
*L = short(y[0]);
*R = short(y[1]);
break;
case 24:
int_z[0] = 0;
int_z[1] = 0;
retcode = Read(&int_z[0], 3);
retcode = Read(&int_z[1], 3);
int_z[0] = Mot_Swap_32(int_z[0]);
int_z[1] = Mot_Swap_32(int_z[1]);
*L = (short) (int_z[0] / 65536);
*R = (short) (int_z[1] / 65536);
break;
case 32:
retcode = Read(int_z, 8);
int_z[0] = Mot_Swap_32(int_z[0]);
int_z[1] = Mot_Swap_32(int_z[1]);
if(Use_Floats)
{
IntToFloat((int *) &z[0], int_z[0]);
IntToFloat((int *) &z[1], int_z[1]);
*L = (short) (z[0] * 32767.0f);
*R = (short) (z[1] * 32767.0f);
}
else
{
*L = (short) (int_z[0] / 65536);
*R = (short) (int_z[1] / 65536);
}
break;
case 64:
retcode = Read(int_z64, 16);
int_z64[0] = Mot_Swap_64(int_z64[0]);
int_z64[1] = Mot_Swap_64(int_z64[1]);
Int64ToDouble((Uint64 *) &z64[0], int_z64[0]);
Int64ToDouble((Uint64 *) &z64[1], int_z64[1]);
*L = (short) (z64[0] * 32767.0);
*R = (short) (z64[1] * 32767.0);
break;
default:
retcode = 0;
}
return retcode;
}
int AIFFFile::Get_Marker(int Marker_Id)
{
unsigned char string_size;
int i;
int chunk_size = SeekChunk("MARK");
if(chunk_size)
{
Read(&Markers.numMarkers, sizeof(unsigned short));
Markers.numMarkers = Mot_Swap_16(Markers.numMarkers);
for(i = 0 ; i < Markers.numMarkers; i++)
{
Read(&CurMarker.id, sizeof(unsigned short));
CurMarker.id = Mot_Swap_16(CurMarker.id);
Read(&CurMarker.position, sizeof(unsigned long));
CurMarker.position = Mot_Swap_32(CurMarker.position);
if(CurMarker.id == Marker_Id)
{
return(CurMarker.position);
}
else
{
Read(&string_size, sizeof(unsigned char));
string_size++;
Seek(CurrentFilePosition() + string_size);
}
}
// Couldn't find the specified marker so disable everything
SustainLoop.PlayMode = NoLooping;
return(-1);
}
else
{
// Everything is broken so disable looping
SustainLoop.PlayMode = NoLooping;
return(-1);
}
}
void AIFFFile::IntToFloat(int *Dest, int Source)
{
*Dest = Source;
}
void AIFFFile::Int64ToDouble(Uint64 *Dest, Uint64 Source)
{
*Dest = Source;
}
| 28.067265 | 81 | 0.506071 |
426c13fd0ff5d057eb38130136cf45fe3043ea2c | 6,174 | hpp | C++ | inference-engine/thirdparty/mkl-dnn/src/cpu/jit_avx512_core_x8s8s32x_1x1_deconvolution.hpp | zhoub/dldt | e42c01cf6e1d3aefa55e2c5df91f1054daddc575 | [
"Apache-2.0"
] | 52 | 2019-12-11T14:33:19.000Z | 2021-09-24T14:09:54.000Z | inference-engine/thirdparty/mkl-dnn/src/cpu/jit_avx512_core_x8s8s32x_1x1_deconvolution.hpp | zhoub/dldt | e42c01cf6e1d3aefa55e2c5df91f1054daddc575 | [
"Apache-2.0"
] | 13 | 2019-12-12T04:15:23.000Z | 2021-09-06T01:16:04.000Z | inference-engine/thirdparty/mkl-dnn/src/cpu/jit_avx512_core_x8s8s32x_1x1_deconvolution.hpp | zhoub/dldt | e42c01cf6e1d3aefa55e2c5df91f1054daddc575 | [
"Apache-2.0"
] | 15 | 2019-12-12T00:58:07.000Z | 2021-09-15T09:37:39.000Z |
/*******************************************************************************
* Copyright 2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* 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.
*******************************************************************************/
#ifndef CPU_JIT_AVX512_CORE_X8S8S32X_1X1_DECONVOLUTION_HPP
#define CPU_JIT_AVX512_CORE_X8S8S32X_1X1_DECONVOLUTION_HPP
#include "c_types_map.hpp"
#include "cpu_deconvolution_pd.hpp"
#include "cpu_engine.hpp"
#include "cpu_reducer.hpp"
#include "mkldnn_thread.hpp"
#include "utils.hpp"
#include "cpu_convolution_pd.hpp"
#include "type_helpers.hpp"
#include "primitive_iterator.hpp"
#include "jit_uni_1x1_conv_utils.hpp"
#include "jit_avx512_core_x8s8s32x_1x1_convolution.hpp"
namespace mkldnn {
namespace impl {
namespace cpu {
template <impl::data_type_t src_type, impl::data_type_t dst_type>
struct jit_avx512_core_x8s8s32x_1x1_deconvolution_fwd_t
: public cpu_primitive_t {
struct pd_t : public cpu_deconvolution_fwd_pd_t {
pd_t(engine_t *engine, const deconvolution_desc_t *adesc,
const primitive_attr_t *attr,
const deconvolution_fwd_pd_t *hint_fwd_pd)
: cpu_deconvolution_fwd_pd_t(engine, adesc, attr, hint_fwd_pd)
, conv_pd_(nullptr) {}
pd_t(const pd_t &other)
: cpu_deconvolution_fwd_pd_t(other)
, conv_pd_(other.conv_pd_->clone())
, conv_supports_bias_(other.conv_supports_bias_) {}
~pd_t() { delete conv_pd_; }
DECLARE_DECONVOLUTION_PD_T(
jit_avx512_core_x8s8s32x_1x1_deconvolution_fwd_t<src_type,
dst_type>);
status_t init_convolution() {
convolution_desc_t cd;
status_t status;
auto dd = this->desc();
status = conv_desc_init(&cd, prop_kind::forward_training,
alg_kind::convolution_direct, &(dd->src_desc),
&(dd->weights_desc), &(dd->bias_desc), &(dd->dst_desc),
dd->strides, dd->dilates, dd->padding[0], dd->padding[1],
dd->padding_kind);
if (status == status::success) {
status = mkldnn_primitive_desc::create<
typename mkldnn::impl::cpu::
jit_avx512_core_x8s8s32x_1x1_convolution_fwd_t<src_type,
dst_type>::pd_t>(&conv_pd_,
(op_desc_t *)&cd, &(this->attr_), this->engine_,
nullptr);
}
if (status == status::success) {
status = set_default_params();
}
return status;
};
virtual status_t init() override {
using namespace prop_kind;
status_t status;
assert(this->engine()->kind() == engine_kind::cpu);
bool ok = true && utils::one_of(this->desc()->prop_kind,
prop_kind::forward_training,
prop_kind::forward_inference)
&& this->desc()->alg_kind == alg_kind::deconvolution_direct
&& !this->has_zero_dim_memory()
&& this->desc()->src_desc.data_type == src_type
&& this->desc()->dst_desc.data_type == dst_type
&& this->desc()->weights_desc.data_type == data_type::s8
&& IMPLICATION(this->with_bias(),
utils::one_of(this->desc()->bias_desc.data_type,
data_type::f32, data_type::s32,
data_type::s8, data_type::u8))
&& this->desc()->accum_data_type == data_type::s32;
if (ok)
status = init_convolution();
else
status = status::unimplemented;
return status;
}
protected:
virtual status_t set_default_params() {
using namespace memory_format;
auto conv_1x1_pd_ = static_cast<typename mkldnn::impl::cpu::
jit_avx512_core_x8s8s32x_1x1_convolution_fwd_t<src_type,
dst_type>::pd_t *>(conv_pd_);
CHECK(this->src_pd_.set_format(
conv_1x1_pd_->src_pd()->desc()->format));
CHECK(this->dst_pd_.set_format(
conv_1x1_pd_->dst_pd()->desc()->format));
CHECK(this->weights_pd_.set_format(
conv_1x1_pd_->weights_pd()->desc()->format));
if (this->with_bias())
CHECK(this->bias_pd_.set_format(
conv_1x1_pd_->weights_pd(1)->desc()->format));
return status::success;
}
primitive_desc_t *conv_pd_;
bool conv_supports_bias_;
};
jit_avx512_core_x8s8s32x_1x1_deconvolution_fwd_t(const pd_t *apd,
const input_vector &inputs, const output_vector &outputs)
: cpu_primitive_t(apd, inputs, outputs), conv_p_(nullptr) {}
~jit_avx512_core_x8s8s32x_1x1_deconvolution_fwd_t() {
delete this->conv_p_;
}
virtual void execute(event_t *e) const {
switch (pd()->desc()->prop_kind) {
case prop_kind::forward_training:
case prop_kind::forward_inference: (conv_p_)->execute(e); break;
default: assert(!"invalid prop_kind");
}
e->set_state(event_t::ready);
}
private:
const pd_t *pd() const { return (const pd_t *)primitive_t::pd(); }
primitive_t *conv_p_;
};
}
}
}
#endif /* CPU_JIT_AVX512_CORE_X8S8S32X_1X1_DECONVOLUTION_HPP */
| 37.877301 | 88 | 0.573858 |
426d393697ce31c2e9966196878a5b2b0785e8d7 | 693 | cpp | C++ | HOL6/unified/main.cpp | sudopluto/GPUClassS19 | 6bc0ff715b0c2082e46fd77d33fe1cf8486b09f4 | [
"MIT"
] | null | null | null | HOL6/unified/main.cpp | sudopluto/GPUClassS19 | 6bc0ff715b0c2082e46fd77d33fe1cf8486b09f4 | [
"MIT"
] | null | null | null | HOL6/unified/main.cpp | sudopluto/GPUClassS19 | 6bc0ff715b0c2082e46fd77d33fe1cf8486b09f4 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
void initialize (int N, float *a, float *b, float *c){
for (int i = 0; i < N; i++){
if (i < N){
c[i] = 0;
a[i] = 1 + i;
b[i] = 1 - i;
}
}
}
void addVectors (int N, float *a, float *b, float *c){
for (int i = 0; i < N; i++){
if (i < N){
c[i] = a[i] + b[i];
}
}
}
int main (int argc, char **argv){
if (argc != 2) exit (1);
int N = atoi(argv[1]);
float *a, *b, *c;
a = (float *) malloc(N*sizeof(float));
b = (float *) malloc(N*sizeof(float));
c = (float *) malloc(N*sizeof(float));
initialize(N,a,b,c);
addVectors(N,a,b,c);
for (int i = 0; i < 5; i++) {
printf("%f\n", c[i]);
}
free(a);
free(b);
free(c);
}
| 15.75 | 54 | 0.486291 |
426d9e182fd082858b230aa1f5cd48f10aac8725 | 3,192 | cc | C++ | modules/congestion_controller/goog_cc/congestion_window_pushback_controller_unittest.cc | minstrelsy/webrtc-official | cfe75c12ee04d17e7898ebc0a8ad1051b6627e53 | [
"BSD-3-Clause"
] | 305 | 2020-03-31T14:12:50.000Z | 2022-03-19T16:45:49.000Z | modules/congestion_controller/goog_cc/congestion_window_pushback_controller_unittest.cc | daixy111040536/webrtc | 7abfc990c00ab35090fff285fcf635d1d7892433 | [
"BSD-3-Clause"
] | 23 | 2020-04-29T11:41:23.000Z | 2021-09-07T02:07:57.000Z | modules/congestion_controller/goog_cc/congestion_window_pushback_controller_unittest.cc | daixy111040536/webrtc | 7abfc990c00ab35090fff285fcf635d1d7892433 | [
"BSD-3-Clause"
] | 122 | 2020-04-17T11:38:56.000Z | 2022-03-25T15:48:42.000Z | /*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/congestion_controller/goog_cc/congestion_window_pushback_controller.h"
#include <memory>
#include "api/transport/field_trial_based_config.h"
#include "test/field_trial.h"
#include "test/gmock.h"
#include "test/gtest.h"
using ::testing::_;
namespace webrtc {
namespace test {
class CongestionWindowPushbackControllerTest : public ::testing::Test {
public:
CongestionWindowPushbackControllerTest() {
cwnd_controller_.reset(
new CongestionWindowPushbackController(&field_trial_config_));
}
protected:
FieldTrialBasedConfig field_trial_config_;
std::unique_ptr<CongestionWindowPushbackController> cwnd_controller_;
};
TEST_F(CongestionWindowPushbackControllerTest, FullCongestionWindow) {
cwnd_controller_->UpdateOutstandingData(100000);
cwnd_controller_->SetDataWindow(DataSize::bytes(50000));
uint32_t bitrate_bps = 80000;
bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps);
EXPECT_EQ(72000u, bitrate_bps);
cwnd_controller_->SetDataWindow(DataSize::bytes(50000));
bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps);
EXPECT_EQ(static_cast<uint32_t>(72000 * 0.9 * 0.9), bitrate_bps);
}
TEST_F(CongestionWindowPushbackControllerTest, NormalCongestionWindow) {
cwnd_controller_->UpdateOutstandingData(199999);
cwnd_controller_->SetDataWindow(DataSize::bytes(200000));
uint32_t bitrate_bps = 80000;
bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps);
EXPECT_EQ(80000u, bitrate_bps);
}
TEST_F(CongestionWindowPushbackControllerTest, LowBitrate) {
cwnd_controller_->UpdateOutstandingData(100000);
cwnd_controller_->SetDataWindow(DataSize::bytes(50000));
uint32_t bitrate_bps = 35000;
bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps);
EXPECT_EQ(static_cast<uint32_t>(35000 * 0.9), bitrate_bps);
cwnd_controller_->SetDataWindow(DataSize::bytes(20000));
bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps);
EXPECT_EQ(30000u, bitrate_bps);
}
TEST_F(CongestionWindowPushbackControllerTest, NoPushbackOnDataWindowUnset) {
cwnd_controller_->UpdateOutstandingData(1e8); // Large number
uint32_t bitrate_bps = 80000;
bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps);
EXPECT_EQ(80000u, bitrate_bps);
}
TEST_F(CongestionWindowPushbackControllerTest, PushbackOnInititialDataWindow) {
test::ScopedFieldTrials trials("WebRTC-CongestionWindow/InitWin:100000/");
cwnd_controller_.reset(
new CongestionWindowPushbackController(&field_trial_config_));
cwnd_controller_->UpdateOutstandingData(1e8); // Large number
uint32_t bitrate_bps = 80000;
bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps);
EXPECT_GT(80000u, bitrate_bps);
}
} // namespace test
} // namespace webrtc
| 33.957447 | 88 | 0.794486 |
f11737a8bdf71e8e728cc3403ef9cde13391f555 | 3,515 | cpp | C++ | gfx/region_pixman.cpp | clarfonthey/laf | 305592194e3d89dfe6d16648bf84576a2f7b05a5 | [
"MIT"
] | 186 | 2017-04-25T12:13:05.000Z | 2022-03-30T08:06:47.000Z | gfx/region_pixman.cpp | clarfonthey/laf | 305592194e3d89dfe6d16648bf84576a2f7b05a5 | [
"MIT"
] | 34 | 2016-12-20T16:33:31.000Z | 2022-03-29T21:07:52.000Z | gfx/region_pixman.cpp | clarfonthey/laf | 305592194e3d89dfe6d16648bf84576a2f7b05a5 | [
"MIT"
] | 47 | 2016-12-19T17:23:46.000Z | 2022-03-30T19:45:55.000Z | // LAF Gfx Library
// Copyright (C) 2001-2015 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pixman.h"
#include "base/debug.h"
#include "gfx/point.h"
#include "gfx/region.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
namespace gfx {
inline Rect to_rect(const pixman_box32& extends)
{
return Rect(
extends.x1, extends.y1,
extends.x2 - extends.x1,
extends.y2 - extends.y1);
}
Region::Region()
{
pixman_region32_init(&m_region);
}
Region::Region(const Region& copy)
{
pixman_region32_init(&m_region);
pixman_region32_copy(&m_region, ©.m_region);
}
Region::Region(const Rect& rect)
{
if (!rect.isEmpty())
pixman_region32_init_rect(&m_region, rect.x, rect.y, rect.w, rect.h);
else
pixman_region32_init(&m_region);
}
Region::~Region()
{
pixman_region32_fini(&m_region);
}
Region& Region::operator=(const Rect& rect)
{
if (!rect.isEmpty()) {
pixman_box32 box = { rect.x, rect.y, rect.x2(), rect.y2() };
pixman_region32_reset(&m_region, &box);
}
else
pixman_region32_clear(&m_region);
return *this;
}
Region& Region::operator=(const Region& copy)
{
pixman_region32_copy(&m_region, ©.m_region);
return *this;
}
Region::iterator Region::begin()
{
iterator it;
it.m_ptr = pixman_region32_rectangles(&m_region, NULL);
return it;
}
Region::iterator Region::end()
{
iterator it;
it.m_ptr = pixman_region32_rectangles(&m_region, NULL) + size();
return it;
}
Region::const_iterator Region::begin() const
{
const_iterator it;
it.m_ptr = pixman_region32_rectangles(&m_region, NULL);
return it;
}
Region::const_iterator Region::end() const
{
const_iterator it;
it.m_ptr = pixman_region32_rectangles(&m_region, NULL) + size();
return it;
}
bool Region::isEmpty() const
{
return (pixman_region32_not_empty(&m_region) ? false: true);
}
bool Region::isRect() const
{
return (size() == 1);
}
bool Region::isComplex() const
{
return (size() > 1);
}
std::size_t Region::size() const
{
return pixman_region32_n_rects(&m_region);
}
Rect Region::bounds() const
{
return to_rect(*pixman_region32_extents(&m_region));
}
void Region::clear()
{
pixman_region32_clear(&m_region);
}
void Region::offset(int dx, int dy)
{
pixman_region32_translate(&m_region, dx, dy);
}
void Region::offset(const PointT<int>& delta)
{
pixman_region32_translate(&m_region, delta.x, delta.y);
}
Region& Region::createIntersection(const Region& a, const Region& b)
{
pixman_region32_intersect(&m_region, &a.m_region, &b.m_region);
return *this;
}
Region& Region::createUnion(const Region& a, const Region& b)
{
pixman_region32_union(&m_region, &a.m_region, &b.m_region);
return *this;
}
Region& Region::createSubtraction(const Region& a, const Region& b)
{
pixman_region32_subtract(&m_region, &a.m_region, &b.m_region);
return *this;
}
bool Region::contains(const PointT<int>& pt) const
{
return pixman_region32_contains_point(&m_region, pt.x, pt.y, NULL) ? true: false;
}
Region::Overlap Region::contains(const Rect& rect) const
{
static_assert(
int(Out) == int(PIXMAN_REGION_OUT) &&
int(In) == int(PIXMAN_REGION_IN) &&
int(Part) == int(PIXMAN_REGION_PART), "Pixman constants have changed");
pixman_box32 box = { rect.x, rect.y, rect.x2(), rect.y2() };
return (Region::Overlap)pixman_region32_contains_rectangle(&m_region, &box);
}
} // namespace gfx
| 20.085714 | 83 | 0.702703 |
f119ccfb9176845b806213b365af93a316cf0fff | 6,870 | cpp | C++ | frameworks/entity/plugins/wheels/dmzEntityPluginWheels.cpp | shillcock/dmz | 02174b45089e12cd7f0840d5259a00403cd1ccff | [
"MIT"
] | 2 | 2015-11-05T03:03:40.000Z | 2016-02-03T21:50:40.000Z | frameworks/entity/plugins/wheels/dmzEntityPluginWheels.cpp | dmzgroup/dmz | fc2d9ddcb04ed71f4106b8d33539529807b3dea6 | [
"MIT"
] | null | null | null | frameworks/entity/plugins/wheels/dmzEntityPluginWheels.cpp | dmzgroup/dmz | fc2d9ddcb04ed71f4106b8d33539529807b3dea6 | [
"MIT"
] | null | null | null | #include <dmzEntityConsts.h>
#include "dmzEntityPluginWheels.h"
#include <dmzObjectAttributeMasks.h>
#include <dmzObjectConsts.h>
#include <dmzObjectModule.h>
#include <dmzRuntimeConfig.h>
#include <dmzRuntimeConfigToTypesBase.h>
#include <dmzRuntimePluginFactoryLinkSymbol.h>
#include <dmzRuntimePluginInfo.h>
#include <dmzRuntimeObjectType.h>
#include <dmzTypesMatrix.h>
#include <dmzTypesVector.h>
/*!
\class dmz::EntityPluginWheels
\ingroup Entity
\brief Articulates an object's wheels based on velocity.
\details
\code
<dmz>
<runtime>
<object-type name="Type">
<wheels pairs="Int32" radius="Float64" root="String" modifier="Float64"/>
</object-type>
</runtime>
</dmz>
\endcode
Wheels are defined on a ObjectType basis.
- pairs: Number of wheel pairs. Defaults to 0.
- radius: Wheel radius in meters. Defaults to 0.25.
- root: Root of the wheel attribute name. Defaults to dmz::EntityWheelRootName.
- modifier: Defaults to 1.0
*/
//! \cond
dmz::EntityPluginWheels::EntityPluginWheels (const PluginInfo &Info, Config &local) :
Plugin (Info),
TimeSlice (Info),
ObjectObserverUtil (Info, local),
_log (Info),
_defs (Info),
_defaultAttr (0) {
_init (local);
}
dmz::EntityPluginWheels::~EntityPluginWheels () {
_wheelTable.empty ();
_objTable.empty ();
}
// Plugin Interface
void
dmz::EntityPluginWheels::update_plugin_state (
const PluginStateEnum State,
const UInt32 Level) {
if (State == PluginStateInit) {
}
else if (State == PluginStateStart) {
}
else if (State == PluginStateStop) {
}
else if (State == PluginStateShutdown) {
}
}
void
dmz::EntityPluginWheels::discover_plugin (
const PluginDiscoverEnum Mode,
const Plugin *PluginPtr) {
if (Mode == PluginDiscoverAdd) {
}
else if (Mode == PluginDiscoverRemove) {
}
}
// Time Slice Interface
void
dmz::EntityPluginWheels::update_time_slice (const Float64 DeltaTime) {
ObjectModule *module = get_object_module ();
if (module) {
HashTableHandleIterator it;
ObjectStruct *os (0);
while (_objTable.get_next (it, os)) {
Matrix ori;
Vector vel;
module->lookup_velocity (os->Object, _defaultAttr, vel);
module->lookup_orientation (os->Object, _defaultAttr, ori);
Float64 speed = vel.magnitude ();
if (!is_zero64 (speed)) {
Vector dir (0.0, 0.0, -1.0);
ori.transform_vector (dir);
if (dir.get_angle (vel) > HalfPi64) { speed = -speed; }
const Float64 Distance = speed * DeltaTime;
WheelStruct *wheel (os->wheels);
while (wheel) {
Float64 value (0.0);
module->lookup_scalar (os->Object, wheel->Attr, value);
value -= (Distance * wheel->InvertRadius * wheel->Mod);
value = normalize_angle (value);
module->store_scalar (os->Object, wheel->Attr, value);
wheel = wheel->next;
}
}
}
}
}
// Object Observer Interface
void
dmz::EntityPluginWheels::create_object (
const UUID &Identity,
const Handle ObjectHandle,
const ObjectType &Type,
const ObjectLocalityEnum Locality) {
WheelStruct *ws = _lookup_wheels_def (Type);
if (ws) {
ObjectStruct *os = new ObjectStruct (ObjectHandle, ws);
if (os && !_objTable.store (ObjectHandle, os)) { delete os; os = 0; }
}
}
void
dmz::EntityPluginWheels::destroy_object (
const UUID &Identity,
const Handle ObjectHandle) {
ObjectStruct *os = _objTable.remove (ObjectHandle);
if (os) { delete os; os = 0; }
}
dmz::EntityPluginWheels::WheelStruct *
dmz::EntityPluginWheels::_lookup_wheels_def (const ObjectType &Type) {
WheelStruct *result (0);
ObjectType current (Type);
while (!result && current) {
result = _wheelTable.lookup (current.get_handle ());
if (!result) { result = _create_wheels_def (current); }
current.become_parent ();
}
return result;
}
namespace {
static const dmz::UInt32 FlipRight = 0x01;
static const dmz::UInt32 FlipLeft = 0x02;
};
dmz::EntityPluginWheels::WheelStruct *
dmz::EntityPluginWheels::_create_wheels_def (const ObjectType &Type) {
WheelStruct *result (0);
Config wheels;
if (Type.get_config ().lookup_all_config_merged ("wheels", wheels)) {
UInt32 flip (0);
const Float64 Radius = config_to_float64 ("radius", wheels, 0.25);
const Float64 Mod = config_to_float64 ("modifier", wheels, 1.0);
const String Root = config_to_string ("root", wheels, EntityWheelRootName);
const Int32 Pairs = config_to_int32 ("pairs", wheels, 0);
const String FlipString = config_to_string ("reverse", wheels, "none");
if (FlipString == "left") { flip = FlipLeft; }
else if (FlipString == "right") { flip = FlipRight; }
else if ((FlipString == "both") || (FlipString == "all")) {
flip = FlipLeft | FlipRight;
}
else if (FlipString == "none") { flip = 0; }
if (Radius > 0.0) {
const Float64 InvertRadius = 1.0 / Radius;
if (Pairs > 0) {
for (Int32 ix = 1; ix <= Pairs; ix++) {
Handle attr = _defs.create_named_handle (
create_wheel_attribute_name (Root, EntityWheelLeft, ix));
WheelStruct *ws = new WheelStruct (
attr,
InvertRadius,
Mod * (flip & FlipLeft ? -1.0 : 1.0));
if (ws) {
ws->next = result;
result = ws;
}
attr = _defs.create_named_handle (
create_wheel_attribute_name (Root, EntityWheelRight, ix));
ws = new WheelStruct (
attr,
InvertRadius,
Mod * (flip & FlipRight ? -1.0 : 1.0));
if (ws) {
ws->next = result;
result = ws;
}
}
}
else {
_log.error << "Must have at least one wheel pair in type: "
<< Type.get_name () << endl;
}
}
else {
_log.error << "Radius of wheel of type: " << Type.get_name ()
<< " is less than or equal to zero: " << Radius << endl;
}
}
return result;
}
void
dmz::EntityPluginWheels::_init (Config &local) {
_defaultAttr = _defs.create_named_handle (ObjectAttributeDefaultName);
activate_default_object_attribute (ObjectCreateMask | ObjectDestroyMask);
}
//! \endcond
extern "C" {
DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin *
create_dmzEntityPluginWheels (
const dmz::PluginInfo &Info,
dmz::Config &local,
dmz::Config &global) {
return new dmz::EntityPluginWheels (Info, local);
}
};
| 22.82392 | 85 | 0.604658 |
f11edf0045a11ad72e3bb5d8fd84b19f5e9060ea | 977 | cpp | C++ | Engine/src/Traceability/Logger.cpp | LinMAD/Nibble | 65a8d12810335d832512812740f86bd8df14feb0 | [
"MIT"
] | null | null | null | Engine/src/Traceability/Logger.cpp | LinMAD/Nibble | 65a8d12810335d832512812740f86bd8df14feb0 | [
"MIT"
] | null | null | null | Engine/src/Traceability/Logger.cpp | LinMAD/Nibble | 65a8d12810335d832512812740f86bd8df14feb0 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Logger.h"
#include "spdlog/sinks/stdout_color_sinks.h"
namespace Nibble {
std::shared_ptr<spdlog::logger> Logger::s_CoreLogger;
std::shared_ptr<spdlog::logger> Logger::s_ClientLogger;
Logger::Logger()
{
}
Logger::~Logger()
{
}
void Logger::Init()
{
// https://github.com/gabime/spdlog/wiki/3.-Custom-formatting
// %^ - Start color range (can be used only once)
// %$ - End color range (for example %^[+++]%$ %v) (can be used only once)
// %T - ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S
// %l - The log level of the message
// %v - The actual text to log ("debug", "info", etc)
spdlog::set_pattern("%^[%l]|%T| %n: %v");
s_CoreLogger = spdlog::stdout_color_mt("Nibble");
s_ClientLogger = spdlog::stdout_color_mt("Application");
// TODO Add log level config loading
s_CoreLogger->set_level(spdlog::level::trace);
s_ClientLogger->set_level(spdlog::level::trace);
}
} | 28.735294 | 77 | 0.64176 |
f121c81e2a556a26ce7c1dbda509bdc8ae36dcc9 | 1,344 | hpp | C++ | src/sensors/interface.hpp | Hyp-ed/hyped-2022 | 9cac4632b660f569629cf0ad4048787f6017905d | [
"Apache-2.0"
] | 9 | 2021-07-31T16:22:24.000Z | 2022-01-19T18:14:31.000Z | src/sensors/interface.hpp | Hyp-ed/hyped-2022 | 9cac4632b660f569629cf0ad4048787f6017905d | [
"Apache-2.0"
] | 91 | 2021-07-29T18:21:30.000Z | 2022-03-31T20:44:55.000Z | src/sensors/interface.hpp | Hyp-ed/hyped-2022 | 9cac4632b660f569629cf0ad4048787f6017905d | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <string>
#include <data/data.hpp>
namespace hyped {
using data::BatteryData;
using data::ImuData;
using data::NavigationVector;
using data::StripeCounter;
using data::TemperatureData;
namespace sensors {
class SensorInterface {
public:
/**
* @brief Check if sensor is responding, i.e. connected to the system
* @return true - if sensor is online
*/
virtual bool isOnline() = 0;
};
class ImuInterface : public SensorInterface {
public:
/**
* @brief Get IMU data
* @param imu - output pointer to be filled by this sensor
*/
virtual void getData(ImuData *imu) = 0;
};
class GpioInterface : public SensorInterface {
public:
/**
* @brief Get GPIO data
* @param stripe_counter - output pointer
*/
virtual void getData(StripeCounter *stripe_counter) = 0;
};
class BMSInterface : public SensorInterface {
public:
/**
* @brief Get Battery data
* @param battery - output pointer to be filled by this sensor
*/
virtual void getData(BatteryData *battery) = 0;
};
class TemperatureInterface {
public:
/**
* @brief not a thread, checks temperature
*/
virtual void run() = 0;
/**
* @brief returns int representation of temperature
* @return int temperature degrees C
*/
virtual int getData() = 0;
};
} // namespace sensors
} // namespace hyped
| 19.764706 | 71 | 0.680804 |
f1221f59c63a06cf4df50f1e2769796ba5ba222c | 332 | cpp | C++ | Plugins/InstancedPlugin/Source/InstancedPlugin/Private/Components/Operations/IPOperationAlignBase.cpp | redcatbox/Instanced | 347790e8ade0c6e6fb9b742afc78c764414ed36a | [
"MIT"
] | 1 | 2022-02-03T17:10:29.000Z | 2022-02-03T17:10:29.000Z | Plugins/InstancedPlugin/Source/InstancedPlugin/Private/Components/Operations/IPOperationAlignBase.cpp | redcatbox/Instanced | 347790e8ade0c6e6fb9b742afc78c764414ed36a | [
"MIT"
] | null | null | null | Plugins/InstancedPlugin/Source/InstancedPlugin/Private/Components/Operations/IPOperationAlignBase.cpp | redcatbox/Instanced | 347790e8ade0c6e6fb9b742afc78c764414ed36a | [
"MIT"
] | null | null | null | // redbox, 2021
#include "Components/Operations/IPOperationAlignBase.h"
UIPOperationAlignBase::UIPOperationAlignBase()
{
#if WITH_EDITORONLY_DATA
bInstancesNumEditCondition = false;
bAlignToSurface = false;
OffsetInTraceDirection = 0.f;
bReverse = false;
bTraceComplex = false;
bIgnoreSelf = true;
DrawTime = 5.f;
#endif
}
| 19.529412 | 55 | 0.777108 |
f1226e2ec401b0be3b8b0af702bb3de980341b25 | 725 | cpp | C++ | dmoj/dmopc/2014/contest-2/deforestation.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-07-16T01:46:38.000Z | 2020-07-16T01:46:38.000Z | dmoj/dmopc/2014/contest-2/deforestation.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | null | null | null | dmoj/dmopc/2014/contest-2/deforestation.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-05-27T14:30:43.000Z | 2020-05-27T14:30:43.000Z | #include <iostream>
#include <vector>
using namespace std;
inline void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
int main()
{
use_io_optimizations();
unsigned int trees;
cin >> trees;
vector<unsigned int> prefix_sums(trees + 1);
for (unsigned int i {1}; i <= trees; ++i)
{
unsigned int mass;
cin >> mass;
prefix_sums[i] = prefix_sums[i - 1] + mass;
}
unsigned int queries;
cin >> queries;
for (unsigned int i {0}; i < queries; ++i)
{
unsigned int from;
unsigned int to;
cin >> from >> to;
cout << prefix_sums[to + 1] - prefix_sums[from] << '\n';
}
return 0;
}
| 16.477273 | 64 | 0.56 |
f124100905a0dd50b377e341d084a768cc278f82 | 1,151 | cpp | C++ | cref/10_enums.cpp | admantium-sg/learning-cpp | cc827a8d7eabceac32069bb7f5a64b3c0fe488f4 | [
"BSD-3-Clause"
] | null | null | null | cref/10_enums.cpp | admantium-sg/learning-cpp | cc827a8d7eabceac32069bb7f5a64b3c0fe488f4 | [
"BSD-3-Clause"
] | null | null | null | cref/10_enums.cpp | admantium-sg/learning-cpp | cc827a8d7eabceac32069bb7f5a64b3c0fe488f4 | [
"BSD-3-Clause"
] | null | null | null | /*
* ---------------------------------------
* Copyright (c) Sebastian Günther 2021 |
* |
* devcon@admantium.com |
* |
* SPDX-License-Identifier: BSD-3-Clause |
* ---------------------------------------
*/
#include <stdio.h>
#include <stdexcept>
#include <iostream>
#include <cstddef>
using namespace std;
enum class Color {
Red,
Blue,
Green
};
class ColorFactory{
public:
static int getInstances() { return instances;}
static Color makeColor(Color c) { ColorFactory::instances++; return c;}
static int instances;
};
int ColorFactory::instances = 0;
int main(int argc, char* argv[]) {
cout << "Number of args: " << argc << endl;
for (int i=0; i < argc; i++) {
cout << "Arg " << i << ": " << argv[i] << endl;
}
ColorFactory paint;
Color r = paint.makeColor(Color::Red);
Color g = paint.makeColor(Color::Green);
cout << "Number of paints " << ColorFactory::getInstances() << endl;
if (r == Color::Red) {cout << "Beautifull Red" << endl;}
// if (r == 0) {cout << "Beautifull Red";} //throws error
} | 24.489362 | 75 | 0.519548 |
f12445216f388fed4e59651814fdd8bac1bae6e2 | 3,016 | cpp | C++ | src/fuel.cpp | BonJovi1/Bullet-the-Blue-Sky | 9ebf41fc85ccf9f8e2880acdafc6dfffd8a0268f | [
"WTFPL"
] | null | null | null | src/fuel.cpp | BonJovi1/Bullet-the-Blue-Sky | 9ebf41fc85ccf9f8e2880acdafc6dfffd8a0268f | [
"WTFPL"
] | null | null | null | src/fuel.cpp | BonJovi1/Bullet-the-Blue-Sky | 9ebf41fc85ccf9f8e2880acdafc6dfffd8a0268f | [
"WTFPL"
] | null | null | null | #include "ball.h"
#include "main.h"
Fuel::Fuel(float x, float y, float z, color_t color) {
this->position = glm::vec3(x, y, z);
this->rotation = 0;
this->kill = 0;
this->fuel_box.height = 15;
this->fuel_box.width = 15;
this->fuel_box.depth = 15;
this->fuel_box.x = x;
this->fuel_box.y = y;
this->fuel_box.z = z;
// speed = 1;
// Our vertices. Three consecutive floats give a 3D vertex; Three consecutive vertices give a triangle.
// A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices
static const GLfloat vertex_buffer_data_sq[] = {
-15.0f,-15.0f,-15.0f, // triangle 1 : begin
-15.0f,-15.0f, 15.0f,
-15.0f, 15.0f, 15.0f, // triangle 1 : end
15.0f, 15.0f,-15.0f, // triangle 2 : begin
-15.0f,-15.0f,-15.0f,
-15.0f, 15.0f,-15.0f, // triangle 2 : end
15.0f,-15.0f, 15.0f,
-15.0f,-15.0f,-15.0f,
15.0f,-15.0f,-15.0f,
15.0f, 15.0f,-15.0f,
15.0f,-15.0f,-15.0f,
-15.0f,-15.0f,-15.0f,
-15.0f,-15.0f,-15.0f,
-15.0f, 15.0f, 15.0f,
-15.0f, 15.0f,-15.0f,
15.0f,-15.0f, 15.0f,
-15.0f,-15.0f, 15.0f,
-15.0f,-15.0f,-15.0f,
-15.0f, 15.0f, 15.0f,
-15.0f,-15.0f, 15.0f,
15.0f,-15.0f, 15.0f,
15.0f, 15.0f, 15.0f,
15.0f,-15.0f,-15.0f,
15.0f, 15.0f,-15.0f,
15.0f,-15.0f,-15.0f,
15.0f, 15.0f, 15.0f,
15.0f,-15.0f, 15.0f,
15.0f, 15.0f, 15.0f,
15.0f, 15.0f,-15.0f,
-15.0f, 15.0f,-15.0f,
15.0f, 15.0f, 15.0f,
-15.0f, 15.0f,-15.0f,
-15.0f, 15.0f, 15.0f,
15.0f, 15.0f, 15.0f,
-15.0f, 15.0f, 15.0f,
15.0f,-15.0f, 15.0f
};
// Our vertices. Three consecutive floats give a 3D vertex; Three consecutive vertices give a triangle.
// A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices
this->object = create3DObject(GL_TRIANGLES, 12*3, vertex_buffer_data_sq, color, GL_FILL);
}
void Fuel::draw(glm::mat4 VP) {
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position); // glTranslatef
glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(1, 0, 0));
// No need as coords centered at 0, 0, 0 of cube arouund which we waant to rotate
// rotate = rotate * glm::translate(glm::vec3(0, -0.6, 0));
Matrices.model *= (translate * rotate);
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->object);
}
void Fuel::set_position(float x, float y) {
this->position = glm::vec3(x, y, 0);
}
void Fuel::tick() {
// this->rotation += speed;
// this->position.x -= speed;
this->position.y -= 0.6;
this->fuel_box.x = this->position.x;
this->fuel_box.y = this->position.y;
this->fuel_box.z = this->position.z;
} | 34.272727 | 107 | 0.556698 |
f1292ef8610d84e7d6c789af02652b45f680a893 | 573 | cpp | C++ | 1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp | arpangoswami/LeetcodeSolutions | 17a2450cacf0020c2626023012a5a354c8fee5da | [
"MIT"
] | null | null | null | 1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp | arpangoswami/LeetcodeSolutions | 17a2450cacf0020c2626023012a5a354c8fee5da | [
"MIT"
] | null | null | null | 1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp | arpangoswami/LeetcodeSolutions | 17a2450cacf0020c2626023012a5a354c8fee5da | [
"MIT"
] | null | null | null | class Solution {
public:
int longestSubarray(vector<int>& nums, int limit) {
int left = 0;
int n = nums.size();
multiset<int> windowElements;
int ans = 1;
for(int i=0;i<n;i++){
windowElements.insert(nums[i]);
while(left <= i && (*windowElements.rbegin() - *windowElements.begin()) > limit){
auto it = windowElements.find(nums[left]);
windowElements.erase(it);
left++;
}
ans = max(ans,i-left+1);
}
return ans;
}
}; | 30.157895 | 93 | 0.490401 |
f12ad4de9a7ae79ebaa583594bdcce5ade49214d | 10,437 | cc | C++ | hookflash-core/webRTC/webRTC_ios/src/modules/video_coding/codecs/test/videoprocessor.cc | ilin-in/OP | bf3e87d90008e2a4106ee70360fbe15b0d694e77 | [
"Unlicense"
] | 1 | 2020-02-19T09:55:55.000Z | 2020-02-19T09:55:55.000Z | hookflash-core/webRTC/webRTC_ios/src/modules/video_coding/codecs/test/videoprocessor.cc | ilin-in/OP | bf3e87d90008e2a4106ee70360fbe15b0d694e77 | [
"Unlicense"
] | null | null | null | hookflash-core/webRTC/webRTC_ios/src/modules/video_coding/codecs/test/videoprocessor.cc | ilin-in/OP | bf3e87d90008e2a4106ee70360fbe15b0d694e77 | [
"Unlicense"
] | null | null | null | /*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/video_coding/codecs/test/videoprocessor.h"
#include <cassert>
#include <cstring>
#include <limits>
#include "system_wrappers/interface/cpu_info.h"
namespace webrtc {
namespace test {
VideoProcessorImpl::VideoProcessorImpl(webrtc::VideoEncoder* encoder,
webrtc::VideoDecoder* decoder,
FrameReader* frame_reader,
FrameWriter* frame_writer,
PacketManipulator* packet_manipulator,
const TestConfig& config,
Stats* stats)
: encoder_(encoder),
decoder_(decoder),
frame_reader_(frame_reader),
frame_writer_(frame_writer),
packet_manipulator_(packet_manipulator),
config_(config),
stats_(stats),
encode_callback_(NULL),
decode_callback_(NULL),
source_buffer_(NULL),
first_key_frame_has_been_excluded_(false),
last_frame_missing_(false),
initialized_(false) {
assert(encoder);
assert(decoder);
assert(frame_reader);
assert(frame_writer);
assert(packet_manipulator);
assert(stats);
}
bool VideoProcessorImpl::Init() {
// Calculate a factor used for bit rate calculations:
bit_rate_factor_ = config_.codec_settings->maxFramerate * 0.001 * 8; // bits
int frame_length_in_bytes = frame_reader_->FrameLength();
// Initialize data structures used by the encoder/decoder APIs
source_buffer_ = new WebRtc_UWord8[frame_length_in_bytes];
last_successful_frame_buffer_ = new WebRtc_UWord8[frame_length_in_bytes];
// Set fixed properties common for all frames:
source_frame_._width = config_.codec_settings->width;
source_frame_._height = config_.codec_settings->height;
source_frame_._length = frame_length_in_bytes;
source_frame_._size = frame_length_in_bytes;
// Setup required callbacks for the encoder/decoder:
encode_callback_ = new VideoProcessorEncodeCompleteCallback(this);
decode_callback_ = new VideoProcessorDecodeCompleteCallback(this);
WebRtc_Word32 register_result =
encoder_->RegisterEncodeCompleteCallback(encode_callback_);
if (register_result != WEBRTC_VIDEO_CODEC_OK) {
fprintf(stderr, "Failed to register encode complete callback, return code: "
"%d\n", register_result);
return false;
}
register_result = decoder_->RegisterDecodeCompleteCallback(decode_callback_);
if (register_result != WEBRTC_VIDEO_CODEC_OK) {
fprintf(stderr, "Failed to register decode complete callback, return code: "
"%d\n", register_result);
return false;
}
// Init the encoder and decoder
WebRtc_UWord32 nbr_of_cores = 1;
if (!config_.use_single_core) {
nbr_of_cores = CpuInfo::DetectNumberOfCores();
}
WebRtc_Word32 init_result =
encoder_->InitEncode(config_.codec_settings, nbr_of_cores,
config_.networking_config.max_payload_size_in_bytes);
if (init_result != WEBRTC_VIDEO_CODEC_OK) {
fprintf(stderr, "Failed to initialize VideoEncoder, return code: %d\n",
init_result);
return false;
}
init_result = decoder_->InitDecode(config_.codec_settings, nbr_of_cores);
if (init_result != WEBRTC_VIDEO_CODEC_OK) {
fprintf(stderr, "Failed to initialize VideoDecoder, return code: %d\n",
init_result);
return false;
}
if (config_.verbose) {
printf("Video Processor:\n");
printf(" #CPU cores used : %d\n", nbr_of_cores);
printf(" Total # of frames: %d\n", frame_reader_->NumberOfFrames());
printf(" Codec settings:\n");
printf(" Start bitrate : %d kbps\n",
config_.codec_settings->startBitrate);
printf(" Width : %d\n", config_.codec_settings->width);
printf(" Height : %d\n", config_.codec_settings->height);
}
initialized_ = true;
return true;
}
VideoProcessorImpl::~VideoProcessorImpl() {
delete[] source_buffer_;
delete[] last_successful_frame_buffer_;
encoder_->RegisterEncodeCompleteCallback(NULL);
delete encode_callback_;
decoder_->RegisterDecodeCompleteCallback(NULL);
delete decode_callback_;
}
bool VideoProcessorImpl::ProcessFrame(int frame_number) {
assert(frame_number >=0);
if (!initialized_) {
fprintf(stderr, "Attempting to use uninitialized VideoProcessor!\n");
return false;
}
if (frame_reader_->ReadFrame(source_buffer_)) {
// point the source frame buffer to the newly read frame data:
source_frame_._buffer = source_buffer_;
// Ensure we have a new statistics data object we can fill:
FrameStatistic& stat = stats_->NewFrame(frame_number);
encode_start_ = TickTime::Now();
// Use the frame number as "timestamp" to identify frames
source_frame_._timeStamp = frame_number;
// Decide if we're going to force a keyframe:
VideoFrameType frame_type = kDeltaFrame;
if (config_.keyframe_interval > 0 &&
frame_number % config_.keyframe_interval == 0) {
frame_type = kKeyFrame;
}
WebRtc_Word32 encode_result = encoder_->Encode(source_frame_, NULL,
frame_type);
if (encode_result != WEBRTC_VIDEO_CODEC_OK) {
fprintf(stderr, "Failed to encode frame %d, return code: %d\n",
frame_number, encode_result);
}
stat.encode_return_code = encode_result;
return true;
} else {
return false; // we've reached the last frame
}
}
void VideoProcessorImpl::FrameEncoded(EncodedImage* encoded_image) {
TickTime encode_stop = TickTime::Now();
int frame_number = encoded_image->_timeStamp;
FrameStatistic& stat = stats_->stats_[frame_number];
stat.encode_time_in_us = GetElapsedTimeMicroseconds(encode_start_,
encode_stop);
stat.encoding_successful = true;
stat.encoded_frame_length_in_bytes = encoded_image->_length;
stat.frame_number = encoded_image->_timeStamp;
stat.frame_type = encoded_image->_frameType;
stat.bit_rate_in_kbps = encoded_image->_length * bit_rate_factor_;
stat.total_packets = encoded_image->_length /
config_.networking_config.packet_size_in_bytes + 1;
// Perform packet loss if criteria is fullfilled:
bool exclude_this_frame = false;
// Only keyframes can be excluded
if (encoded_image->_frameType == kKeyFrame) {
switch (config_.exclude_frame_types) {
case kExcludeOnlyFirstKeyFrame:
if (!first_key_frame_has_been_excluded_) {
first_key_frame_has_been_excluded_ = true;
exclude_this_frame = true;
}
break;
case kExcludeAllKeyFrames:
exclude_this_frame = true;
break;
default:
assert(false);
}
}
if (!exclude_this_frame) {
stat.packets_dropped =
packet_manipulator_->ManipulatePackets(encoded_image);
}
// Keep track of if frames are lost due to packet loss so we can tell
// this to the encoder (this is handled by the RTP logic in the full stack)
decode_start_ = TickTime::Now();
// TODO(kjellander): Pass fragmentation header to the decoder when
// CL 172001 has been submitted and PacketManipulator supports this.
WebRtc_Word32 decode_result = decoder_->Decode(*encoded_image,
last_frame_missing_, NULL);
stat.decode_return_code = decode_result;
if (decode_result != WEBRTC_VIDEO_CODEC_OK) {
// Write the last successful frame the output file to avoid getting it out
// of sync with the source file for SSIM and PSNR comparisons:
frame_writer_->WriteFrame(last_successful_frame_buffer_);
}
// save status for losses so we can inform the decoder for the next frame:
last_frame_missing_ = encoded_image->_length == 0;
}
void VideoProcessorImpl::FrameDecoded(const RawImage& image) {
TickTime decode_stop = TickTime::Now();
int frame_number = image._timeStamp;
// Report stats
FrameStatistic& stat = stats_->stats_[frame_number];
stat.decode_time_in_us = GetElapsedTimeMicroseconds(decode_start_,
decode_stop);
stat.decoding_successful = true;
// Update our copy of the last successful frame:
memcpy(last_successful_frame_buffer_, image._buffer, image._length);
bool write_success = frame_writer_->WriteFrame(image._buffer);
if (!write_success) {
fprintf(stderr, "Failed to write frame %d to disk!", frame_number);
}
}
int VideoProcessorImpl::GetElapsedTimeMicroseconds(
const webrtc::TickTime& start, const webrtc::TickTime& stop) {
WebRtc_UWord64 encode_time = (stop - start).Microseconds();
assert(encode_time <
static_cast<unsigned int>(std::numeric_limits<int>::max()));
return static_cast<int>(encode_time);
}
const char* ExcludeFrameTypesToStr(ExcludeFrameTypes e) {
switch (e) {
case kExcludeOnlyFirstKeyFrame:
return "ExcludeOnlyFirstKeyFrame";
case kExcludeAllKeyFrames:
return "ExcludeAllKeyFrames";
default:
assert(false);
return "Unknown";
}
}
const char* VideoCodecTypeToStr(webrtc::VideoCodecType e) {
switch (e) {
case kVideoCodecVP8:
return "VP8";
case kVideoCodecI420:
return "I420";
case kVideoCodecRED:
return "RED";
case kVideoCodecULPFEC:
return "ULPFEC";
case kVideoCodecUnknown:
return "Unknown";
default:
assert(false);
return "Unknown";
}
}
// Callbacks
WebRtc_Word32
VideoProcessorImpl::VideoProcessorEncodeCompleteCallback::Encoded(
EncodedImage& encoded_image,
const webrtc::CodecSpecificInfo* codec_specific_info,
const webrtc::RTPFragmentationHeader* fragmentation) {
video_processor_->FrameEncoded(&encoded_image); // forward to parent class
return 0;
}
WebRtc_Word32
VideoProcessorImpl::VideoProcessorDecodeCompleteCallback::Decoded(
RawImage& image) {
video_processor_->FrameDecoded(image); // forward to parent class
return 0;
}
} // namespace test
} // namespace webrtc
| 36.239583 | 80 | 0.696465 |
f12b3726fca9bd6e160b866808b266980538cc88 | 3,681 | cpp | C++ | Source/Framework/Core/GameComponentContainer.cpp | gabr1e11/cornerstone | bc696e22af350b867219ef3ac99840b3e8a3f20a | [
"MIT"
] | null | null | null | Source/Framework/Core/GameComponentContainer.cpp | gabr1e11/cornerstone | bc696e22af350b867219ef3ac99840b3e8a3f20a | [
"MIT"
] | null | null | null | Source/Framework/Core/GameComponentContainer.cpp | gabr1e11/cornerstone | bc696e22af350b867219ef3ac99840b3e8a3f20a | [
"MIT"
] | null | null | null | //
// GameComponentContainer.cpp
//
// @author Roberto Cano
//
#include "GameComponentContainer.hpp"
using namespace Framework;
using namespace Framework::Core;
using namespace Framework::Types;
void GameComponentContainer::addComponent(Types::GameComponent::PtrType component)
{
const ComponentId& componentId = component->getComponentId();
const InstanceId& instanceId = component->getInstanceId();
_notStartedComponents.push(component);
// Dependency injection
Types::GameObject::PtrType gameObjectPtr = shared_from_this();
component->_setOwner(gameObjectPtr);
// Map by Instance Id
auto insertionIter = _componentsMapByInstanceId.insert(std::pair<InstanceId, Types::GameComponent::PtrType>(instanceId, std::move(component)));
assert(insertionIter.second);
// Map by Component Id
auto componentsMapIter = _componentsMapByComponentId.find(componentId);
if (componentsMapIter != _componentsMapByComponentId.end())
{
componentsMapIter->second.emplace(instanceId);
}
else
{
_componentsMapByComponentId.emplace(componentId, std::set<InstanceId>{instanceId});
}
}
bool GameComponentContainer::removeComponent(const Core::GameComponent& component)
{
const InstanceId& instanceId = component.getInstanceId();
return removeComponent(instanceId);
}
bool GameComponentContainer::removeComponent(const InstanceId& instanceId)
{
bool retValue = true;
auto findIter = _componentsMapByInstanceId.find(instanceId);
if (findIter == _componentsMapByInstanceId.end())
{
return false;
}
const GameComponent& component = *(findIter->second);
const ComponentId& componentId = component.getComponentId();
// Map by Component Id
auto componentsMapIter = _componentsMapByComponentId.find(componentId);
if (componentsMapIter != _componentsMapByComponentId.end())
{
componentsMapIter->second.erase(instanceId);
}
else
{
retValue = false;
}
// Map by Instance Id
_componentsMapByInstanceId.erase(findIter);
return retValue;
}
bool GameComponentContainer::hasComponent(const Core::GameComponent& component) const
{
const InstanceId& instanceId = component.getInstanceId();
return hasComponent(instanceId);
}
bool GameComponentContainer::hasComponents(const ComponentId& componentId) const
{
auto componentsMapIter = _componentsMapByComponentId.find(componentId);
return componentsMapIter != _componentsMapByComponentId.end();
}
bool GameComponentContainer::hasComponent(const InstanceId& instanceId) const
{
auto instancesMapIter = _componentsMapByInstanceId.find(instanceId);
return instancesMapIter != _componentsMapByInstanceId.end();
}
const std::set<InstanceId>& GameComponentContainer::getComponentsIds(const ComponentId& componentId) const
{
auto componentsMapIter = _componentsMapByComponentId.find(componentId);
assert(componentsMapIter != _componentsMapByComponentId.end());
return componentsMapIter->second;
}
void GameComponentContainer::internalInit()
{
for (auto& componentPair : _componentsMapByInstanceId)
{
componentPair.second->init();
}
}
void GameComponentContainer::internalStart()
{
for (auto& componentPair : _componentsMapByInstanceId)
{
componentPair.second->start();
}
}
void GameComponentContainer::internalUpdate(float dt)
{
for (auto& componentPair : _componentsMapByInstanceId)
{
componentPair.second->update(dt);
}
}
void GameComponentContainer::updateNotStarted()
{
if (_notStartedComponents.empty())
{
return;
}
while (!_notStartedComponents.empty())
{
Types::GameComponent::WeakPtrType gameComponentWPtr = _notStartedComponents.front();
_notStartedComponents.pop();
if (auto gameComponent = gameComponentWPtr.lock())
{
gameComponent->internalStart();
}
}
} | 25.741259 | 144 | 0.784569 |
f12d0977ce64856eef91ed814818316579c52041 | 1,013 | cpp | C++ | code/baseline-system/src/sensors/sensor_random.cpp | jo-jstrm/rime-data-streaming-iot | 8caf549868c6f5ebacb201cb21be9ae5b641ee0b | [
"MIT"
] | null | null | null | code/baseline-system/src/sensors/sensor_random.cpp | jo-jstrm/rime-data-streaming-iot | 8caf549868c6f5ebacb201cb21be9ae5b641ee0b | [
"MIT"
] | 1 | 2021-08-16T09:19:17.000Z | 2021-08-16T09:19:17.000Z | code/baseline-system/src/sensors/sensor_random.cpp | jo-jstrm/rime-data-streaming-iot | 8caf549868c6f5ebacb201cb21be9ae5b641ee0b | [
"MIT"
] | null | null | null | #include "sensor_random.hpp"
#include <random>
#include <chrono>
#include <utility>
#include "results.hpp"
using namespace caf;
using namespace std;
using namespace std::chrono;
using read = atom_constant<atom("read")>;
using state = atom_constant<atom("state")>;
behavior random_sensor(stateful_actor<sensor_state>* self, string name) {
self->state.name = name;
return {
// RETURN: (string sensor_name, double sensor reading)
[=](read) {
double sensor_reading;
system_clock::time_point begin = system_clock::now();
system_clock::duration dur;
mt19937 gen;
uniform_real_distribution<double> dist(0, 100);
//seed the generator
dur = system_clock::now() - begin;
gen.seed(dur.count());
sensor_reading = dist(gen);
return value(sensor_reading);
},
/*-------------------------------Testing------------------------------*/
[=](state) {
return self->state.name;
}
};
} | 24.707317 | 76 | 0.586377 |
f132ed9ead1956efad145f4b362f7737812a27b8 | 6,264 | cpp | C++ | qttools/src/assistant/3rdparty/clucene/src/CLucene/index/FieldInfos.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qttools/src/assistant/3rdparty/clucene/src/CLucene/index/FieldInfos.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qttools/src/assistant/3rdparty/clucene/src/CLucene/index/FieldInfos.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team
*
* Distributable under the terms of either the Apache License (Version 2.0) or
* the GNU Lesser General Public License, as specified in the COPYING file.
*
* Changes are Copyright (C) 2015 The Qt Company Ltd.
*/
#include "CLucene/StdHeader.h"
#include "FieldInfos.h"
#include "CLucene/store/Directory.h"
#include "CLucene/document/Document.h"
#include "CLucene/document/Field.h"
#include "CLucene/util/VoidMap.h"
#include "CLucene/util/Misc.h"
#include "CLucene/util/StringIntern.h"
CL_NS_USE(store)
CL_NS_USE(document)
CL_NS_USE(util)
CL_NS_DEF(index)
FieldInfo::FieldInfo(const TCHAR* _fieldName, bool _isIndexed,
int32_t _fieldNumber, bool _storeTermVector, bool _storeOffsetWithTermVector,
bool _storePositionWithTermVector, bool _omitNorms)
: name(CLStringIntern::intern(_fieldName CL_FILELINE))
, isIndexed(_isIndexed)
, number(_fieldNumber)
, storeTermVector(_storeTermVector)
, storeOffsetWithTermVector(_storeOffsetWithTermVector)
, storePositionWithTermVector(_storeTermVector)
, omitNorms(_omitNorms)
{
}
FieldInfo::~FieldInfo()
{
CL_NS(util)::CLStringIntern::unintern(name);
}
// #pragma mark -- FieldInfos
FieldInfos::FieldInfos()
: byName(false, false)
, byNumber(true)
{
}
FieldInfos::~FieldInfos()
{
byName.clear();
byNumber.clear();
}
FieldInfos::FieldInfos(Directory* d, const QString& name)
: byName(false, false)
, byNumber(true)
{
IndexInput* input = d->openInput(name);
try {
read(input);
} _CLFINALLY (
input->close();
_CLDELETE(input);
);
}
void FieldInfos::add(const Document* doc)
{
DocumentFieldEnumeration* fields = doc->fields();
Field* field;
while (fields->hasMoreElements()) {
field = fields->nextElement();
add(field->name(), field->isIndexed(), field->isTermVectorStored());
}
_CLDELETE(fields);
}
void FieldInfos::add(const TCHAR* name, bool isIndexed, bool storeTermVector,
bool storePositionWithTermVector, bool storeOffsetWithTermVector, bool omitNorms)
{
FieldInfo* fi = fieldInfo(name);
if (fi == NULL) {
addInternal(name, isIndexed, storeTermVector,
storePositionWithTermVector,
storeOffsetWithTermVector, omitNorms);
} else {
if (fi->isIndexed != isIndexed) {
// once indexed, always index
fi->isIndexed = true;
}
if (fi->storeTermVector != storeTermVector) {
// once vector, always vector
fi->storeTermVector = true;
}
if (fi->storePositionWithTermVector != storePositionWithTermVector) {
// once vector, always vector
fi->storePositionWithTermVector = true;
}
if (fi->storeOffsetWithTermVector != storeOffsetWithTermVector) {
// once vector, always vector
fi->storeOffsetWithTermVector = true;
}
if (fi->omitNorms != omitNorms) {
// once norms are stored, always store
fi->omitNorms = false;
}
}
}
void FieldInfos::add(const TCHAR** names, bool isIndexed, bool storeTermVectors,
bool storePositionWithTermVector, bool storeOffsetWithTermVector, bool omitNorms)
{
int32_t i=0;
while (names[i] != NULL) {
add(names[i], isIndexed, storeTermVectors, storePositionWithTermVector,
storeOffsetWithTermVector, omitNorms);
++i;
}
}
int32_t FieldInfos::fieldNumber(const TCHAR* fieldName) const
{
FieldInfo* fi = fieldInfo(fieldName);
return (fi != NULL) ? fi->number : -1;
}
FieldInfo* FieldInfos::fieldInfo(const TCHAR* fieldName) const
{
return byName.get(fieldName);
}
const TCHAR* FieldInfos::fieldName(const int32_t fieldNumber) const
{
FieldInfo* fi = fieldInfo(fieldNumber);
return (fi == NULL) ? LUCENE_BLANK_STRING : fi->name;
}
FieldInfo* FieldInfos::fieldInfo(const int32_t fieldNumber) const
{
if (fieldNumber < 0 || (size_t)fieldNumber >= byNumber.size())
return NULL;
return byNumber[fieldNumber];
}
int32_t FieldInfos::size() const
{
return byNumber.size();
}
void FieldInfos::write(Directory* d, const QString& name) const
{
IndexOutput* output = d->createOutput(name);
try {
write(output);
} _CLFINALLY (
output->close();
_CLDELETE(output);
);
}
void FieldInfos::write(IndexOutput* output) const
{
output->writeVInt(size());
FieldInfo* fi;
uint8_t bits;
for (int32_t i = 0; i < size(); ++i) {
fi = fieldInfo(i);
bits = 0x0;
if (fi->isIndexed)
bits |= IS_INDEXED;
if (fi->storeTermVector)
bits |= STORE_TERMVECTOR;
if (fi->storePositionWithTermVector)
bits |= STORE_POSITIONS_WITH_TERMVECTOR;
if (fi->storeOffsetWithTermVector)
bits |= STORE_OFFSET_WITH_TERMVECTOR;
if (fi->omitNorms)
bits |= OMIT_NORMS;
output->writeString(fi->name, _tcslen(fi->name));
output->writeByte(bits);
}
}
void FieldInfos::read(IndexInput* input)
{
int32_t size = input->readVInt();
for (int32_t i = 0; i < size; ++i) {
// we could read name into a string buffer, but we can't be sure what
// the maximum field length will be.
TCHAR* name = input->readString();
uint8_t bits = input->readByte();
bool isIndexed = (bits & IS_INDEXED) != 0;
bool storeTermVector = (bits & STORE_TERMVECTOR) != 0;
bool storePositionsWithTermVector =
(bits & STORE_POSITIONS_WITH_TERMVECTOR) != 0;
bool storeOffsetWithTermVector = (bits & STORE_OFFSET_WITH_TERMVECTOR) != 0;
bool omitNorms = (bits & OMIT_NORMS) != 0;
addInternal(name, isIndexed, storeTermVector,
storePositionsWithTermVector, storeOffsetWithTermVector, omitNorms);
_CLDELETE_CARRAY(name);
}
}
void FieldInfos::addInternal(const TCHAR* name, bool isIndexed,
bool storeTermVector, bool storePositionWithTermVector,
bool storeOffsetWithTermVector, bool omitNorms)
{
FieldInfo* fi = _CLNEW FieldInfo(name, isIndexed, byNumber.size(),
storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector,
omitNorms);
byNumber.push_back(fi);
byName.put(fi->name, fi);
}
bool FieldInfos::hasVectors() const
{
for (int32_t i = 0; i < size(); i++) {
if (fieldInfo(i)->storeTermVector)
return true;
}
return false;
}
CL_NS_END
| 26.43038 | 85 | 0.685983 |
f133409731a3a8155fbf3128a4b1e316847324c6 | 240 | cpp | C++ | src/trap_instances/SegmentLdr.cpp | DavidLudwig/executor | eddb527850af639b3ffe314e05d92a083ba47af6 | [
"MIT"
] | 2 | 2019-09-16T15:51:39.000Z | 2020-03-04T08:47:42.000Z | src/trap_instances/SegmentLdr.cpp | probonopd/executor | 0fb82c09109ec27ae8707f07690f7325ee0f98e0 | [
"MIT"
] | null | null | null | src/trap_instances/SegmentLdr.cpp | probonopd/executor | 0fb82c09109ec27ae8707f07690f7325ee0f98e0 | [
"MIT"
] | null | null | null | #define INSTANTIATE_TRAPS_SegmentLdr
#include <SegmentLdr.h>
// Function for preventing the linker from considering the static constructors in this module unused
namespace Executor {
namespace ReferenceTraps {
void SegmentLdr() {}
}
}
| 24 | 100 | 0.791667 |
f1368c3c646265606a2f4ca855cf81b325293b08 | 269 | cpp | C++ | cpp_algs/bst/test_new.cpp | vitalir2/AlgorithmsCpp | f9a1b7a0b51c6f122ff600008d2c0ef72a26502f | [
"MIT"
] | null | null | null | cpp_algs/bst/test_new.cpp | vitalir2/AlgorithmsCpp | f9a1b7a0b51c6f122ff600008d2c0ef72a26502f | [
"MIT"
] | null | null | null | cpp_algs/bst/test_new.cpp | vitalir2/AlgorithmsCpp | f9a1b7a0b51c6f122ff600008d2c0ef72a26502f | [
"MIT"
] | null | null | null | #include <iostream>
void f(double* n) {
n = new double(4);
}
void g(double* n) {
delete n;
}
int main() {
double* x = new double(5);
f(x);
std::cout << *x << std::endl;
g(x);
std::cout << *x << std::endl;
int* m = nullptr;
delete m;
return 0;
}
| 12.227273 | 31 | 0.520446 |
f136c9e05ffcde42149c9d9ba3a27c2ddca3539c | 774 | cpp | C++ | 2021_March/30.cpp | zzz0906/LeetCode | cd0b4a4fd03d0dff585c9ef349984eba1922ece0 | [
"MIT"
] | 17 | 2018-08-23T08:53:56.000Z | 2021-04-17T00:06:13.000Z | 2021_March/30.cpp | zzz0906/LeetCode | cd0b4a4fd03d0dff585c9ef349984eba1922ece0 | [
"MIT"
] | null | null | null | 2021_March/30.cpp | zzz0906/LeetCode | cd0b4a4fd03d0dff585c9ef349984eba1922ece0 | [
"MIT"
] | null | null | null | class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
if (envelopes.empty() || envelopes[0].size() == 0) return 0;
int res = 1, n = envelopes.size();
vector<int> dp(n,1);
sort(envelopes.begin(), envelopes.end());
for (int i = 1; i < n; i++){
for (int j = 0; j < i; ++j)
if (envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1]) {
dp[i] = max(dp[i], dp[j] + 1);
}
res = max(res,dp[i]);
}
return res;
// if (envelopes[i][0] > envelopes[i-1][0] && envelopes[i][1] > envelopes[i-1][1])
// dp[i] = dp[i-1] + 1;
// else
// dp[i] = dp[i-1];
}
}; | 36.857143 | 94 | 0.425065 |
f13712f5a4d5b34c049fdc782a7bbe51a4e909a6 | 9,958 | cpp | C++ | src/websocket/frame_websocket.cpp | hl4/da4qi4 | 9dfb8902427d40b392977b4fd706048ce3ee8828 | [
"Apache-2.0"
] | 166 | 2019-04-15T03:19:31.000Z | 2022-03-26T05:41:12.000Z | src/websocket/frame_websocket.cpp | YangKefan/da4qi4 | 9dfb8902427d40b392977b4fd706048ce3ee8828 | [
"Apache-2.0"
] | 9 | 2019-07-18T06:09:59.000Z | 2021-01-27T04:19:04.000Z | src/websocket/frame_websocket.cpp | YangKefan/da4qi4 | 9dfb8902427d40b392977b4fd706048ce3ee8828 | [
"Apache-2.0"
] | 43 | 2019-07-03T05:41:57.000Z | 2022-02-24T14:16:09.000Z | #include "daqi/websocket/frame_websocket.hpp"
#include <cstring>
namespace da4qi4
{
namespace Websocket
{
std::string FrameBuilder::Build(char const* data, size_t len)
{
std::string buffer;
size_t externded_payload_len = (len <= 125 ? 0 : (len <= 65535 ? 2 : 8));
size_t mask_key_len = ((len && _frame_header.MASK) ? 4 : 0);
auto frame_size = static_cast<size_t>(2 + externded_payload_len + mask_key_len + len);
buffer.resize(frame_size);
uint8_t* ptr = reinterpret_cast<uint8_t*>(buffer.data());
uint64_t offset = 0;
ptr[0] |= _frame_header.FIN;
ptr[0] |= _frame_header.OPCODE;
if (len)
{
ptr[1] |= _frame_header.MASK;
}
++offset;
if (len <= 125)
{
ptr[offset++] |= static_cast<unsigned char>(len);
}
else if (len <= 65535)
{
ptr[offset++] |= 126;
ptr[offset++] = static_cast<unsigned char>((len >> 8) & 0xFF);
ptr[offset++] = len & 0xFF;
}
else
{
ptr[offset++] |= 127;
ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 56) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 48) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 40) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 32) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 24) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 16) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 8) & 0xff));
ptr[offset++] = static_cast<unsigned char>((static_cast<uint64_t>(len) & 0xff));
}
if (!len || !data)
{
return buffer;
}
if (_frame_header.MASK)
{
int mask_key = static_cast<int>(_frame_header.MASKING_KEY);
ptr[offset++] = static_cast<unsigned char>(((mask_key >> 24) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((mask_key >> 16) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((mask_key >> 8) & 0xff));
ptr[offset++] = static_cast<unsigned char>(((mask_key) & 0xff));
unsigned char* mask = ptr + offset - 4;
for (uint32_t i = 0; i < len; ++i)
{
ptr[offset++] = static_cast<uint8_t>(data[i] ^ mask[i % 4]);
}
}
else
{
std::copy(data, data + len, reinterpret_cast<char*>(ptr + offset));
offset += len;
}
assert(offset == frame_size);
return buffer;
}
void FrameParser::reset()
{
_parser_step = e_fixed_header;
_masking_key_pos = 0;
_payload_len_offset = 0;
_payload.clear();
memset(&_frame_header, 0, sizeof(_frame_header));
}
void FrameParser::move_reset(FrameParser&& parser)
{
if (&parser == this)
{
return;
}
_parser_step = parser._parser_step;
_payload_len_offset = parser._payload_len_offset;
_masking_key_pos = parser._masking_key_pos;
_payload = std::move(parser._payload);
_frame_header = std::move(parser._frame_header);
_msb_cb = std::move(parser._msb_cb);
}
uint32_t FrameParser::parse_fixed_header(const char* data)
{
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
memset(&_frame_header, 0, sizeof(_frame_header));
_payload_len_offset = 0;
_frame_header.FIN = ptr[0] & 0xf0;
_frame_header.RSV1 = ptr[0] & 0x40;
_frame_header.RSV2 = ptr[0] & 0x20;
_frame_header.RSV3 = ptr[0] & 0x10;
_frame_header.OPCODE = static_cast<FrameType>(ptr[0] & 0x0f);
_parser_step = e_payload_len;
return 1U;
}
uint32_t FrameParser::parse_payload_len(const char* data)
{
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
_frame_header.MASK = ptr[0] & 0x80;
_frame_header.PAYLOAD_LEN = ptr[0] & (0x7f);
if (_frame_header.PAYLOAD_LEN <= 125)
{
_frame_header.PAYLOAD_REALY_LEN = _frame_header.PAYLOAD_LEN;
if (_frame_header.MASK)
{
_parser_step = e_masking_key;
}
else
{
_parser_step = e_payload_data;
}
}
else if (_frame_header.PAYLOAD_LEN > 125)
{
_parser_step = e_extened_payload_len;
}
if (_frame_header.PAYLOAD_LEN == 0)
{
assert(_msb_cb);
_msb_cb("", _frame_header.OPCODE, !!_frame_header.FIN);
reset();
}
return 1U;
}
uint32_t FrameParser::parse_extened_payload_len(const char* data, uint32_t len)
{
uint32_t offset = 0;
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
if (_frame_header.PAYLOAD_LEN == 126)
{
//Extended payload length is 16bit!
uint32_t min_len = std::min<uint32_t>
(2 - _payload_len_offset, len - offset);
memcpy(&_frame_header.EXT_PAYLOAD_LEN_16,
ptr + offset, min_len);
offset += min_len;
_payload_len_offset += min_len;
if (_payload_len_offset == 2)
{
decode_extened_payload_len();
}
}
else if (_frame_header.PAYLOAD_LEN == 127)
{
//Extended payload length is 64bit!
auto min_len = std::min<uint32_t>(8 - _payload_len_offset, len - offset);
memcpy(&_frame_header.EXT_PAYLOAD_LEN_64, ptr + offset, static_cast<size_t>(min_len));
offset += min_len;
_payload_len_offset += min_len;
if (_payload_len_offset == 8)
{
decode_extened_payload_len();
}
}
return offset;
}
void FrameParser::decode_extened_payload_len()
{
if (_frame_header.PAYLOAD_LEN == 126)
{
uint16_t tmp = _frame_header.EXT_PAYLOAD_LEN_16;
uint8_t* buffer_ = reinterpret_cast<uint8_t*>(&tmp);
_frame_header.PAYLOAD_REALY_LEN =
static_cast<uint64_t>(
(static_cast<uint16_t>(buffer_[0]) << 8) | static_cast<uint16_t>(buffer_[1]));
}
else if (_frame_header.PAYLOAD_LEN == 127)
{
uint64_t tmp = _frame_header.EXT_PAYLOAD_LEN_64;
uint8_t* buffer_ = reinterpret_cast<uint8_t*>(&tmp);
_frame_header.PAYLOAD_REALY_LEN =
(static_cast<uint64_t>(buffer_[0]) << 56) |
(static_cast<uint64_t>(buffer_[1]) << 48) |
(static_cast<uint64_t>(buffer_[2]) << 40) |
(static_cast<uint64_t>(buffer_[3]) << 32) |
(static_cast<uint64_t>(buffer_[4]) << 24) |
(static_cast<uint64_t>(buffer_[5]) << 16) |
(static_cast<uint64_t>(buffer_[6]) << 8) |
static_cast<uint64_t>(buffer_[7]);
}
if (_frame_header.MASK)
{
_parser_step = e_masking_key;
}
else
{
_parser_step = e_payload_data;
}
}
uint32_t FrameParser::parse_masking_key(const char* data, uint32_t len)
{
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
auto min = std::min<uint32_t>(4 - _masking_key_pos, len);
if (_parser_step == e_masking_key)
{
memcpy(&_frame_header.MASKING_KEY, ptr, static_cast<size_t>(min));
_masking_key_pos += min;
if (_masking_key_pos == 4)
{
_parser_step = e_payload_data;
}
}
return min;
}
uint32_t FrameParser::parse_payload(const char* data, uint32_t len)
{
if (_payload.empty() && _frame_header.PAYLOAD_REALY_LEN > 0)
{
_payload.reserve(static_cast<size_t>(_frame_header.PAYLOAD_REALY_LEN));
}
auto remain = static_cast<uint32_t>(_frame_header.PAYLOAD_REALY_LEN) - static_cast<uint32_t>(_payload.size());
auto min_len = std::min<uint32_t>(remain, len);
if (_frame_header.MASK)
{
unsigned char* mask = reinterpret_cast<unsigned char*>(&_frame_header.MASKING_KEY);
for (size_t i = 0; i < min_len; i++)
{
_payload.push_back(static_cast<char>(data[i] ^ mask[i % 4]));
}
}
else
{
_payload.append(data, min_len);
}
if (_payload.size() == _frame_header.PAYLOAD_REALY_LEN)
{
assert(_msb_cb);
_msb_cb(std::move(_payload), _frame_header.OPCODE, !!_frame_header.FIN);
reset();
}
return min_len;
}
std::pair<bool, std::string> FrameParser::Parse(void const* data, uint32_t len)
{
assert(data != nullptr && len > 0);
uint32_t offset = 0;
uint32_t remain_len = len;
try
{
do
{
if (_parser_step == e_fixed_header && remain_len)
{
offset += parse_fixed_header(static_cast<char const*>(data) + offset);
remain_len = len - offset;
}
if (_parser_step == e_payload_len && remain_len)
{
offset += parse_payload_len(static_cast<char const*>(data) + offset);
remain_len = len - offset;
}
if (_parser_step == e_extened_payload_len && remain_len)
{
offset += parse_extened_payload_len(static_cast<char const*>(data) + offset, remain_len);
remain_len = len - offset;
}
if (_parser_step == e_masking_key && remain_len)
{
offset += parse_masking_key(static_cast<char const*>(data) + offset, remain_len);
remain_len = len - offset;
}
if (_parser_step == e_payload_data && remain_len)
{
offset += parse_payload(static_cast<char const*>(data) + offset, remain_len);
remain_len = len - offset;
}
}
while (offset < len);
}
catch (std::exception const& e)
{
return {false, e.what()};
}
catch (...)
{
return {false, "unknown exception."};
}
return {true, ""};
}
} // namespace Websocket
} // namespace da4qi4
| 28.37037 | 114 | 0.586463 |
f137c5d4c66f20fd9810d8e5203c0a323e4e585e | 2,893 | cpp | C++ | lib/src/agents/proximity_sensor.cpp | eidelen/maf | 759b4b4a21962de8ec53dd198bc5bf66c19ee017 | [
"MIT"
] | null | null | null | lib/src/agents/proximity_sensor.cpp | eidelen/maf | 759b4b4a21962de8ec53dd198bc5bf66c19ee017 | [
"MIT"
] | null | null | null | lib/src/agents/proximity_sensor.cpp | eidelen/maf | 759b4b4a21962de8ec53dd198bc5bf66c19ee017 | [
"MIT"
] | null | null | null | /****************************************************************************
** Copyright (c) 2021 Adrian Schneider
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and associated documentation files (the "Software"),
** to deal in the Software without restriction, including without limitation
** the rights to use, copy, modify, merge, publish, distribute, sublicense,
** and/or sell copies of the Software, and to permit persons to whom the
** Software is furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
** FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
** DEALINGS IN THE SOFTWARE.
**
*****************************************************************************/
#include "proximity_sensor.h"
std::shared_ptr<ProximitySensor> ProximitySensor::createProxSensor(unsigned int id, double range)
{
return std::shared_ptr<ProximitySensor>(new ProximitySensor(id, range));
}
ProximitySensor::ProximitySensor(unsigned int id, double range): Agent::Agent(id), m_range(range)
{
}
ProximitySensor::~ProximitySensor()
{
}
void ProximitySensor::update(double time)
{
// update first sub agents
updateSubAgents(time);
assert(hasEnvironment());
// update agents in range
m_agentsInRange.clear();
EnvironmentInterface::DistanceQueue q = m_environment.lock()->getAgentDistancesToAllOtherAgents(id());
while(!q.empty())
{
const auto& d = q.top();
// if target is not on ignore list and target is in range
if( d.dist < m_range )
{
if( m_ignoreAgentIds.find(d.targetId) == m_ignoreAgentIds.end() )
{
m_agentsInRange.push_back(d);
}
q.pop();
}
else
{
// DistanceQueue is ordered -> next agent is out of range too
break;
}
}
performMove(time);
}
AgentType ProximitySensor::type() const
{
return AgentType::EProxSensor;
}
double ProximitySensor::range() const
{
return m_range;
}
void ProximitySensor::setRange(double newRange)
{
m_range = newRange;
}
std::vector<EnvironmentInterface::Distance> ProximitySensor::getAgentsInSensorRange() const
{
return m_agentsInRange;
}
void ProximitySensor::addIgnoreAgentId(unsigned int agentId)
{
m_ignoreAgentIds.insert(agentId);
}
| 28.93 | 106 | 0.663671 |
f137ef2add0af378ea99b08270988355bd06f43b | 212 | cpp | C++ | TestProject/Source/TestProject/TestProject.cpp | 1Gokul/TestProject | e732c65440537252bd02b9b527ac9a084f4ce44c | [
"MIT"
] | 3 | 2020-07-06T19:46:42.000Z | 2021-12-06T11:23:17.000Z | TestProject/Source/TestProject/TestProject.cpp | 1Gokul/TestProject | e732c65440537252bd02b9b527ac9a084f4ce44c | [
"MIT"
] | null | null | null | TestProject/Source/TestProject/TestProject.cpp | 1Gokul/TestProject | e732c65440537252bd02b9b527ac9a084f4ce44c | [
"MIT"
] | 1 | 2021-12-06T11:23:48.000Z | 2021-12-06T11:23:48.000Z | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "TestProject.h"
#include "Modules/ModuleManager.h"
IMPLEMENT_PRIMARY_GAME_MODULE(FDefaultGameModuleImpl, TestProject, "TestProject");
| 30.285714 | 83 | 0.783019 |
f138a7c9b24826789f4657efba62850bfafede9b | 3,047 | cpp | C++ | go/runtime/cgosymbolizer/symbolizer.cpp | searKing/golang | b386053582e223fc1f4c4ab3c2d73ab423cefef2 | [
"MIT"
] | 37 | 2019-11-19T15:42:09.000Z | 2022-03-27T07:55:42.000Z | go/runtime/cgosymbolizer/symbolizer.cpp | searKing/golang | b386053582e223fc1f4c4ab3c2d73ab423cefef2 | [
"MIT"
] | 5 | 2020-10-28T06:55:54.000Z | 2021-06-19T05:25:46.000Z | go/runtime/cgosymbolizer/symbolizer.cpp | searKing/golang | b386053582e223fc1f4c4ab3c2d73ab423cefef2 | [
"MIT"
] | 8 | 2019-12-17T05:56:18.000Z | 2021-08-17T20:36:41.000Z | // Copyright 2021 The searKing Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "symbolizer.h"
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
#include <boost/stacktrace/frame.hpp>
#include <boost/stacktrace/stacktrace.hpp>
#include "traceback.h"
static int append_pc_info_to_symbolizer_list(cgoSymbolizerArg* arg);
static int append_entry_to_symbolizer_list(cgoSymbolizerArg* arg);
// For the details of how this is called see runtime.SetCgoTraceback.
void cgoSymbolizer(cgoSymbolizerArg* arg) {
cgoSymbolizerMore* more = arg->data;
if (more != NULL) {
arg->file = more->file;
arg->lineno = more->lineno;
arg->func = more->func;
// set non-zero if more info for this PC
arg->more = more->more != NULL;
arg->data = more->more;
// If returning the last file/line, we can set the
// entry point field.
if (!arg->more) { // no more info
append_entry_to_symbolizer_list(arg);
}
return;
}
arg->file = NULL;
arg->lineno = 0;
arg->func = NULL;
arg->more = 0;
if (arg->pc == 0) {
return;
}
append_pc_info_to_symbolizer_list(arg);
// If returning only one file/line, we can set the entry point field.
if (!arg->more) {
append_entry_to_symbolizer_list(arg);
}
}
void prepare_syminfo(const boost::stacktrace::detail::native_frame_ptr_t addr,
std::string& file, std::size_t& line, std::string& func) {
auto frame = boost::stacktrace::frame(addr);
file = frame.source_file();
line = frame.source_line();
func = frame.name();
if (!func.empty()) {
func = boost::core::demangle(func.c_str());
} else {
func = boost::stacktrace::detail::to_hex_array(addr).data();
}
if (file.empty() || file.find_first_of("?") == 0) {
boost::stacktrace::detail::location_from_symbol loc(addr);
if (!loc.empty()) {
file = loc.name();
}
}
}
static int append_pc_info_to_symbolizer_list(cgoSymbolizerArg* arg) {
std::string file;
std::size_t line = 0;
std::string func;
prepare_syminfo(boost::stacktrace::frame::native_frame_ptr_t(arg->pc), file,
line, func);
// init head with current stack
if (arg->file == NULL) {
arg->file = strdup(file.c_str());
arg->lineno = line;
arg->func = strdup(func.c_str());
return 0;
}
cgoSymbolizerMore* more = (cgoSymbolizerMore*)malloc(sizeof(*more));
if (more == NULL) {
return 1;
}
// append current stack to the tail
more->more = NULL;
more->file = strdup(file.c_str());
more->lineno = line;
more->func = strdup(func.c_str());
cgoSymbolizerMore** pp = NULL;
for (pp = &arg->data; *pp != NULL; pp = &(*pp)->more) {
}
*pp = more;
arg->more = 1;
return 0;
}
static int append_entry_to_symbolizer_list(cgoSymbolizerArg* arg) {
auto frame = boost::stacktrace::frame(
boost::stacktrace::frame::native_frame_ptr_t(arg->pc));
arg->entry = (uintptr_t)strdup(frame.name().c_str());
return 0;
} | 27.954128 | 79 | 0.653758 |
f13ca70aaf155bb98e21ed8269ff4fbac2b742b0 | 1,187 | cpp | C++ | src/BabylonImGui/src/inspector/components/sceneexplorer/entities/transform_node_tree_item_component.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 277 | 2017-05-18T08:27:10.000Z | 2022-03-26T01:31:37.000Z | src/BabylonImGui/src/inspector/components/sceneexplorer/entities/transform_node_tree_item_component.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 77 | 2017-09-03T15:35:02.000Z | 2022-03-28T18:47:20.000Z | src/BabylonImGui/src/inspector/components/sceneexplorer/entities/transform_node_tree_item_component.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 37 | 2017-03-30T03:36:24.000Z | 2022-01-28T08:28:36.000Z | #include <babylon/inspector/components/sceneexplorer/entities/transform_node_tree_item_component.h>
#include <babylon/inspector/components/sceneexplorer/tree_item_label_component.h>
#include <babylon/meshes/transform_node.h>
#include <babylon/misc/string_tools.h>
#include <imgui_utils/imgui_utils.h>
namespace BABYLON {
TransformNodeTreeItemComponent::TransformNodeTreeItemComponent(
const ITransformNodeTreeItemComponentProps& iProps)
: props{iProps}
{
const auto& transformNode = props.transformNode;
sprintf(label, "%s", transformNode->name.c_str());
// Set the entity info
entityInfo.uniqueId = transformNode->uniqueId;
const auto className = transformNode->getClassName();
if (StringTools::contains(className, "TransformNode")) {
entityInfo.type = EntityType::TransformNode;
}
else if (StringTools::contains(className, "Mesh")) {
entityInfo.type = EntityType::Mesh;
}
}
TransformNodeTreeItemComponent::~TransformNodeTreeItemComponent() = default;
void TransformNodeTreeItemComponent::render()
{
// TransformNode tree item label
TreeItemLabelComponent::render(label, faCodeBranch, ImGui::cornflowerblue);
}
} // end of namespace BABYLON
| 31.236842 | 99 | 0.781803 |
f13ca97b2f05ebd5a61231499adceea695401023 | 7,774 | cpp | C++ | unique_paths.cpp | artureganyan/algorithms | 98cd0048162b3cb1c79712a884261cd3fe31063c | [
"MIT"
] | null | null | null | unique_paths.cpp | artureganyan/algorithms | 98cd0048162b3cb1c79712a884261cd3fe31063c | [
"MIT"
] | null | null | null | unique_paths.cpp | artureganyan/algorithms | 98cd0048162b3cb1c79712a884261cd3fe31063c | [
"MIT"
] | null | null | null | // Problem: https://leetcode.com/problems/unique-paths/
#include <vector>
#include "utils.h"
namespace unique_paths {
// Note: All solutions return int as required by the initial problem, but
// 32-bit signed integer can hold the result for at most the 17x18 grid.
// The straightforward solution, recursively counting paths from the start
// cell to the target
class Solution1 {
public:
// Time: O(C(n + m, m)), Space: O(n + m), Recursion depth < n + m
// n - number of rows, m - number of columns,
// C(n + m, m) - binomial coefficient (n + m)! / (m! * n!)
//
// Note: Time complexity is estimated by the number of paths, which is
// the binomial coefficient as shown in the Solution3. Space complexity
// depends on the recursion depth, which is determined by the path
// length n + m - 1.
//
int run(int rows_count, int cols_count)
{
if (rows_count <= 0 || cols_count <= 0)
return 0;
if (rows_count == 1 || cols_count == 1)
return 1;
// Go right + go down
return run(rows_count, cols_count - 1) +
run(rows_count - 1, cols_count);
}
};
// Non-recursive solution, counting paths from the target cell to the start
class Solution2 {
public:
// Time: O(n * m), Space: O(n * m), n - number of rows, m - number of columns
//
// Note: It calculates all cells, but 1) we need only the (0, 0), 2) the
// results are symmetrical: count(n, m) == count(m, n). So it could be
// optimized.
//
int run(int rows_count, int cols_count)
{
if (rows_count <= 0 || cols_count <= 0)
return 0;
// Idea:
// Count paths in reverse order, moving the start from the target cell to (0, 0):
// 1. Put the start to the target cell (t = rows_count - 1, l = cols_count - 1).
// Then there is only 1 path, i.e. the cell itself.
// 2. Go to the outer rectangle, which top-left corner is (t - 1, l - 1) if this
// is a square.
// 3. Calculate counts for the top and left borders of the outer rectangle. For
// each cell (r, c), the count is a sum of counts for (r + 1, c) and (r, c + 1),
// because we can step only right or down.
// 4. Repeat 2 and 3 until we reach (0, 0).
//
// 0 0 0 0 0 0 6 3 1
// 0 0 0 -> 0 2 1 -> 3 2 1
// 0 0 1 0 1 1 1 1 1
// Allocate one more row and column with zeros to avoid excessive range checks
std::vector<std::vector<int>> count(rows_count + 1, std::vector<int>(cols_count + 1, 0));
// Start from the target cell
int t = rows_count - 1;
int l = cols_count - 1;
int b = t;
int r = l;
count[t][l] = 1;
do {
// Go up and left. If not possible, decrease the right/bottom border
// because everything at the right/bottom is already counted.
if (t > 0) {
t -= 1;
} else {
r = l - 1;
}
if (l > 0) {
l -= 1;
} else {
b = t - 1;
}
// Count top border of the outer rectangle
for (int ci = r, ri = t; ci > l; ci--) {
calculateCount(count, ri, ci);
}
// Count left border of the outer rectangle
for (int ri = b, ci = l; ri > t; ri--) {
calculateCount(count, ri, ci);
}
// Count top-left corner of the outer rectangle
calculateCount(count, t, l);
} while (t != 0 || l != 0);
return count[0][0];
}
private:
inline void calculateCount(std::vector<std::vector<int>>& count, int r, int c) const
{
int& cell = count[r][c];
cell += count[r + 1][c];
cell += count[r][c + 1];
}
};
// This solution just calculates the binomial coefficient
class Solution3 {
public:
// Time: O(n - m), Space: O(1), n - number of rows, m - number of columns
//
// Warning: This implementation uses floating-point calculation and produces
// rounding error for large grids (e.g. test for 15x18 returned 1 path less
// than expected).
//
int run(int rows_count, int cols_count)
{
// Idea:
// If we look at the numbers of paths from each cell to the right-bottom
// corner, we may notice that they are binomial coefficients
// C(n, m) = n! / (m! * (n - m)!), written by diagonals:
//
// Numbers of paths. n n, excluding
// They are C(n, m). trivial cases
//
// 70 35 15 5 1 8 7 6 5 4 8 7 6 5 *
// 35 20 10 4 1 7 6 5 4 3 7 6 5 4 *
// 15 10 6 3 1 6 5 4 3 2 6 5 4 3 *
// 5 4 3 2 1 5 4 3 2 1 5 4 3 2 *
// 1 1 1 1 1 4 3 2 1 1 * * * * *
//
// For all cells except the right and bottom borders (which correspond
// to trivial cases nx1 and 1xn):
// n = (rows_count - 1) + (cols_count - 1)
// m = (cols_count - 1)
//
// Finally, to reduce the number of multiplications, we can simplify
// C(n, m) to ((m+1) * (m+2) * ... * n) / (n - m)! and swap rows_count
// and cols_count if rows_count > cols_count (the result is the same,
// but both the dividend and divisor are lesser).
if (rows_count <= 0 || cols_count <= 0)
return 0;
if (rows_count == 1 || cols_count == 1)
return 1;
if (rows_count > cols_count)
std::swap(rows_count, cols_count);
// Calculate C(n, m) = n! / (m! * (n - m)!)
// n, m
const int n = rows_count - 1 + cols_count - 1;
const int m = cols_count - 1;
// n! / m! = (m + 1) * (m + 2) * ... * n
double nf_div_mf = 1;
for (int i = m + 1; i <= n; i++)
nf_div_mf *= i;
// (n - m)!
double n_minus_m_f = 1;
for (int i = 2; i <= (n - m); i++)
n_minus_m_f *= i;
// C(n, m)
const double C_n_m = nf_div_mf / n_minus_m_f;
return static_cast<int>(C_n_m);
}
};
template <typename Solution>
void test(bool large_grid = false)
{
auto test_symmetrical = [](int rows_count, int cols_count, int expected)
{
if (Solution().run(rows_count, cols_count) != expected)
return false;
if (rows_count != cols_count) {
if (Solution().run(cols_count, rows_count) != expected)
return false;
}
return true;
};
ASSERT( test_symmetrical(-1, -1, 0) );
ASSERT( test_symmetrical(-1, 0, 0) );
ASSERT( test_symmetrical(-1, 1, 0) );
ASSERT( test_symmetrical(0, 0, 0) );
ASSERT( test_symmetrical(1, 0, 0) );
ASSERT( test_symmetrical(1, 1, 1) );
ASSERT( test_symmetrical(1, 2, 1) );
ASSERT( test_symmetrical(1, 3, 1) );
ASSERT( test_symmetrical(2, 2, 2) );
ASSERT( test_symmetrical(2, 3, 3) );
ASSERT( test_symmetrical(2, 4, 4) );
ASSERT( test_symmetrical(2, 5, 5) );
ASSERT( test_symmetrical(3, 3, 6) );
ASSERT( test_symmetrical(3, 4, 10) );
ASSERT( test_symmetrical(3, 5, 15) );
ASSERT( test_symmetrical(4, 4, 20) );
ASSERT( test_symmetrical(4, 5, 35) );
ASSERT( test_symmetrical(5, 5, 70) );
ASSERT( test_symmetrical(10, 10, 48620) );
if (large_grid)
ASSERT( test_symmetrical(17, 18, 1166803110) );
}
int main()
{
// Do not test large grid because of time complexity
test<Solution1>();
test<Solution2>(true);
// Do not test large grid because of rounding error
test<Solution3>();
return 0;
}
}
| 32.123967 | 97 | 0.531515 |
f13e2cc115d980c7d7ace1510d7f56367aa38fec | 5,915 | cpp | C++ | CFour/srcCPP/Source Generation/Generate findThreats/File5.cpp | cherrykit/Connect-Four | 8e611b2a2e2bec74b03cea405d2945eae430b8cf | [
"MIT"
] | 11 | 2015-07-01T02:40:53.000Z | 2020-07-11T22:38:27.000Z | CFour/srcCPP/Source Generation/Generate findThreats/File5.cpp | cherrykit/Connect-Four | 8e611b2a2e2bec74b03cea405d2945eae430b8cf | [
"MIT"
] | 2 | 2018-08-01T20:54:20.000Z | 2020-11-03T08:19:05.000Z | CFour/srcCPP/Source Generation/Generate findThreats/File5.cpp | MarkusThill/Connect-Four | 2a58844594ac022846385dd3ddc8bbbf0a26eae5 | [
"MIT"
] | 6 | 2018-02-21T20:30:57.000Z | 2020-10-25T15:17:31.000Z | //---------------------------------------------------------------------------
#include <vcl.h>
#include <fstream.h>
#pragma hdrstop
//---------------------------------------------------------------------------
__int64 viererreihen[49]=
{
0x1041040000i64,
0x41041000i64,
0x1041040i64,
0x41041i64,
0x2082080000i64,
0x82082000i64,
0x2082080i64,
0x82082i64,
0x1084200000i64,
0x42108000i64,
0x1084200i64,
0x42108i64,
0x8102040000i64,
0x204081000i64,
0x8102040i64,
0x204081i64,
0x4104100000i64,
0x104104000i64,
0x4104100i64,
0x104104i64,
0x2108400000i64,
0x84210000i64,
0x2108400i64,
0x84210i64,
0x10204080000i64,
0x408102000i64,
0x10204080i64,
0x408102i64,
0x8208200000i64,
0x208208000i64,
0x8208200i64,
0x208208i64,
0x4210800000i64,
0x108420000i64,
0x4210800i64,
0x108420i64,
0x20408100000i64,
0x810204000i64,
0x20408100i64,
0x810204i64,
0x10410400000i64,
0x410410000i64,
0x10410400i64,
0x410410i64,
0x20820800000i64,
0x820820000i64,
0x20820800i64,
0x820820i64
};
const unsigned __int64 Feldwert[7][6]=
{2199023255552i64,
1099511627776i64,
549755813888i64,
274877906944i64,
137438953472i64,
68719476736i64,
34359738368i64,
17179869184i64,
8589934592i64,
4294967296i64,
2147483648i64,
1073741824i64,
536870912i64,
268435456i64,
134217728i64,
67108864i64,
33554432i64,
16777216i64,
8388608i64,
4194304i64,
2097152i64,
1048576i64,
524288i64,
262144i64,
131072i64,
65536i64,
32768i64,
16384i64,
8192i64,
4096i64,
2048i64,
1024i64,
512i64,
256i64,
128i64,
64i64,
32i64,
16i64,
8i64,
4i64,
2i64,
1i64};
void fgh(void);
bool WeitereDrohung(__int64 feld, int *x1, int *y1, int *x2, int *y2);
AnsiString ToHex(__int64 wert);
#pragma argsused
int main(int argc, char* argv[])
{
fgh();
return 0;
}
//---------------------------------------------------------------------------
void fgh(void)
{
int i,j,k, counter=0,l,m;
__int64 array[30];
ofstream datei;
datei.open("C:\\10\\find.txt", ios::out);
datei << "short int FindThreats1(void)\n{\n\n";
for(l=0;l<7;l++)
{
datei << "\tswitch(Hoehe[" << l << "])\n\t{\n";
for(m=0;m<6;m++)
{
datei << "\t\tcase " << m <<":\n";
for(k=0;k<30;k++)
array[k]=-1i64;
int r=0;
for(k=0;k<49;k++)
for(i=0;i<7;i++)
for(j=0;j<6;j++)
if( (Feldwert[i][j] & viererreihen[k]))
{
__int64 dreierreihe= viererreihen[k] & (~Feldwert[i][j]);
int spalte1=-1, spalte2=-1, reihe1=-1, reihe2=-1;
if(!WeitereDrohung(dreierreihe, &spalte1, &reihe1, &spalte2, &reihe2))
{
spalte1=i;
reihe1=j;
}
if(Feldwert[l][m] & dreierreihe)
{
__int64 zweierreihe = dreierreihe & (~Feldwert[l][m]);
if(reihe1>0 && reihe2>0 && spalte1>=0 && spalte2>=0)
{
counter++;
int u;
for(u=0;u<30;u++)
if(array[u]==zweierreihe)
goto eins;
array[r++]=zweierreihe;
AnsiString wert=ToHex(zweierreihe);
datei << "\t\t\tif((Feld1 & 0x"<< wert.c_str() << "i64) == 0x"<<wert.c_str()<<"i64 && (Hoehe[" <<spalte1 <<"]<" <<reihe1 << " || Hoehe[" << spalte2 <<"]<" << reihe2 << ")) return "<< l <<";\n";
}
else if(reihe1>0 && spalte1>=0)
{
counter++;
int u;
for(u=0;u<30;u++)
if(array[u]==zweierreihe)
goto eins;
array[r++]=zweierreihe;
AnsiString wert=ToHex(zweierreihe);
datei << "\t\t\tif((Feld1 & 0x"<< wert.c_str() << "i64) == 0x"<<wert.c_str()<<"i64 && Hoehe[" <<spalte1 <<"]<" <<reihe1 << ") return "<< l <<";\n";
}
else if(reihe2>0 && spalte2>=0)
{
counter++;
int u;
for(u=0;u<30;u++)
if(array[u]==zweierreihe)
goto eins;
array[r++]=zweierreihe;
AnsiString wert=ToHex(zweierreihe);
datei << "\t\t\tif((Feld1 & 0x"<< wert.c_str() << "i64) == 0x"<<wert.c_str()<<"i64 && Hoehe[" <<spalte2 <<"]<" <<reihe2 << ") return "<< l <<";\n";
}
eins:
}
}
datei << "\t\t\tbreak;\n";
}
datei << "\t\tdefault:\n\t\t\tbreak;\n\t}\n";
}
datei << "\treturn (-1);\n}";
}
bool WeitereDrohung(__int64 feld, int *x1, int *y1, int *x2, int *y2)
{
int i,j;
for(i=0;i<7;i++)
for(j=0;j<6;j++)
{
if(Feldwert[i][j] & feld)
{
if(i>=4 || i==0) //es kann nicht auf 2 Seiten sein
return false;
if( (Feldwert[i+1][j] & feld) && (Feldwert[i+2][j] & feld) ) //Horizontal
{
*x1=i-1; *x2=i+3; *y1=j; *y2=j;
return true;
}
if(j<3 && j>0) //Diagonal hoch
if( (Feldwert[i+1][j+1] & feld) && (Feldwert[i+2][j+2] & feld) )
{
*x1=i-1; *x2=i+3; *y1=j-1; *y2=j+3;
return true;
}
if(j>2 && j<5) //Diagonal runter
if( (Feldwert[i+1][j-1] & feld) && (Feldwert[i+2][j-2] & feld))
{
*x1=i-1; *x2=i+3; *y1=j+1; *y2=j-3;
return true;
}
return false;
}
}
return false;
}
AnsiString ToHex(__int64 wert)
{
AnsiString rueck;
rueck.SetLength(0);
int x = 15;
__int64 verschiebe, temp, nibble;
Boolean trotzdem=false;
for(int i=15;i>=0;i--)
{
verschiebe= ((__int64)x) << (i*4i64);
temp = wert & verschiebe;
nibble = temp >> (i*4i64);
if(nibble>0 || trotzdem)
{
rueck.SetLength(rueck.Length()+1);
trotzdem=true;
if(nibble<10)
rueck[rueck.Length()]=(nibble+48);
else
rueck[rueck.Length()]=(nibble+55);
}
}
return rueck;
}
| 23.105469 | 203 | 0.509045 |
f13e6e63b73ef115d8ca7a445339307d0a7f6eca | 176,331 | cpp | C++ | GCG_Source.build/module.django.utils._os.cpp | Pckool/GCG | cee786d04ea30f3995e910bca82635f442b2a6a8 | [
"MIT"
] | null | null | null | GCG_Source.build/module.django.utils._os.cpp | Pckool/GCG | cee786d04ea30f3995e910bca82635f442b2a6a8 | [
"MIT"
] | null | null | null | GCG_Source.build/module.django.utils._os.cpp | Pckool/GCG | cee786d04ea30f3995e910bca82635f442b2a6a8 | [
"MIT"
] | null | null | null | /* Generated code for Python source for module 'django.utils._os'
* created by Nuitka version 0.5.28.2
*
* This code is in part copyright 2017 Kay Hayen.
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* 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 "nuitka/prelude.h"
#include "__helpers.h"
/* The _module_django$utils$_os is a Python object pointer of module type. */
/* Note: For full compatibility with CPython, every module variable access
* needs to go through it except for cases where the module cannot possibly
* have changed in the mean time.
*/
PyObject *module_django$utils$_os;
PyDictObject *moduledict_django$utils$_os;
/* The module constants used, if any. */
extern PyObject *const_str_plain_force_text;
static PyObject *const_str_digest_a2f4bfb7897945f1cc69848924f0cb55;
extern PyObject *const_str_plain_remove;
extern PyObject *const_str_plain_PY2;
extern PyObject *const_str_plain_ModuleSpec;
extern PyObject *const_str_plain___spec__;
extern PyObject *const_str_plain___package__;
extern PyObject *const_str_plain_sys;
extern PyObject *const_tuple_str_plain_SuspiciousFileOperation_tuple;
extern PyObject *const_str_plain_decode;
extern PyObject *const_str_plain_unicode_literals;
extern PyObject *const_str_plain_nt;
extern PyObject *const_str_plain_sep;
static PyObject *const_str_digest_02c3b3e14ee51a74c880c9a2312b4dc8;
extern PyObject *const_str_plain_text_type;
static PyObject *const_str_plain_final_path;
extern PyObject *const_tuple_str_plain_path_tuple;
static PyObject *const_str_plain_symlink_path;
static PyObject *const_str_digest_e029ae267a3a9a3ffb4d22037d50a89e;
extern PyObject *const_dict_empty;
extern PyObject *const_str_digest_842dfd4744c6e20ce39943a1591eb59d;
extern PyObject *const_str_plain___file__;
static PyObject *const_str_digest_e333b5c27f64858ace2064722679d143;
extern PyObject *const_str_digest_e3393b2e61653c3df2c7d436c253bbee;
static PyObject *const_tuple_d68c618138c0feb94dce5f32faa81863_tuple;
extern PyObject *const_tuple_str_plain_force_text_tuple;
extern PyObject *const_str_digest_e399ba4554180f37de594a6743234f17;
extern PyObject *const_int_0;
extern PyObject *const_str_plain_path;
extern PyObject *const_str_angle_listcontraction;
extern PyObject *const_str_plain_safe_join;
extern PyObject *const_str_plain_encode;
static PyObject *const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple;
extern PyObject *const_str_plain_six;
extern PyObject *const_str_plain_p;
extern PyObject *const_str_plain_tempfile;
extern PyObject *const_str_plain_abspathu;
static PyObject *const_str_digest_b3b92bc7aa9804266ff219682e3d0112;
static PyObject *const_str_plain_mkdtemp;
extern PyObject *const_str_plain_normpath;
extern PyObject *const_str_plain_abspath;
static PyObject *const_str_plain_rmdir;
static PyObject *const_str_digest_7099b288cddfaaccfbbcfd3d0cceafa5;
extern PyObject *const_str_plain_normcase;
static PyObject *const_str_plain_getdefaultencoding;
static PyObject *const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple;
extern PyObject *const_str_digest_dfb6e1abbed3113ee07234fdc458a320;
static PyObject *const_str_digest_d92a79f74db4468ebeba34a6c933cb11;
extern PyObject *const_tuple_str_plain_six_tuple;
extern PyObject *const_str_plain_os;
static PyObject *const_str_digest_5c892843b642786d8376f7cd7a9ec574;
static PyObject *const_str_plain_getfilesystemencoding;
static PyObject *const_str_plain_symlink;
extern PyObject *const_str_plain_original;
extern PyObject *const_tuple_empty;
extern PyObject *const_str_plain_getcwdu;
extern PyObject *const_str_plain_SuspiciousFileOperation;
extern PyObject *const_str_digest_467c9722f19d9d40d148689532cdc0b1;
extern PyObject *const_str_plain_base;
extern PyObject *const_str_plain_tmpdir;
extern PyObject *const_str_plain_upath;
extern PyObject *const_str_plain_npath;
extern PyObject *const_str_plain_paths;
static PyObject *const_str_plain_base_path;
extern PyObject *const_str_plain_makedirs;
static PyObject *const_str_plain_original_path;
extern PyObject *const_str_plain___loader__;
extern PyObject *const_str_plain_format;
extern PyObject *const_str_plain_join;
extern PyObject *const_str_plain_name;
static PyObject *const_str_plain_symlinks_supported;
extern PyObject *const_str_plain_startswith;
static PyObject *const_str_plain_supported;
extern PyObject *const_str_plain_dirname;
static PyObject *const_str_plain_fs_encoding;
static PyObject *const_tuple_str_plain_p_str_plain_paths_tuple;
extern PyObject *const_str_plain_PY3;
extern PyObject *const_str_plain___doc__;
extern PyObject *const_str_plain___cached__;
static PyObject *const_str_plain_isabs;
static PyObject *module_filename_obj;
static bool constants_created = false;
static void createModuleConstants( void )
{
const_str_digest_a2f4bfb7897945f1cc69848924f0cb55 = UNSTREAM_STRING( &constant_bin[ 1141471 ], 19, 0 );
const_str_digest_02c3b3e14ee51a74c880c9a2312b4dc8 = UNSTREAM_STRING( &constant_bin[ 1141490 ], 257, 0 );
const_str_plain_final_path = UNSTREAM_STRING( &constant_bin[ 1141747 ], 10, 1 );
const_str_plain_symlink_path = UNSTREAM_STRING( &constant_bin[ 1141757 ], 12, 1 );
const_str_digest_e029ae267a3a9a3ffb4d22037d50a89e = UNSTREAM_STRING( &constant_bin[ 1141769 ], 39, 0 );
const_str_digest_e333b5c27f64858ace2064722679d143 = UNSTREAM_STRING( &constant_bin[ 1141808 ], 71, 0 );
const_tuple_d68c618138c0feb94dce5f32faa81863_tuple = PyTuple_New( 4 );
PyTuple_SET_ITEM( const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 0, const_str_plain_tmpdir ); Py_INCREF( const_str_plain_tmpdir );
const_str_plain_original_path = UNSTREAM_STRING( &constant_bin[ 1141879 ], 13, 1 );
PyTuple_SET_ITEM( const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 1, const_str_plain_original_path ); Py_INCREF( const_str_plain_original_path );
PyTuple_SET_ITEM( const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 2, const_str_plain_symlink_path ); Py_INCREF( const_str_plain_symlink_path );
const_str_plain_supported = UNSTREAM_STRING( &constant_bin[ 1262 ], 9, 1 );
PyTuple_SET_ITEM( const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 3, const_str_plain_supported ); Py_INCREF( const_str_plain_supported );
const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple = PyTuple_New( 4 );
PyTuple_SET_ITEM( const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 0, const_str_plain_base ); Py_INCREF( const_str_plain_base );
PyTuple_SET_ITEM( const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 1, const_str_plain_paths ); Py_INCREF( const_str_plain_paths );
PyTuple_SET_ITEM( const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 2, const_str_plain_final_path ); Py_INCREF( const_str_plain_final_path );
const_str_plain_base_path = UNSTREAM_STRING( &constant_bin[ 1141892 ], 9, 1 );
PyTuple_SET_ITEM( const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 3, const_str_plain_base_path ); Py_INCREF( const_str_plain_base_path );
const_str_digest_b3b92bc7aa9804266ff219682e3d0112 = UNSTREAM_STRING( &constant_bin[ 1141901 ], 183, 0 );
const_str_plain_mkdtemp = UNSTREAM_STRING( &constant_bin[ 1142084 ], 7, 1 );
const_str_plain_rmdir = UNSTREAM_STRING( &constant_bin[ 1142091 ], 5, 1 );
const_str_digest_7099b288cddfaaccfbbcfd3d0cceafa5 = UNSTREAM_STRING( &constant_bin[ 1142096 ], 25, 0 );
const_str_plain_getdefaultencoding = UNSTREAM_STRING( &constant_bin[ 1142121 ], 18, 1 );
const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple = PyTuple_New( 7 );
PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 0, const_str_plain_abspath ); Py_INCREF( const_str_plain_abspath );
PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 1, const_str_plain_dirname ); Py_INCREF( const_str_plain_dirname );
const_str_plain_isabs = UNSTREAM_STRING( &constant_bin[ 1142139 ], 5, 1 );
PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 2, const_str_plain_isabs ); Py_INCREF( const_str_plain_isabs );
PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 3, const_str_plain_join ); Py_INCREF( const_str_plain_join );
PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 4, const_str_plain_normcase ); Py_INCREF( const_str_plain_normcase );
PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 5, const_str_plain_normpath ); Py_INCREF( const_str_plain_normpath );
PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 6, const_str_plain_sep ); Py_INCREF( const_str_plain_sep );
const_str_digest_d92a79f74db4468ebeba34a6c933cb11 = UNSTREAM_STRING( &constant_bin[ 1142144 ], 213, 0 );
const_str_digest_5c892843b642786d8376f7cd7a9ec574 = UNSTREAM_STRING( &constant_bin[ 1142357 ], 98, 0 );
const_str_plain_getfilesystemencoding = UNSTREAM_STRING( &constant_bin[ 1142455 ], 21, 1 );
const_str_plain_symlink = UNSTREAM_STRING( &constant_bin[ 1141757 ], 7, 1 );
const_str_plain_symlinks_supported = UNSTREAM_STRING( &constant_bin[ 1142476 ], 18, 1 );
const_str_plain_fs_encoding = UNSTREAM_STRING( &constant_bin[ 1142494 ], 11, 1 );
const_tuple_str_plain_p_str_plain_paths_tuple = PyTuple_New( 2 );
PyTuple_SET_ITEM( const_tuple_str_plain_p_str_plain_paths_tuple, 0, const_str_plain_p ); Py_INCREF( const_str_plain_p );
PyTuple_SET_ITEM( const_tuple_str_plain_p_str_plain_paths_tuple, 1, const_str_plain_paths ); Py_INCREF( const_str_plain_paths );
constants_created = true;
}
#ifndef __NUITKA_NO_ASSERT__
void checkModuleConstants_django$utils$_os( void )
{
// The module may not have been used at all.
if (constants_created == false) return;
}
#endif
// The module code objects.
static PyCodeObject *codeobj_f795cf1a4736e33c5a5152c4aef12ba3;
static PyCodeObject *codeobj_e3f2225c4277cee0cd5878c353c5494a;
static PyCodeObject *codeobj_8338c887cffee3f6624948b93fdb5cad;
static PyCodeObject *codeobj_f5eb817954879f203f472ef76832ad97;
static PyCodeObject *codeobj_519eab41ce47fa2590f6a99ccc08067a;
static PyCodeObject *codeobj_7f1d67953d1486ada0ef5501b0312cae;
static PyCodeObject *codeobj_786e20e096923522b138dc8044ece5a9;
static void createModuleCodeObjects(void)
{
module_filename_obj = MAKE_RELATIVE_PATH( const_str_digest_a2f4bfb7897945f1cc69848924f0cb55 );
codeobj_f795cf1a4736e33c5a5152c4aef12ba3 = MAKE_CODEOBJ( module_filename_obj, const_str_angle_listcontraction, 63, const_tuple_str_plain_p_str_plain_paths_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_e3f2225c4277cee0cd5878c353c5494a = MAKE_CODEOBJ( module_filename_obj, const_str_digest_7099b288cddfaaccfbbcfd3d0cceafa5, 1, const_tuple_empty, 0, 0, CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_8338c887cffee3f6624948b93fdb5cad = MAKE_CODEOBJ( module_filename_obj, const_str_plain_abspathu, 24, const_tuple_str_plain_path_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_f5eb817954879f203f472ef76832ad97 = MAKE_CODEOBJ( module_filename_obj, const_str_plain_npath, 44, const_tuple_str_plain_path_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_519eab41ce47fa2590f6a99ccc08067a = MAKE_CODEOBJ( module_filename_obj, const_str_plain_safe_join, 54, const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_VARARGS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_7f1d67953d1486ada0ef5501b0312cae = MAKE_CODEOBJ( module_filename_obj, const_str_plain_symlinks_supported, 82, const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 0, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_786e20e096923522b138dc8044ece5a9 = MAKE_CODEOBJ( module_filename_obj, const_str_plain_upath, 35, const_tuple_str_plain_path_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
}
// The module function declarations.
NUITKA_CROSS_MODULE PyObject *impl___internal__$$$function_12_complex_call_helper_pos_star_list( PyObject **python_pars );
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_1_abspathu( );
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_2_upath( );
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_3_npath( );
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_4_safe_join( );
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_5_symlinks_supported( );
// The module function definitions.
static PyObject *impl_django$utils$_os$$$function_1_abspathu( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *par_path = python_pars[ 0 ];
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_args_element_name_3;
PyObject *tmp_args_element_name_4;
PyObject *tmp_assign_source_1;
PyObject *tmp_called_instance_1;
PyObject *tmp_called_name_1;
PyObject *tmp_called_name_2;
PyObject *tmp_called_name_3;
int tmp_cond_truth_1;
PyObject *tmp_cond_value_1;
PyObject *tmp_return_value;
static struct Nuitka_FrameObject *cache_frame_8338c887cffee3f6624948b93fdb5cad = NULL;
struct Nuitka_FrameObject *frame_8338c887cffee3f6624948b93fdb5cad;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_8338c887cffee3f6624948b93fdb5cad, codeobj_8338c887cffee3f6624948b93fdb5cad, module_django$utils$_os, sizeof(void *) );
frame_8338c887cffee3f6624948b93fdb5cad = cache_frame_8338c887cffee3f6624948b93fdb5cad;
// Push the new frame as the currently active one.
pushFrameStack( frame_8338c887cffee3f6624948b93fdb5cad );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_8338c887cffee3f6624948b93fdb5cad ) == 2 ); // Frame stack
// Framed code:
tmp_called_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_isabs );
if (unlikely( tmp_called_name_1 == NULL ))
{
tmp_called_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_isabs );
}
if ( tmp_called_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "isabs" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 30;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = par_path;
CHECK_OBJECT( tmp_args_element_name_1 );
frame_8338c887cffee3f6624948b93fdb5cad->m_frame.f_lineno = 30;
{
PyObject *call_args[] = { tmp_args_element_name_1 };
tmp_cond_value_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args );
}
if ( tmp_cond_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 30;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_1 );
exception_lineno = 30;
type_description_1 = "o";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == 1 )
{
goto branch_no_1;
}
else
{
goto branch_yes_1;
}
branch_yes_1:;
tmp_called_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_join );
if (unlikely( tmp_called_name_2 == NULL ))
{
tmp_called_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_join );
}
if ( tmp_called_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "join" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 31;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_called_instance_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_called_instance_1 == NULL ))
{
tmp_called_instance_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_called_instance_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 31;
type_description_1 = "o";
goto frame_exception_exit_1;
}
frame_8338c887cffee3f6624948b93fdb5cad->m_frame.f_lineno = 31;
tmp_args_element_name_2 = CALL_METHOD_NO_ARGS( tmp_called_instance_1, const_str_plain_getcwdu );
if ( tmp_args_element_name_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 31;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_args_element_name_3 = par_path;
if ( tmp_args_element_name_3 == NULL )
{
Py_DECREF( tmp_args_element_name_2 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 31;
type_description_1 = "o";
goto frame_exception_exit_1;
}
frame_8338c887cffee3f6624948b93fdb5cad->m_frame.f_lineno = 31;
{
PyObject *call_args[] = { tmp_args_element_name_2, tmp_args_element_name_3 };
tmp_assign_source_1 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_2, call_args );
}
Py_DECREF( tmp_args_element_name_2 );
if ( tmp_assign_source_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 31;
type_description_1 = "o";
goto frame_exception_exit_1;
}
{
PyObject *old = par_path;
par_path = tmp_assign_source_1;
Py_XDECREF( old );
}
branch_no_1:;
tmp_called_name_3 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normpath );
if (unlikely( tmp_called_name_3 == NULL ))
{
tmp_called_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normpath );
}
if ( tmp_called_name_3 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normpath" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 32;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_args_element_name_4 = par_path;
if ( tmp_args_element_name_4 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 32;
type_description_1 = "o";
goto frame_exception_exit_1;
}
frame_8338c887cffee3f6624948b93fdb5cad->m_frame.f_lineno = 32;
{
PyObject *call_args[] = { tmp_args_element_name_4 };
tmp_return_value = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_3, call_args );
}
if ( tmp_return_value == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 32;
type_description_1 = "o";
goto frame_exception_exit_1;
}
goto frame_return_exit_1;
#if 0
RESTORE_FRAME_EXCEPTION( frame_8338c887cffee3f6624948b93fdb5cad );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_8338c887cffee3f6624948b93fdb5cad );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_8338c887cffee3f6624948b93fdb5cad );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_8338c887cffee3f6624948b93fdb5cad, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_8338c887cffee3f6624948b93fdb5cad->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_8338c887cffee3f6624948b93fdb5cad, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_8338c887cffee3f6624948b93fdb5cad,
type_description_1,
par_path
);
// Release cached frame.
if ( frame_8338c887cffee3f6624948b93fdb5cad == cache_frame_8338c887cffee3f6624948b93fdb5cad )
{
Py_DECREF( frame_8338c887cffee3f6624948b93fdb5cad );
}
cache_frame_8338c887cffee3f6624948b93fdb5cad = NULL;
assertFrameObject( frame_8338c887cffee3f6624948b93fdb5cad );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_1_abspathu );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_path );
par_path = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( par_path );
par_path = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_1_abspathu );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
static PyObject *impl_django$utils$_os$$$function_2_upath( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *par_path = python_pars[ 0 ];
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
int tmp_and_left_truth_1;
PyObject *tmp_and_left_value_1;
PyObject *tmp_and_right_value_1;
PyObject *tmp_args_element_name_1;
PyObject *tmp_called_name_1;
int tmp_cond_truth_1;
PyObject *tmp_cond_value_1;
PyObject *tmp_isinstance_cls_1;
PyObject *tmp_isinstance_inst_1;
PyObject *tmp_operand_name_1;
PyObject *tmp_return_value;
PyObject *tmp_source_name_1;
PyObject *tmp_source_name_2;
PyObject *tmp_source_name_3;
static struct Nuitka_FrameObject *cache_frame_786e20e096923522b138dc8044ece5a9 = NULL;
struct Nuitka_FrameObject *frame_786e20e096923522b138dc8044ece5a9;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_786e20e096923522b138dc8044ece5a9, codeobj_786e20e096923522b138dc8044ece5a9, module_django$utils$_os, sizeof(void *) );
frame_786e20e096923522b138dc8044ece5a9 = cache_frame_786e20e096923522b138dc8044ece5a9;
// Push the new frame as the currently active one.
pushFrameStack( frame_786e20e096923522b138dc8044ece5a9 );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_786e20e096923522b138dc8044ece5a9 ) == 2 ); // Frame stack
// Framed code:
tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six );
if (unlikely( tmp_source_name_1 == NULL ))
{
tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six );
}
if ( tmp_source_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_and_left_value_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_PY2 );
if ( tmp_and_left_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_and_left_truth_1 = CHECK_IF_TRUE( tmp_and_left_value_1 );
if ( tmp_and_left_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_and_left_value_1 );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
if ( tmp_and_left_truth_1 == 1 )
{
goto and_right_1;
}
else
{
goto and_left_1;
}
and_right_1:;
Py_DECREF( tmp_and_left_value_1 );
tmp_isinstance_inst_1 = par_path;
if ( tmp_isinstance_inst_1 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six );
if (unlikely( tmp_source_name_2 == NULL ))
{
tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six );
}
if ( tmp_source_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_isinstance_cls_1 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_text_type );
if ( tmp_isinstance_cls_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_operand_name_1 = BUILTIN_ISINSTANCE( tmp_isinstance_inst_1, tmp_isinstance_cls_1 );
Py_DECREF( tmp_isinstance_cls_1 );
if ( tmp_operand_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_and_right_value_1 = UNARY_OPERATION( UNARY_NOT, tmp_operand_name_1 );
if ( tmp_and_right_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_and_right_value_1 );
tmp_cond_value_1 = tmp_and_right_value_1;
goto and_end_1;
and_left_1:;
tmp_cond_value_1 = tmp_and_left_value_1;
and_end_1:;
tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_1 );
exception_lineno = 39;
type_description_1 = "o";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_source_name_3 = par_path;
if ( tmp_source_name_3 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 40;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_decode );
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 40;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_fs_encoding );
if (unlikely( tmp_args_element_name_1 == NULL ))
{
tmp_args_element_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_fs_encoding );
}
if ( tmp_args_element_name_1 == NULL )
{
Py_DECREF( tmp_called_name_1 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "fs_encoding" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 40;
type_description_1 = "o";
goto frame_exception_exit_1;
}
frame_786e20e096923522b138dc8044ece5a9->m_frame.f_lineno = 40;
{
PyObject *call_args[] = { tmp_args_element_name_1 };
tmp_return_value = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args );
}
Py_DECREF( tmp_called_name_1 );
if ( tmp_return_value == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 40;
type_description_1 = "o";
goto frame_exception_exit_1;
}
goto frame_return_exit_1;
branch_no_1:;
tmp_return_value = par_path;
if ( tmp_return_value == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 41;
type_description_1 = "o";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_return_value );
goto frame_return_exit_1;
#if 0
RESTORE_FRAME_EXCEPTION( frame_786e20e096923522b138dc8044ece5a9 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_786e20e096923522b138dc8044ece5a9 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_786e20e096923522b138dc8044ece5a9 );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_786e20e096923522b138dc8044ece5a9, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_786e20e096923522b138dc8044ece5a9->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_786e20e096923522b138dc8044ece5a9, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_786e20e096923522b138dc8044ece5a9,
type_description_1,
par_path
);
// Release cached frame.
if ( frame_786e20e096923522b138dc8044ece5a9 == cache_frame_786e20e096923522b138dc8044ece5a9 )
{
Py_DECREF( frame_786e20e096923522b138dc8044ece5a9 );
}
cache_frame_786e20e096923522b138dc8044ece5a9 = NULL;
assertFrameObject( frame_786e20e096923522b138dc8044ece5a9 );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_2_upath );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_path );
par_path = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( par_path );
par_path = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_2_upath );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
static PyObject *impl_django$utils$_os$$$function_3_npath( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *par_path = python_pars[ 0 ];
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
int tmp_and_left_truth_1;
PyObject *tmp_and_left_value_1;
PyObject *tmp_and_right_value_1;
PyObject *tmp_args_element_name_1;
PyObject *tmp_called_name_1;
int tmp_cond_truth_1;
PyObject *tmp_cond_value_1;
PyObject *tmp_isinstance_cls_1;
PyObject *tmp_isinstance_inst_1;
PyObject *tmp_operand_name_1;
PyObject *tmp_return_value;
PyObject *tmp_source_name_1;
PyObject *tmp_source_name_2;
static struct Nuitka_FrameObject *cache_frame_f5eb817954879f203f472ef76832ad97 = NULL;
struct Nuitka_FrameObject *frame_f5eb817954879f203f472ef76832ad97;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_f5eb817954879f203f472ef76832ad97, codeobj_f5eb817954879f203f472ef76832ad97, module_django$utils$_os, sizeof(void *) );
frame_f5eb817954879f203f472ef76832ad97 = cache_frame_f5eb817954879f203f472ef76832ad97;
// Push the new frame as the currently active one.
pushFrameStack( frame_f5eb817954879f203f472ef76832ad97 );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_f5eb817954879f203f472ef76832ad97 ) == 2 ); // Frame stack
// Framed code:
tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six );
if (unlikely( tmp_source_name_1 == NULL ))
{
tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six );
}
if ( tmp_source_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 49;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_and_left_value_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_PY2 );
if ( tmp_and_left_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 49;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_and_left_truth_1 = CHECK_IF_TRUE( tmp_and_left_value_1 );
if ( tmp_and_left_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_and_left_value_1 );
exception_lineno = 49;
type_description_1 = "o";
goto frame_exception_exit_1;
}
if ( tmp_and_left_truth_1 == 1 )
{
goto and_right_1;
}
else
{
goto and_left_1;
}
and_right_1:;
Py_DECREF( tmp_and_left_value_1 );
tmp_isinstance_inst_1 = par_path;
if ( tmp_isinstance_inst_1 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 49;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_isinstance_cls_1 = (PyObject *)&PyBytes_Type;
tmp_operand_name_1 = BUILTIN_ISINSTANCE( tmp_isinstance_inst_1, tmp_isinstance_cls_1 );
if ( tmp_operand_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 49;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_and_right_value_1 = UNARY_OPERATION( UNARY_NOT, tmp_operand_name_1 );
if ( tmp_and_right_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 49;
type_description_1 = "o";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_and_right_value_1 );
tmp_cond_value_1 = tmp_and_right_value_1;
goto and_end_1;
and_left_1:;
tmp_cond_value_1 = tmp_and_left_value_1;
and_end_1:;
tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_1 );
exception_lineno = 49;
type_description_1 = "o";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_source_name_2 = par_path;
if ( tmp_source_name_2 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 50;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_encode );
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 50;
type_description_1 = "o";
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_fs_encoding );
if (unlikely( tmp_args_element_name_1 == NULL ))
{
tmp_args_element_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_fs_encoding );
}
if ( tmp_args_element_name_1 == NULL )
{
Py_DECREF( tmp_called_name_1 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "fs_encoding" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 50;
type_description_1 = "o";
goto frame_exception_exit_1;
}
frame_f5eb817954879f203f472ef76832ad97->m_frame.f_lineno = 50;
{
PyObject *call_args[] = { tmp_args_element_name_1 };
tmp_return_value = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args );
}
Py_DECREF( tmp_called_name_1 );
if ( tmp_return_value == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 50;
type_description_1 = "o";
goto frame_exception_exit_1;
}
goto frame_return_exit_1;
branch_no_1:;
tmp_return_value = par_path;
if ( tmp_return_value == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 51;
type_description_1 = "o";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_return_value );
goto frame_return_exit_1;
#if 0
RESTORE_FRAME_EXCEPTION( frame_f5eb817954879f203f472ef76832ad97 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_f5eb817954879f203f472ef76832ad97 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_f5eb817954879f203f472ef76832ad97 );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_f5eb817954879f203f472ef76832ad97, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_f5eb817954879f203f472ef76832ad97->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_f5eb817954879f203f472ef76832ad97, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_f5eb817954879f203f472ef76832ad97,
type_description_1,
par_path
);
// Release cached frame.
if ( frame_f5eb817954879f203f472ef76832ad97 == cache_frame_f5eb817954879f203f472ef76832ad97 )
{
Py_DECREF( frame_f5eb817954879f203f472ef76832ad97 );
}
cache_frame_f5eb817954879f203f472ef76832ad97 = NULL;
assertFrameObject( frame_f5eb817954879f203f472ef76832ad97 );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_3_npath );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_path );
par_path = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( par_path );
par_path = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_3_npath );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
static PyObject *impl_django$utils$_os$$$function_4_safe_join( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *par_base = python_pars[ 0 ];
PyObject *par_paths = python_pars[ 1 ];
PyObject *var_final_path = NULL;
PyObject *var_base_path = NULL;
PyObject *outline_0_var_p = NULL;
PyObject *tmp_listcontraction_1__$0 = NULL;
PyObject *tmp_listcontraction_1__contraction = NULL;
PyObject *tmp_listcontraction_1__iter_value_0 = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *exception_keeper_type_2;
PyObject *exception_keeper_value_2;
PyTracebackObject *exception_keeper_tb_2;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2;
PyObject *exception_keeper_type_3;
PyObject *exception_keeper_value_3;
PyTracebackObject *exception_keeper_tb_3;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3;
int tmp_and_left_truth_1;
int tmp_and_left_truth_2;
PyObject *tmp_and_left_value_1;
PyObject *tmp_and_left_value_2;
PyObject *tmp_and_right_value_1;
PyObject *tmp_and_right_value_2;
PyObject *tmp_append_list_1;
PyObject *tmp_append_value_1;
PyObject *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_args_element_name_3;
PyObject *tmp_args_element_name_4;
PyObject *tmp_args_element_name_5;
PyObject *tmp_args_element_name_6;
PyObject *tmp_args_element_name_7;
PyObject *tmp_args_element_name_8;
PyObject *tmp_args_element_name_9;
PyObject *tmp_args_element_name_10;
PyObject *tmp_args_element_name_11;
PyObject *tmp_args_element_name_12;
PyObject *tmp_args_element_name_13;
PyObject *tmp_args_element_name_14;
PyObject *tmp_args_element_name_15;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_assign_source_3;
PyObject *tmp_assign_source_4;
PyObject *tmp_assign_source_5;
PyObject *tmp_assign_source_6;
PyObject *tmp_assign_source_7;
PyObject *tmp_assign_source_8;
PyObject *tmp_called_name_1;
PyObject *tmp_called_name_2;
PyObject *tmp_called_name_3;
PyObject *tmp_called_name_4;
PyObject *tmp_called_name_5;
PyObject *tmp_called_name_6;
PyObject *tmp_called_name_7;
PyObject *tmp_called_name_8;
PyObject *tmp_called_name_9;
PyObject *tmp_called_name_10;
PyObject *tmp_called_name_11;
PyObject *tmp_called_name_12;
PyObject *tmp_called_name_13;
PyObject *tmp_called_name_14;
PyObject *tmp_compexpr_left_1;
PyObject *tmp_compexpr_left_2;
PyObject *tmp_compexpr_right_1;
PyObject *tmp_compexpr_right_2;
int tmp_cond_truth_1;
PyObject *tmp_cond_value_1;
PyObject *tmp_dircall_arg1_1;
PyObject *tmp_dircall_arg2_1;
PyObject *tmp_dircall_arg3_1;
PyObject *tmp_iter_arg_1;
PyObject *tmp_left_name_1;
PyObject *tmp_next_source_1;
PyObject *tmp_operand_name_1;
PyObject *tmp_outline_return_value_1;
PyObject *tmp_raise_type_1;
int tmp_res;
PyObject *tmp_return_value;
PyObject *tmp_right_name_1;
PyObject *tmp_source_name_1;
PyObject *tmp_source_name_2;
PyObject *tmp_tuple_element_1;
static struct Nuitka_FrameObject *cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2 = NULL;
struct Nuitka_FrameObject *frame_f795cf1a4736e33c5a5152c4aef12ba3_2;
static struct Nuitka_FrameObject *cache_frame_519eab41ce47fa2590f6a99ccc08067a = NULL;
struct Nuitka_FrameObject *frame_519eab41ce47fa2590f6a99ccc08067a;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
NUITKA_MAY_BE_UNUSED char const *type_description_2 = NULL;
tmp_return_value = NULL;
tmp_outline_return_value_1 = NULL;
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_519eab41ce47fa2590f6a99ccc08067a, codeobj_519eab41ce47fa2590f6a99ccc08067a, module_django$utils$_os, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) );
frame_519eab41ce47fa2590f6a99ccc08067a = cache_frame_519eab41ce47fa2590f6a99ccc08067a;
// Push the new frame as the currently active one.
pushFrameStack( frame_519eab41ce47fa2590f6a99ccc08067a );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_519eab41ce47fa2590f6a99ccc08067a ) == 2 ); // Frame stack
// Framed code:
tmp_called_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_force_text );
if (unlikely( tmp_called_name_1 == NULL ))
{
tmp_called_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_force_text );
}
if ( tmp_called_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "force_text" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 62;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = par_base;
CHECK_OBJECT( tmp_args_element_name_1 );
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 62;
{
PyObject *call_args[] = { tmp_args_element_name_1 };
tmp_assign_source_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args );
}
if ( tmp_assign_source_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 62;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
{
PyObject *old = par_base;
par_base = tmp_assign_source_1;
Py_XDECREF( old );
}
// Tried code:
tmp_iter_arg_1 = par_paths;
if ( tmp_iter_arg_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "free variable '%s' referenced before assignment in enclosing scope", "paths" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 63;
type_description_1 = "oooo";
goto try_except_handler_2;
}
tmp_assign_source_3 = MAKE_ITERATOR( tmp_iter_arg_1 );
if ( tmp_assign_source_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 63;
type_description_1 = "oooo";
goto try_except_handler_2;
}
assert( tmp_listcontraction_1__$0 == NULL );
tmp_listcontraction_1__$0 = tmp_assign_source_3;
tmp_assign_source_4 = PyList_New( 0 );
assert( tmp_listcontraction_1__contraction == NULL );
tmp_listcontraction_1__contraction = tmp_assign_source_4;
MAKE_OR_REUSE_FRAME( cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2, codeobj_f795cf1a4736e33c5a5152c4aef12ba3, module_django$utils$_os, sizeof(void *)+sizeof(void *) );
frame_f795cf1a4736e33c5a5152c4aef12ba3_2 = cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2;
// Push the new frame as the currently active one.
pushFrameStack( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 ) == 2 ); // Frame stack
// Framed code:
// Tried code:
loop_start_1:;
tmp_next_source_1 = tmp_listcontraction_1__$0;
CHECK_OBJECT( tmp_next_source_1 );
tmp_assign_source_5 = ITERATOR_NEXT( tmp_next_source_1 );
if ( tmp_assign_source_5 == NULL )
{
if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() )
{
goto loop_end_1;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
type_description_2 = "oo";
exception_lineno = 63;
goto try_except_handler_3;
}
}
{
PyObject *old = tmp_listcontraction_1__iter_value_0;
tmp_listcontraction_1__iter_value_0 = tmp_assign_source_5;
Py_XDECREF( old );
}
tmp_assign_source_6 = tmp_listcontraction_1__iter_value_0;
CHECK_OBJECT( tmp_assign_source_6 );
{
PyObject *old = outline_0_var_p;
outline_0_var_p = tmp_assign_source_6;
Py_INCREF( outline_0_var_p );
Py_XDECREF( old );
}
tmp_append_list_1 = tmp_listcontraction_1__contraction;
CHECK_OBJECT( tmp_append_list_1 );
tmp_called_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_force_text );
if (unlikely( tmp_called_name_2 == NULL ))
{
tmp_called_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_force_text );
}
if ( tmp_called_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "force_text" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 63;
type_description_2 = "oo";
goto try_except_handler_3;
}
tmp_args_element_name_2 = outline_0_var_p;
CHECK_OBJECT( tmp_args_element_name_2 );
frame_f795cf1a4736e33c5a5152c4aef12ba3_2->m_frame.f_lineno = 63;
{
PyObject *call_args[] = { tmp_args_element_name_2 };
tmp_append_value_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_2, call_args );
}
if ( tmp_append_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 63;
type_description_2 = "oo";
goto try_except_handler_3;
}
assert( PyList_Check( tmp_append_list_1 ) );
tmp_res = PyList_Append( tmp_append_list_1, tmp_append_value_1 );
Py_DECREF( tmp_append_value_1 );
if ( tmp_res == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 63;
type_description_2 = "oo";
goto try_except_handler_3;
}
if ( CONSIDER_THREADING() == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 63;
type_description_2 = "oo";
goto try_except_handler_3;
}
goto loop_start_1;
loop_end_1:;
tmp_outline_return_value_1 = tmp_listcontraction_1__contraction;
CHECK_OBJECT( tmp_outline_return_value_1 );
Py_INCREF( tmp_outline_return_value_1 );
goto try_return_handler_3;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join );
return NULL;
// Return handler code:
try_return_handler_3:;
Py_XDECREF( tmp_listcontraction_1__$0 );
tmp_listcontraction_1__$0 = NULL;
Py_XDECREF( tmp_listcontraction_1__contraction );
tmp_listcontraction_1__contraction = NULL;
Py_XDECREF( tmp_listcontraction_1__iter_value_0 );
tmp_listcontraction_1__iter_value_0 = NULL;
goto frame_return_exit_2;
// Exception handler code:
try_except_handler_3:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_listcontraction_1__$0 );
tmp_listcontraction_1__$0 = NULL;
Py_XDECREF( tmp_listcontraction_1__contraction );
tmp_listcontraction_1__contraction = NULL;
Py_XDECREF( tmp_listcontraction_1__iter_value_0 );
tmp_listcontraction_1__iter_value_0 = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto frame_exception_exit_2;
// End of try:
#if 0
RESTORE_FRAME_EXCEPTION( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_2:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_2;
frame_exception_exit_2:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_f795cf1a4736e33c5a5152c4aef12ba3_2, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_f795cf1a4736e33c5a5152c4aef12ba3_2->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_f795cf1a4736e33c5a5152c4aef12ba3_2, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_f795cf1a4736e33c5a5152c4aef12ba3_2,
type_description_2,
outline_0_var_p,
par_paths
);
// Release cached frame.
if ( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 == cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2 )
{
Py_DECREF( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 );
}
cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2 = NULL;
assertFrameObject( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto nested_frame_exit_1;
frame_no_exception_1:;
goto skip_nested_handling_1;
nested_frame_exit_1:;
type_description_1 = "oooo";
goto try_except_handler_2;
skip_nested_handling_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join );
return NULL;
// Return handler code:
try_return_handler_2:;
Py_XDECREF( outline_0_var_p );
outline_0_var_p = NULL;
goto outline_result_1;
// Exception handler code:
try_except_handler_2:;
exception_keeper_type_2 = exception_type;
exception_keeper_value_2 = exception_value;
exception_keeper_tb_2 = exception_tb;
exception_keeper_lineno_2 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( outline_0_var_p );
outline_0_var_p = NULL;
// Re-raise.
exception_type = exception_keeper_type_2;
exception_value = exception_keeper_value_2;
exception_tb = exception_keeper_tb_2;
exception_lineno = exception_keeper_lineno_2;
goto outline_exception_1;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join );
return NULL;
outline_exception_1:;
exception_lineno = 63;
goto frame_exception_exit_1;
outline_result_1:;
tmp_assign_source_2 = tmp_outline_return_value_1;
{
PyObject *old = par_paths;
par_paths = tmp_assign_source_2;
Py_XDECREF( old );
}
tmp_called_name_3 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspathu );
if (unlikely( tmp_called_name_3 == NULL ))
{
tmp_called_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_abspathu );
}
if ( tmp_called_name_3 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "abspathu" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 64;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_dircall_arg1_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_join );
if (unlikely( tmp_dircall_arg1_1 == NULL ))
{
tmp_dircall_arg1_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_join );
}
if ( tmp_dircall_arg1_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "join" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 64;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_dircall_arg2_1 = PyTuple_New( 1 );
tmp_tuple_element_1 = par_base;
if ( tmp_tuple_element_1 == NULL )
{
Py_DECREF( tmp_dircall_arg2_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 64;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_tuple_element_1 );
PyTuple_SET_ITEM( tmp_dircall_arg2_1, 0, tmp_tuple_element_1 );
tmp_dircall_arg3_1 = par_paths;
CHECK_OBJECT( tmp_dircall_arg3_1 );
Py_INCREF( tmp_dircall_arg1_1 );
Py_INCREF( tmp_dircall_arg3_1 );
{
PyObject *dir_call_args[] = {tmp_dircall_arg1_1, tmp_dircall_arg2_1, tmp_dircall_arg3_1};
tmp_args_element_name_3 = impl___internal__$$$function_12_complex_call_helper_pos_star_list( dir_call_args );
}
if ( tmp_args_element_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 64;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 64;
{
PyObject *call_args[] = { tmp_args_element_name_3 };
tmp_assign_source_7 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_3, call_args );
}
Py_DECREF( tmp_args_element_name_3 );
if ( tmp_assign_source_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 64;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
assert( var_final_path == NULL );
var_final_path = tmp_assign_source_7;
tmp_called_name_4 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspathu );
if (unlikely( tmp_called_name_4 == NULL ))
{
tmp_called_name_4 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_abspathu );
}
if ( tmp_called_name_4 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "abspathu" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 65;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_4 = par_base;
if ( tmp_args_element_name_4 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 65;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 65;
{
PyObject *call_args[] = { tmp_args_element_name_4 };
tmp_assign_source_8 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_4, call_args );
}
if ( tmp_assign_source_8 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 65;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
assert( var_base_path == NULL );
var_base_path = tmp_assign_source_8;
tmp_called_name_6 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase );
if (unlikely( tmp_called_name_6 == NULL ))
{
tmp_called_name_6 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase );
}
if ( tmp_called_name_6 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_5 = var_final_path;
if ( tmp_args_element_name_5 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "final_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 73;
{
PyObject *call_args[] = { tmp_args_element_name_5 };
tmp_source_name_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_6, call_args );
}
if ( tmp_source_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_5 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_startswith );
Py_DECREF( tmp_source_name_1 );
if ( tmp_called_name_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_7 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase );
if (unlikely( tmp_called_name_7 == NULL ))
{
tmp_called_name_7 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase );
}
if ( tmp_called_name_7 == NULL )
{
Py_DECREF( tmp_called_name_5 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_left_name_1 = var_base_path;
if ( tmp_left_name_1 == NULL )
{
Py_DECREF( tmp_called_name_5 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_right_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sep );
if (unlikely( tmp_right_name_1 == NULL ))
{
tmp_right_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_sep );
}
if ( tmp_right_name_1 == NULL )
{
Py_DECREF( tmp_called_name_5 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "sep" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_7 = BINARY_OPERATION_ADD( tmp_left_name_1, tmp_right_name_1 );
if ( tmp_args_element_name_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_5 );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 73;
{
PyObject *call_args[] = { tmp_args_element_name_7 };
tmp_args_element_name_6 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_7, call_args );
}
Py_DECREF( tmp_args_element_name_7 );
if ( tmp_args_element_name_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_5 );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 73;
{
PyObject *call_args[] = { tmp_args_element_name_6 };
tmp_operand_name_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_5, call_args );
}
Py_DECREF( tmp_called_name_5 );
Py_DECREF( tmp_args_element_name_6 );
if ( tmp_operand_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_and_left_value_1 = UNARY_OPERATION( UNARY_NOT, tmp_operand_name_1 );
Py_DECREF( tmp_operand_name_1 );
if ( tmp_and_left_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 73;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_and_left_truth_1 = CHECK_IF_TRUE( tmp_and_left_value_1 );
if ( tmp_and_left_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
if ( tmp_and_left_truth_1 == 1 )
{
goto and_right_1;
}
else
{
goto and_left_1;
}
and_right_1:;
tmp_called_name_8 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase );
if (unlikely( tmp_called_name_8 == NULL ))
{
tmp_called_name_8 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase );
}
if ( tmp_called_name_8 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 74;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_8 = var_final_path;
if ( tmp_args_element_name_8 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "final_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 74;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 74;
{
PyObject *call_args[] = { tmp_args_element_name_8 };
tmp_compexpr_left_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_8, call_args );
}
if ( tmp_compexpr_left_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 74;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_9 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase );
if (unlikely( tmp_called_name_9 == NULL ))
{
tmp_called_name_9 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase );
}
if ( tmp_called_name_9 == NULL )
{
Py_DECREF( tmp_compexpr_left_1 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 74;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_9 = var_base_path;
if ( tmp_args_element_name_9 == NULL )
{
Py_DECREF( tmp_compexpr_left_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 74;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 74;
{
PyObject *call_args[] = { tmp_args_element_name_9 };
tmp_compexpr_right_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_9, call_args );
}
if ( tmp_compexpr_right_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_compexpr_left_1 );
exception_lineno = 74;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_and_left_value_2 = RICH_COMPARE_NE( tmp_compexpr_left_1, tmp_compexpr_right_1 );
Py_DECREF( tmp_compexpr_left_1 );
Py_DECREF( tmp_compexpr_right_1 );
if ( tmp_and_left_value_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 74;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_and_left_truth_2 = CHECK_IF_TRUE( tmp_and_left_value_2 );
if ( tmp_and_left_truth_2 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_and_left_value_2 );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
if ( tmp_and_left_truth_2 == 1 )
{
goto and_right_2;
}
else
{
goto and_left_2;
}
and_right_2:;
Py_DECREF( tmp_and_left_value_2 );
tmp_called_name_10 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_dirname );
if (unlikely( tmp_called_name_10 == NULL ))
{
tmp_called_name_10 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_dirname );
}
if ( tmp_called_name_10 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "dirname" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_11 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase );
if (unlikely( tmp_called_name_11 == NULL ))
{
tmp_called_name_11 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase );
}
if ( tmp_called_name_11 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_11 = var_base_path;
if ( tmp_args_element_name_11 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 75;
{
PyObject *call_args[] = { tmp_args_element_name_11 };
tmp_args_element_name_10 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_11, call_args );
}
if ( tmp_args_element_name_10 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 75;
{
PyObject *call_args[] = { tmp_args_element_name_10 };
tmp_compexpr_left_2 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_10, call_args );
}
Py_DECREF( tmp_args_element_name_10 );
if ( tmp_compexpr_left_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_12 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase );
if (unlikely( tmp_called_name_12 == NULL ))
{
tmp_called_name_12 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase );
}
if ( tmp_called_name_12 == NULL )
{
Py_DECREF( tmp_compexpr_left_2 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_12 = var_base_path;
if ( tmp_args_element_name_12 == NULL )
{
Py_DECREF( tmp_compexpr_left_2 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 75;
{
PyObject *call_args[] = { tmp_args_element_name_12 };
tmp_compexpr_right_2 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_12, call_args );
}
if ( tmp_compexpr_right_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_compexpr_left_2 );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_and_right_value_2 = RICH_COMPARE_NE( tmp_compexpr_left_2, tmp_compexpr_right_2 );
Py_DECREF( tmp_compexpr_left_2 );
Py_DECREF( tmp_compexpr_right_2 );
if ( tmp_and_right_value_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_and_right_value_1 = tmp_and_right_value_2;
goto and_end_2;
and_left_2:;
tmp_and_right_value_1 = tmp_and_left_value_2;
and_end_2:;
tmp_cond_value_1 = tmp_and_right_value_1;
goto and_end_1;
and_left_1:;
Py_INCREF( tmp_and_left_value_1 );
tmp_cond_value_1 = tmp_and_left_value_1;
and_end_1:;
tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_1 );
exception_lineno = 75;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_called_name_13 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_SuspiciousFileOperation );
if (unlikely( tmp_called_name_13 == NULL ))
{
tmp_called_name_13 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_SuspiciousFileOperation );
}
if ( tmp_called_name_13 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "SuspiciousFileOperation" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 76;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_source_name_2 = const_str_digest_e333b5c27f64858ace2064722679d143;
tmp_called_name_14 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_format );
assert( tmp_called_name_14 != NULL );
tmp_args_element_name_14 = var_final_path;
if ( tmp_args_element_name_14 == NULL )
{
Py_DECREF( tmp_called_name_14 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "final_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 78;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_15 = var_base_path;
if ( tmp_args_element_name_15 == NULL )
{
Py_DECREF( tmp_called_name_14 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 78;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 77;
{
PyObject *call_args[] = { tmp_args_element_name_14, tmp_args_element_name_15 };
tmp_args_element_name_13 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_14, call_args );
}
Py_DECREF( tmp_called_name_14 );
if ( tmp_args_element_name_13 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 77;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 76;
{
PyObject *call_args[] = { tmp_args_element_name_13 };
tmp_raise_type_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_13, call_args );
}
Py_DECREF( tmp_args_element_name_13 );
if ( tmp_raise_type_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 76;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
exception_type = tmp_raise_type_1;
exception_lineno = 76;
RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooo";
goto frame_exception_exit_1;
branch_no_1:;
tmp_return_value = var_final_path;
if ( tmp_return_value == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "final_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 79;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_return_value );
goto frame_return_exit_1;
#if 0
RESTORE_FRAME_EXCEPTION( frame_519eab41ce47fa2590f6a99ccc08067a );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_2;
frame_return_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_519eab41ce47fa2590f6a99ccc08067a );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_519eab41ce47fa2590f6a99ccc08067a );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_519eab41ce47fa2590f6a99ccc08067a, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_519eab41ce47fa2590f6a99ccc08067a->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_519eab41ce47fa2590f6a99ccc08067a, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_519eab41ce47fa2590f6a99ccc08067a,
type_description_1,
par_base,
par_paths,
var_final_path,
var_base_path
);
// Release cached frame.
if ( frame_519eab41ce47fa2590f6a99ccc08067a == cache_frame_519eab41ce47fa2590f6a99ccc08067a )
{
Py_DECREF( frame_519eab41ce47fa2590f6a99ccc08067a );
}
cache_frame_519eab41ce47fa2590f6a99ccc08067a = NULL;
assertFrameObject( frame_519eab41ce47fa2590f6a99ccc08067a );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_2:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_base );
par_base = NULL;
Py_XDECREF( par_paths );
par_paths = NULL;
Py_XDECREF( var_final_path );
var_final_path = NULL;
Py_XDECREF( var_base_path );
var_base_path = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_3 = exception_type;
exception_keeper_value_3 = exception_value;
exception_keeper_tb_3 = exception_tb;
exception_keeper_lineno_3 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( par_base );
par_base = NULL;
Py_XDECREF( par_paths );
par_paths = NULL;
Py_XDECREF( var_final_path );
var_final_path = NULL;
Py_XDECREF( var_base_path );
var_base_path = NULL;
// Re-raise.
exception_type = exception_keeper_type_3;
exception_value = exception_keeper_value_3;
exception_tb = exception_keeper_tb_3;
exception_lineno = exception_keeper_lineno_3;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
static PyObject *impl_django$utils$_os$$$function_5_symlinks_supported( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *var_tmpdir = NULL;
PyObject *var_original_path = NULL;
PyObject *var_symlink_path = NULL;
PyObject *var_supported = NULL;
PyObject *tmp_try_except_1__unhandled_indicator = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *exception_keeper_type_2;
PyObject *exception_keeper_value_2;
PyTracebackObject *exception_keeper_tb_2;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2;
PyObject *exception_keeper_type_3;
PyObject *exception_keeper_value_3;
PyTracebackObject *exception_keeper_tb_3;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3;
PyObject *exception_keeper_type_4;
PyObject *exception_keeper_value_4;
PyTracebackObject *exception_keeper_tb_4;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_4;
PyObject *exception_keeper_type_5;
PyObject *exception_keeper_value_5;
PyTracebackObject *exception_keeper_tb_5;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_5;
PyObject *exception_keeper_type_6;
PyObject *exception_keeper_value_6;
PyTracebackObject *exception_keeper_tb_6;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_6;
PyObject *exception_preserved_type_1;
PyObject *exception_preserved_value_1;
PyTracebackObject *exception_preserved_tb_1;
PyObject *exception_preserved_type_2;
PyObject *exception_preserved_value_2;
PyTracebackObject *exception_preserved_tb_2;
PyObject *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_args_element_name_3;
PyObject *tmp_args_element_name_4;
PyObject *tmp_args_element_name_5;
PyObject *tmp_args_element_name_6;
PyObject *tmp_args_element_name_7;
PyObject *tmp_args_element_name_8;
PyObject *tmp_args_element_name_9;
PyObject *tmp_args_element_name_10;
PyObject *tmp_args_element_name_11;
PyObject *tmp_args_element_name_12;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_assign_source_3;
PyObject *tmp_assign_source_4;
PyObject *tmp_assign_source_5;
PyObject *tmp_assign_source_6;
PyObject *tmp_assign_source_7;
PyObject *tmp_called_instance_1;
PyObject *tmp_called_name_1;
PyObject *tmp_called_name_2;
PyObject *tmp_called_name_3;
PyObject *tmp_called_name_4;
PyObject *tmp_called_name_5;
PyObject *tmp_called_name_6;
PyObject *tmp_called_name_7;
PyObject *tmp_called_name_8;
PyObject *tmp_called_name_9;
PyObject *tmp_compare_left_1;
PyObject *tmp_compare_left_2;
PyObject *tmp_compare_right_1;
PyObject *tmp_compare_right_2;
int tmp_exc_match_exception_match_1;
bool tmp_is_1;
bool tmp_result;
PyObject *tmp_return_value;
PyObject *tmp_source_name_1;
PyObject *tmp_source_name_2;
PyObject *tmp_source_name_3;
PyObject *tmp_source_name_4;
PyObject *tmp_source_name_5;
PyObject *tmp_source_name_6;
PyObject *tmp_source_name_7;
PyObject *tmp_source_name_8;
PyObject *tmp_source_name_9;
PyObject *tmp_source_name_10;
PyObject *tmp_source_name_11;
PyObject *tmp_tuple_element_1;
NUITKA_MAY_BE_UNUSED PyObject *tmp_unused;
static struct Nuitka_FrameObject *cache_frame_7f1d67953d1486ada0ef5501b0312cae = NULL;
struct Nuitka_FrameObject *frame_7f1d67953d1486ada0ef5501b0312cae;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_7f1d67953d1486ada0ef5501b0312cae, codeobj_7f1d67953d1486ada0ef5501b0312cae, module_django$utils$_os, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) );
frame_7f1d67953d1486ada0ef5501b0312cae = cache_frame_7f1d67953d1486ada0ef5501b0312cae;
// Push the new frame as the currently active one.
pushFrameStack( frame_7f1d67953d1486ada0ef5501b0312cae );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_7f1d67953d1486ada0ef5501b0312cae ) == 2 ); // Frame stack
// Framed code:
tmp_called_instance_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_tempfile );
if (unlikely( tmp_called_instance_1 == NULL ))
{
tmp_called_instance_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_tempfile );
}
if ( tmp_called_instance_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "tempfile" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 88;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 88;
tmp_assign_source_1 = CALL_METHOD_NO_ARGS( tmp_called_instance_1, const_str_plain_mkdtemp );
if ( tmp_assign_source_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 88;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
assert( var_tmpdir == NULL );
var_tmpdir = tmp_assign_source_1;
tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_2 == NULL ))
{
tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 89;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_source_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_path );
if ( tmp_source_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 89;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_join );
Py_DECREF( tmp_source_name_1 );
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 89;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = var_tmpdir;
if ( tmp_args_element_name_1 == NULL )
{
Py_DECREF( tmp_called_name_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "tmpdir" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 89;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_2 = const_str_plain_original;
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 89;
{
PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 };
tmp_assign_source_2 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args );
}
Py_DECREF( tmp_called_name_1 );
if ( tmp_assign_source_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 89;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
assert( var_original_path == NULL );
var_original_path = tmp_assign_source_2;
tmp_source_name_4 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_4 == NULL ))
{
tmp_source_name_4 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_4 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 90;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_source_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_4, const_str_plain_path );
if ( tmp_source_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 90;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_2 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_join );
Py_DECREF( tmp_source_name_3 );
if ( tmp_called_name_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 90;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_3 = var_tmpdir;
if ( tmp_args_element_name_3 == NULL )
{
Py_DECREF( tmp_called_name_2 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "tmpdir" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 90;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_4 = const_str_plain_symlink;
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 90;
{
PyObject *call_args[] = { tmp_args_element_name_3, tmp_args_element_name_4 };
tmp_assign_source_3 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_2, call_args );
}
Py_DECREF( tmp_called_name_2 );
if ( tmp_assign_source_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 90;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
assert( var_symlink_path == NULL );
var_symlink_path = tmp_assign_source_3;
tmp_source_name_5 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_5 == NULL ))
{
tmp_source_name_5 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_5 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 91;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_5, const_str_plain_makedirs );
if ( tmp_called_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 91;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_5 = var_original_path;
if ( tmp_args_element_name_5 == NULL )
{
Py_DECREF( tmp_called_name_3 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "original_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 91;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 91;
{
PyObject *call_args[] = { tmp_args_element_name_5 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_3, call_args );
}
Py_DECREF( tmp_called_name_3 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 91;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_assign_source_4 = Py_True;
assert( tmp_try_except_1__unhandled_indicator == NULL );
Py_INCREF( tmp_assign_source_4 );
tmp_try_except_1__unhandled_indicator = tmp_assign_source_4;
// Tried code:
// Tried code:
// Tried code:
tmp_source_name_6 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_6 == NULL ))
{
tmp_source_name_6 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_6 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 93;
type_description_1 = "oooo";
goto try_except_handler_4;
}
tmp_called_name_4 = LOOKUP_ATTRIBUTE( tmp_source_name_6, const_str_plain_symlink );
if ( tmp_called_name_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 93;
type_description_1 = "oooo";
goto try_except_handler_4;
}
tmp_args_element_name_6 = var_original_path;
if ( tmp_args_element_name_6 == NULL )
{
Py_DECREF( tmp_called_name_4 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "original_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 93;
type_description_1 = "oooo";
goto try_except_handler_4;
}
tmp_args_element_name_7 = var_symlink_path;
if ( tmp_args_element_name_7 == NULL )
{
Py_DECREF( tmp_called_name_4 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "symlink_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 93;
type_description_1 = "oooo";
goto try_except_handler_4;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 93;
{
PyObject *call_args[] = { tmp_args_element_name_6, tmp_args_element_name_7 };
tmp_unused = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_4, call_args );
}
Py_DECREF( tmp_called_name_4 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 93;
type_description_1 = "oooo";
goto try_except_handler_4;
}
Py_DECREF( tmp_unused );
tmp_assign_source_5 = Py_True;
assert( var_supported == NULL );
Py_INCREF( tmp_assign_source_5 );
var_supported = tmp_assign_source_5;
goto try_end_1;
// Exception handler code:
try_except_handler_4:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
tmp_assign_source_6 = Py_False;
{
PyObject *old = tmp_try_except_1__unhandled_indicator;
tmp_try_except_1__unhandled_indicator = tmp_assign_source_6;
Py_INCREF( tmp_try_except_1__unhandled_indicator );
Py_XDECREF( old );
}
// Preserve existing published exception.
exception_preserved_type_1 = PyThreadState_GET()->exc_type;
Py_XINCREF( exception_preserved_type_1 );
exception_preserved_value_1 = PyThreadState_GET()->exc_value;
Py_XINCREF( exception_preserved_value_1 );
exception_preserved_tb_1 = (PyTracebackObject *)PyThreadState_GET()->exc_traceback;
Py_XINCREF( exception_preserved_tb_1 );
if ( exception_keeper_tb_1 == NULL )
{
exception_keeper_tb_1 = MAKE_TRACEBACK( frame_7f1d67953d1486ada0ef5501b0312cae, exception_keeper_lineno_1 );
}
else if ( exception_keeper_lineno_1 != 0 )
{
exception_keeper_tb_1 = ADD_TRACEBACK( exception_keeper_tb_1, frame_7f1d67953d1486ada0ef5501b0312cae, exception_keeper_lineno_1 );
}
NORMALIZE_EXCEPTION( &exception_keeper_type_1, &exception_keeper_value_1, &exception_keeper_tb_1 );
PyException_SetTraceback( exception_keeper_value_1, (PyObject *)exception_keeper_tb_1 );
PUBLISH_EXCEPTION( &exception_keeper_type_1, &exception_keeper_value_1, &exception_keeper_tb_1 );
// Tried code:
tmp_compare_left_1 = PyThreadState_GET()->exc_type;
tmp_compare_right_1 = PyTuple_New( 3 );
tmp_tuple_element_1 = PyExc_OSError;
Py_INCREF( tmp_tuple_element_1 );
PyTuple_SET_ITEM( tmp_compare_right_1, 0, tmp_tuple_element_1 );
tmp_tuple_element_1 = PyExc_NotImplementedError;
Py_INCREF( tmp_tuple_element_1 );
PyTuple_SET_ITEM( tmp_compare_right_1, 1, tmp_tuple_element_1 );
tmp_tuple_element_1 = PyExc_AttributeError;
Py_INCREF( tmp_tuple_element_1 );
PyTuple_SET_ITEM( tmp_compare_right_1, 2, tmp_tuple_element_1 );
tmp_exc_match_exception_match_1 = EXCEPTION_MATCH_BOOL( tmp_compare_left_1, tmp_compare_right_1 );
if ( tmp_exc_match_exception_match_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_compare_right_1 );
exception_lineno = 95;
type_description_1 = "oooo";
goto try_except_handler_5;
}
Py_DECREF( tmp_compare_right_1 );
if ( tmp_exc_match_exception_match_1 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_assign_source_7 = Py_False;
assert( var_supported == NULL );
Py_INCREF( tmp_assign_source_7 );
var_supported = tmp_assign_source_7;
goto branch_end_1;
branch_no_1:;
tmp_result = RERAISE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
if (unlikely( tmp_result == false ))
{
exception_lineno = 92;
}
if (exception_tb && exception_tb->tb_frame == &frame_7f1d67953d1486ada0ef5501b0312cae->m_frame) frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = exception_tb->tb_lineno;
type_description_1 = "oooo";
goto try_except_handler_5;
branch_end_1:;
goto try_end_2;
// Exception handler code:
try_except_handler_5:;
exception_keeper_type_2 = exception_type;
exception_keeper_value_2 = exception_value;
exception_keeper_tb_2 = exception_tb;
exception_keeper_lineno_2 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
// Restore previous exception.
SET_CURRENT_EXCEPTION( exception_preserved_type_1, exception_preserved_value_1, exception_preserved_tb_1 );
// Re-raise.
exception_type = exception_keeper_type_2;
exception_value = exception_keeper_value_2;
exception_tb = exception_keeper_tb_2;
exception_lineno = exception_keeper_lineno_2;
goto try_except_handler_3;
// End of try:
try_end_2:;
// Restore previous exception.
SET_CURRENT_EXCEPTION( exception_preserved_type_1, exception_preserved_value_1, exception_preserved_tb_1 );
goto try_end_1;
// exception handler codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_5_symlinks_supported );
return NULL;
// End of try:
try_end_1:;
tmp_compare_left_2 = tmp_try_except_1__unhandled_indicator;
CHECK_OBJECT( tmp_compare_left_2 );
tmp_compare_right_2 = Py_True;
tmp_is_1 = ( tmp_compare_left_2 == tmp_compare_right_2 );
if ( tmp_is_1 )
{
goto branch_yes_2;
}
else
{
goto branch_no_2;
}
branch_yes_2:;
tmp_source_name_7 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_7 == NULL ))
{
tmp_source_name_7 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_7 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 98;
type_description_1 = "oooo";
goto try_except_handler_3;
}
tmp_called_name_5 = LOOKUP_ATTRIBUTE( tmp_source_name_7, const_str_plain_remove );
if ( tmp_called_name_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 98;
type_description_1 = "oooo";
goto try_except_handler_3;
}
tmp_args_element_name_8 = var_symlink_path;
if ( tmp_args_element_name_8 == NULL )
{
Py_DECREF( tmp_called_name_5 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "symlink_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 98;
type_description_1 = "oooo";
goto try_except_handler_3;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 98;
{
PyObject *call_args[] = { tmp_args_element_name_8 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_5, call_args );
}
Py_DECREF( tmp_called_name_5 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 98;
type_description_1 = "oooo";
goto try_except_handler_3;
}
Py_DECREF( tmp_unused );
branch_no_2:;
goto try_end_3;
// Exception handler code:
try_except_handler_3:;
exception_keeper_type_3 = exception_type;
exception_keeper_value_3 = exception_value;
exception_keeper_tb_3 = exception_tb;
exception_keeper_lineno_3 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_try_except_1__unhandled_indicator );
tmp_try_except_1__unhandled_indicator = NULL;
// Re-raise.
exception_type = exception_keeper_type_3;
exception_value = exception_keeper_value_3;
exception_tb = exception_keeper_tb_3;
exception_lineno = exception_keeper_lineno_3;
goto try_except_handler_2;
// End of try:
try_end_3:;
goto try_end_4;
// Exception handler code:
try_except_handler_2:;
exception_keeper_type_4 = exception_type;
exception_keeper_value_4 = exception_value;
exception_keeper_tb_4 = exception_tb;
exception_keeper_lineno_4 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
// Preserve existing published exception.
exception_preserved_type_2 = PyThreadState_GET()->exc_type;
Py_XINCREF( exception_preserved_type_2 );
exception_preserved_value_2 = PyThreadState_GET()->exc_value;
Py_XINCREF( exception_preserved_value_2 );
exception_preserved_tb_2 = (PyTracebackObject *)PyThreadState_GET()->exc_traceback;
Py_XINCREF( exception_preserved_tb_2 );
if ( exception_keeper_tb_4 == NULL )
{
exception_keeper_tb_4 = MAKE_TRACEBACK( frame_7f1d67953d1486ada0ef5501b0312cae, exception_keeper_lineno_4 );
}
else if ( exception_keeper_lineno_4 != 0 )
{
exception_keeper_tb_4 = ADD_TRACEBACK( exception_keeper_tb_4, frame_7f1d67953d1486ada0ef5501b0312cae, exception_keeper_lineno_4 );
}
NORMALIZE_EXCEPTION( &exception_keeper_type_4, &exception_keeper_value_4, &exception_keeper_tb_4 );
PyException_SetTraceback( exception_keeper_value_4, (PyObject *)exception_keeper_tb_4 );
PUBLISH_EXCEPTION( &exception_keeper_type_4, &exception_keeper_value_4, &exception_keeper_tb_4 );
// Tried code:
tmp_source_name_8 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_8 == NULL ))
{
tmp_source_name_8 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_8 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 100;
type_description_1 = "oooo";
goto try_except_handler_6;
}
tmp_called_name_6 = LOOKUP_ATTRIBUTE( tmp_source_name_8, const_str_plain_rmdir );
if ( tmp_called_name_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 100;
type_description_1 = "oooo";
goto try_except_handler_6;
}
tmp_args_element_name_9 = var_original_path;
if ( tmp_args_element_name_9 == NULL )
{
Py_DECREF( tmp_called_name_6 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "original_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 100;
type_description_1 = "oooo";
goto try_except_handler_6;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 100;
{
PyObject *call_args[] = { tmp_args_element_name_9 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_6, call_args );
}
Py_DECREF( tmp_called_name_6 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 100;
type_description_1 = "oooo";
goto try_except_handler_6;
}
Py_DECREF( tmp_unused );
tmp_source_name_9 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_9 == NULL ))
{
tmp_source_name_9 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_9 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 101;
type_description_1 = "oooo";
goto try_except_handler_6;
}
tmp_called_name_7 = LOOKUP_ATTRIBUTE( tmp_source_name_9, const_str_plain_rmdir );
if ( tmp_called_name_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 101;
type_description_1 = "oooo";
goto try_except_handler_6;
}
tmp_args_element_name_10 = var_tmpdir;
if ( tmp_args_element_name_10 == NULL )
{
Py_DECREF( tmp_called_name_7 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "tmpdir" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 101;
type_description_1 = "oooo";
goto try_except_handler_6;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 101;
{
PyObject *call_args[] = { tmp_args_element_name_10 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_7, call_args );
}
Py_DECREF( tmp_called_name_7 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 101;
type_description_1 = "oooo";
goto try_except_handler_6;
}
Py_DECREF( tmp_unused );
tmp_return_value = var_supported;
if ( tmp_return_value == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "supported" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 102;
type_description_1 = "oooo";
goto try_except_handler_6;
}
Py_INCREF( tmp_return_value );
goto try_return_handler_6;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_5_symlinks_supported );
return NULL;
// Return handler code:
try_return_handler_6:;
// Restore previous exception.
SET_CURRENT_EXCEPTION( exception_preserved_type_2, exception_preserved_value_2, exception_preserved_tb_2 );
goto frame_return_exit_1;
// Exception handler code:
try_except_handler_6:;
exception_keeper_type_5 = exception_type;
exception_keeper_value_5 = exception_value;
exception_keeper_tb_5 = exception_tb;
exception_keeper_lineno_5 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
// Restore previous exception.
SET_CURRENT_EXCEPTION( exception_preserved_type_2, exception_preserved_value_2, exception_preserved_tb_2 );
// Re-raise.
exception_type = exception_keeper_type_5;
exception_value = exception_keeper_value_5;
exception_tb = exception_keeper_tb_5;
exception_lineno = exception_keeper_lineno_5;
goto frame_exception_exit_1;
// End of try:
// End of try:
try_end_4:;
Py_XDECREF( tmp_try_except_1__unhandled_indicator );
tmp_try_except_1__unhandled_indicator = NULL;
tmp_source_name_10 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_10 == NULL ))
{
tmp_source_name_10 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_10 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 100;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_8 = LOOKUP_ATTRIBUTE( tmp_source_name_10, const_str_plain_rmdir );
if ( tmp_called_name_8 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 100;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_11 = var_original_path;
if ( tmp_args_element_name_11 == NULL )
{
Py_DECREF( tmp_called_name_8 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "original_path" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 100;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 100;
{
PyObject *call_args[] = { tmp_args_element_name_11 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_8, call_args );
}
Py_DECREF( tmp_called_name_8 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 100;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_11 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_11 == NULL ))
{
tmp_source_name_11 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_11 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 101;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_called_name_9 = LOOKUP_ATTRIBUTE( tmp_source_name_11, const_str_plain_rmdir );
if ( tmp_called_name_9 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 101;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_12 = var_tmpdir;
if ( tmp_args_element_name_12 == NULL )
{
Py_DECREF( tmp_called_name_9 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "tmpdir" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 101;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 101;
{
PyObject *call_args[] = { tmp_args_element_name_12 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_9, call_args );
}
Py_DECREF( tmp_called_name_9 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 101;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_return_value = var_supported;
if ( tmp_return_value == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "supported" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 102;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_return_value );
goto frame_return_exit_1;
#if 1
RESTORE_FRAME_EXCEPTION( frame_7f1d67953d1486ada0ef5501b0312cae );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_1:;
#if 1
RESTORE_FRAME_EXCEPTION( frame_7f1d67953d1486ada0ef5501b0312cae );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 1
RESTORE_FRAME_EXCEPTION( frame_7f1d67953d1486ada0ef5501b0312cae );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_7f1d67953d1486ada0ef5501b0312cae, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_7f1d67953d1486ada0ef5501b0312cae->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_7f1d67953d1486ada0ef5501b0312cae, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_7f1d67953d1486ada0ef5501b0312cae,
type_description_1,
var_tmpdir,
var_original_path,
var_symlink_path,
var_supported
);
// Release cached frame.
if ( frame_7f1d67953d1486ada0ef5501b0312cae == cache_frame_7f1d67953d1486ada0ef5501b0312cae )
{
Py_DECREF( frame_7f1d67953d1486ada0ef5501b0312cae );
}
cache_frame_7f1d67953d1486ada0ef5501b0312cae = NULL;
assertFrameObject( frame_7f1d67953d1486ada0ef5501b0312cae );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_5_symlinks_supported );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( var_tmpdir );
var_tmpdir = NULL;
Py_XDECREF( var_original_path );
var_original_path = NULL;
Py_XDECREF( var_symlink_path );
var_symlink_path = NULL;
Py_XDECREF( var_supported );
var_supported = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_6 = exception_type;
exception_keeper_value_6 = exception_value;
exception_keeper_tb_6 = exception_tb;
exception_keeper_lineno_6 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( var_tmpdir );
var_tmpdir = NULL;
Py_XDECREF( var_original_path );
var_original_path = NULL;
Py_XDECREF( var_symlink_path );
var_symlink_path = NULL;
Py_XDECREF( var_supported );
var_supported = NULL;
// Re-raise.
exception_type = exception_keeper_type_6;
exception_value = exception_keeper_value_6;
exception_tb = exception_keeper_tb_6;
exception_lineno = exception_keeper_lineno_6;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_5_symlinks_supported );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_1_abspathu( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_django$utils$_os$$$function_1_abspathu,
const_str_plain_abspathu,
#if PYTHON_VERSION >= 330
NULL,
#endif
codeobj_8338c887cffee3f6624948b93fdb5cad,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_django$utils$_os,
const_str_digest_d92a79f74db4468ebeba34a6c933cb11,
0
);
return (PyObject *)result;
}
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_2_upath( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_django$utils$_os$$$function_2_upath,
const_str_plain_upath,
#if PYTHON_VERSION >= 330
NULL,
#endif
codeobj_786e20e096923522b138dc8044ece5a9,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_django$utils$_os,
const_str_digest_e029ae267a3a9a3ffb4d22037d50a89e,
0
);
return (PyObject *)result;
}
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_3_npath( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_django$utils$_os$$$function_3_npath,
const_str_plain_npath,
#if PYTHON_VERSION >= 330
NULL,
#endif
codeobj_f5eb817954879f203f472ef76832ad97,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_django$utils$_os,
const_str_digest_5c892843b642786d8376f7cd7a9ec574,
0
);
return (PyObject *)result;
}
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_4_safe_join( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_django$utils$_os$$$function_4_safe_join,
const_str_plain_safe_join,
#if PYTHON_VERSION >= 330
NULL,
#endif
codeobj_519eab41ce47fa2590f6a99ccc08067a,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_django$utils$_os,
const_str_digest_02c3b3e14ee51a74c880c9a2312b4dc8,
0
);
return (PyObject *)result;
}
static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_5_symlinks_supported( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_django$utils$_os$$$function_5_symlinks_supported,
const_str_plain_symlinks_supported,
#if PYTHON_VERSION >= 330
NULL,
#endif
codeobj_7f1d67953d1486ada0ef5501b0312cae,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_django$utils$_os,
const_str_digest_b3b92bc7aa9804266ff219682e3d0112,
0
);
return (PyObject *)result;
}
#if PYTHON_VERSION >= 300
static struct PyModuleDef mdef_django$utils$_os =
{
PyModuleDef_HEAD_INIT,
"django.utils._os", /* m_name */
NULL, /* m_doc */
-1, /* m_size */
NULL, /* m_methods */
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
#endif
#if PYTHON_VERSION >= 300
extern PyObject *metapath_based_loader;
#endif
#if PYTHON_VERSION >= 330
extern PyObject *const_str_plain___loader__;
#endif
extern void _initCompiledCellType();
extern void _initCompiledGeneratorType();
extern void _initCompiledFunctionType();
extern void _initCompiledMethodType();
extern void _initCompiledFrameType();
#if PYTHON_VERSION >= 350
extern void _initCompiledCoroutineTypes();
#endif
#if PYTHON_VERSION >= 360
extern void _initCompiledAsyncgenTypes();
#endif
// The exported interface to CPython. On import of the module, this function
// gets called. It has to have an exact function name, in cases it's a shared
// library export. This is hidden behind the MOD_INIT_DECL.
MOD_INIT_DECL( django$utils$_os )
{
#if defined(_NUITKA_EXE) || PYTHON_VERSION >= 300
static bool _init_done = false;
// Modules might be imported repeatedly, which is to be ignored.
if ( _init_done )
{
return MOD_RETURN_VALUE( module_django$utils$_os );
}
else
{
_init_done = true;
}
#endif
#ifdef _NUITKA_MODULE
// In case of a stand alone extension module, need to call initialization
// the init here because that's the first and only time we are going to get
// called here.
// Initialize the constant values used.
_initBuiltinModule();
createGlobalConstants();
/* Initialize the compiled types of Nuitka. */
_initCompiledCellType();
_initCompiledGeneratorType();
_initCompiledFunctionType();
_initCompiledMethodType();
_initCompiledFrameType();
#if PYTHON_VERSION >= 350
_initCompiledCoroutineTypes();
#endif
#if PYTHON_VERSION >= 360
_initCompiledAsyncgenTypes();
#endif
#if PYTHON_VERSION < 300
_initSlotCompare();
#endif
#if PYTHON_VERSION >= 270
_initSlotIternext();
#endif
patchBuiltinModule();
patchTypeComparison();
// Enable meta path based loader if not already done.
setupMetaPathBasedLoader();
#if PYTHON_VERSION >= 300
patchInspectModule();
#endif
#endif
/* The constants only used by this module are created now. */
#ifdef _NUITKA_TRACE
puts("django.utils._os: Calling createModuleConstants().");
#endif
createModuleConstants();
/* The code objects used by this module are created now. */
#ifdef _NUITKA_TRACE
puts("django.utils._os: Calling createModuleCodeObjects().");
#endif
createModuleCodeObjects();
// puts( "in initdjango$utils$_os" );
// Create the module object first. There are no methods initially, all are
// added dynamically in actual code only. Also no "__doc__" is initially
// set at this time, as it could not contain NUL characters this way, they
// are instead set in early module code. No "self" for modules, we have no
// use for it.
#if PYTHON_VERSION < 300
module_django$utils$_os = Py_InitModule4(
"django.utils._os", // Module Name
NULL, // No methods initially, all are added
// dynamically in actual module code only.
NULL, // No __doc__ is initially set, as it could
// not contain NUL this way, added early in
// actual code.
NULL, // No self for modules, we don't use it.
PYTHON_API_VERSION
);
#else
module_django$utils$_os = PyModule_Create( &mdef_django$utils$_os );
#endif
moduledict_django$utils$_os = MODULE_DICT( module_django$utils$_os );
CHECK_OBJECT( module_django$utils$_os );
// Seems to work for Python2.7 out of the box, but for Python3, the module
// doesn't automatically enter "sys.modules", so do it manually.
#if PYTHON_VERSION >= 300
{
int r = PyObject_SetItem( PySys_GetObject( (char *)"modules" ), const_str_digest_842dfd4744c6e20ce39943a1591eb59d, module_django$utils$_os );
assert( r != -1 );
}
#endif
// For deep importing of a module we need to have "__builtins__", so we set
// it ourselves in the same way than CPython does. Note: This must be done
// before the frame object is allocated, or else it may fail.
if ( GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___builtins__ ) == NULL )
{
PyObject *value = (PyObject *)builtin_module;
// Check if main module, not a dict then but the module itself.
#if !defined(_NUITKA_EXE) || !0
value = PyModule_GetDict( value );
#endif
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___builtins__, value );
}
#if PYTHON_VERSION >= 330
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___loader__, metapath_based_loader );
#endif
// Temp variables if any
PyObject *tmp_import_from_1__module = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_assign_source_3;
PyObject *tmp_assign_source_4;
PyObject *tmp_assign_source_5;
PyObject *tmp_assign_source_6;
PyObject *tmp_assign_source_7;
PyObject *tmp_assign_source_8;
PyObject *tmp_assign_source_9;
PyObject *tmp_assign_source_10;
PyObject *tmp_assign_source_11;
PyObject *tmp_assign_source_12;
PyObject *tmp_assign_source_13;
PyObject *tmp_assign_source_14;
PyObject *tmp_assign_source_15;
PyObject *tmp_assign_source_16;
PyObject *tmp_assign_source_17;
PyObject *tmp_assign_source_18;
PyObject *tmp_assign_source_19;
PyObject *tmp_assign_source_20;
PyObject *tmp_assign_source_21;
PyObject *tmp_assign_source_22;
PyObject *tmp_assign_source_23;
PyObject *tmp_assign_source_24;
PyObject *tmp_assign_source_25;
PyObject *tmp_assign_source_26;
PyObject *tmp_assign_source_27;
PyObject *tmp_assign_source_28;
PyObject *tmp_called_instance_1;
PyObject *tmp_called_instance_2;
PyObject *tmp_called_name_1;
PyObject *tmp_compexpr_left_1;
PyObject *tmp_compexpr_right_1;
int tmp_cond_truth_1;
int tmp_cond_truth_2;
PyObject *tmp_cond_value_1;
PyObject *tmp_cond_value_2;
PyObject *tmp_fromlist_name_1;
PyObject *tmp_fromlist_name_2;
PyObject *tmp_fromlist_name_3;
PyObject *tmp_fromlist_name_4;
PyObject *tmp_fromlist_name_5;
PyObject *tmp_fromlist_name_6;
PyObject *tmp_fromlist_name_7;
PyObject *tmp_globals_name_1;
PyObject *tmp_globals_name_2;
PyObject *tmp_globals_name_3;
PyObject *tmp_globals_name_4;
PyObject *tmp_globals_name_5;
PyObject *tmp_globals_name_6;
PyObject *tmp_globals_name_7;
PyObject *tmp_import_name_from_1;
PyObject *tmp_import_name_from_2;
PyObject *tmp_import_name_from_3;
PyObject *tmp_import_name_from_4;
PyObject *tmp_import_name_from_5;
PyObject *tmp_import_name_from_6;
PyObject *tmp_import_name_from_7;
PyObject *tmp_import_name_from_8;
PyObject *tmp_import_name_from_9;
PyObject *tmp_import_name_from_10;
PyObject *tmp_import_name_from_11;
PyObject *tmp_level_name_1;
PyObject *tmp_level_name_2;
PyObject *tmp_level_name_3;
PyObject *tmp_level_name_4;
PyObject *tmp_level_name_5;
PyObject *tmp_level_name_6;
PyObject *tmp_level_name_7;
PyObject *tmp_locals_name_1;
PyObject *tmp_locals_name_2;
PyObject *tmp_locals_name_3;
PyObject *tmp_locals_name_4;
PyObject *tmp_locals_name_5;
PyObject *tmp_locals_name_6;
PyObject *tmp_locals_name_7;
PyObject *tmp_name_name_1;
PyObject *tmp_name_name_2;
PyObject *tmp_name_name_3;
PyObject *tmp_name_name_4;
PyObject *tmp_name_name_5;
PyObject *tmp_name_name_6;
PyObject *tmp_name_name_7;
int tmp_or_left_truth_1;
int tmp_or_left_truth_2;
PyObject *tmp_or_left_value_1;
PyObject *tmp_or_left_value_2;
PyObject *tmp_or_right_value_1;
PyObject *tmp_or_right_value_2;
PyObject *tmp_source_name_1;
PyObject *tmp_source_name_2;
PyObject *tmp_source_name_3;
struct Nuitka_FrameObject *frame_e3f2225c4277cee0cd5878c353c5494a;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
// Module code.
tmp_assign_source_1 = Py_None;
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1 );
tmp_assign_source_2 = module_filename_obj;
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2 );
tmp_assign_source_3 = metapath_based_loader;
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___loader__, tmp_assign_source_3 );
// Frame without reuse.
frame_e3f2225c4277cee0cd5878c353c5494a = MAKE_MODULE_FRAME( codeobj_e3f2225c4277cee0cd5878c353c5494a, module_django$utils$_os );
// Push the new frame as the currently active one, and we should be exclusively
// owning it.
pushFrameStack( frame_e3f2225c4277cee0cd5878c353c5494a );
assert( Py_REFCNT( frame_e3f2225c4277cee0cd5878c353c5494a ) == 2 );
// Framed code:
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 1;
{
PyObject *module = PyImport_ImportModule("importlib._bootstrap");
if (likely( module != NULL ))
{
tmp_called_name_1 = PyObject_GetAttr( module, const_str_plain_ModuleSpec );
}
else
{
tmp_called_name_1 = NULL;
}
}
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 1;
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = const_str_digest_842dfd4744c6e20ce39943a1591eb59d;
tmp_args_element_name_2 = metapath_based_loader;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 1;
{
PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 };
tmp_assign_source_4 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args );
}
if ( tmp_assign_source_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 1;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___spec__, tmp_assign_source_4 );
tmp_assign_source_5 = Py_None;
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___cached__, tmp_assign_source_5 );
tmp_assign_source_6 = const_str_digest_467c9722f19d9d40d148689532cdc0b1;
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___package__, tmp_assign_source_6 );
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 1;
tmp_import_name_from_1 = PyImport_ImportModule("__future__");
assert( tmp_import_name_from_1 != NULL );
tmp_assign_source_7 = IMPORT_NAME( tmp_import_name_from_1, const_str_plain_unicode_literals );
if ( tmp_assign_source_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 1;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_unicode_literals, tmp_assign_source_7 );
tmp_name_name_1 = const_str_plain_os;
tmp_globals_name_1 = (PyObject *)moduledict_django$utils$_os;
tmp_locals_name_1 = Py_None;
tmp_fromlist_name_1 = Py_None;
tmp_level_name_1 = const_int_0;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 3;
tmp_assign_source_8 = IMPORT_MODULE5( tmp_name_name_1, tmp_globals_name_1, tmp_locals_name_1, tmp_fromlist_name_1, tmp_level_name_1 );
if ( tmp_assign_source_8 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 3;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os, tmp_assign_source_8 );
tmp_name_name_2 = const_str_plain_sys;
tmp_globals_name_2 = (PyObject *)moduledict_django$utils$_os;
tmp_locals_name_2 = Py_None;
tmp_fromlist_name_2 = Py_None;
tmp_level_name_2 = const_int_0;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 4;
tmp_assign_source_9 = IMPORT_MODULE5( tmp_name_name_2, tmp_globals_name_2, tmp_locals_name_2, tmp_fromlist_name_2, tmp_level_name_2 );
assert( tmp_assign_source_9 != NULL );
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sys, tmp_assign_source_9 );
tmp_name_name_3 = const_str_plain_tempfile;
tmp_globals_name_3 = (PyObject *)moduledict_django$utils$_os;
tmp_locals_name_3 = Py_None;
tmp_fromlist_name_3 = Py_None;
tmp_level_name_3 = const_int_0;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 5;
tmp_assign_source_10 = IMPORT_MODULE5( tmp_name_name_3, tmp_globals_name_3, tmp_locals_name_3, tmp_fromlist_name_3, tmp_level_name_3 );
if ( tmp_assign_source_10 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 5;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_tempfile, tmp_assign_source_10 );
tmp_name_name_4 = const_str_digest_e399ba4554180f37de594a6743234f17;
tmp_globals_name_4 = (PyObject *)moduledict_django$utils$_os;
tmp_locals_name_4 = Py_None;
tmp_fromlist_name_4 = const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple;
tmp_level_name_4 = const_int_0;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 6;
tmp_assign_source_11 = IMPORT_MODULE5( tmp_name_name_4, tmp_globals_name_4, tmp_locals_name_4, tmp_fromlist_name_4, tmp_level_name_4 );
if ( tmp_assign_source_11 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto frame_exception_exit_1;
}
assert( tmp_import_from_1__module == NULL );
tmp_import_from_1__module = tmp_assign_source_11;
// Tried code:
tmp_import_name_from_2 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_2 );
tmp_assign_source_12 = IMPORT_NAME( tmp_import_name_from_2, const_str_plain_abspath );
if ( tmp_assign_source_12 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspath, tmp_assign_source_12 );
tmp_import_name_from_3 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_3 );
tmp_assign_source_13 = IMPORT_NAME( tmp_import_name_from_3, const_str_plain_dirname );
if ( tmp_assign_source_13 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_dirname, tmp_assign_source_13 );
tmp_import_name_from_4 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_4 );
tmp_assign_source_14 = IMPORT_NAME( tmp_import_name_from_4, const_str_plain_isabs );
if ( tmp_assign_source_14 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_isabs, tmp_assign_source_14 );
tmp_import_name_from_5 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_5 );
tmp_assign_source_15 = IMPORT_NAME( tmp_import_name_from_5, const_str_plain_join );
if ( tmp_assign_source_15 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_join, tmp_assign_source_15 );
tmp_import_name_from_6 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_6 );
tmp_assign_source_16 = IMPORT_NAME( tmp_import_name_from_6, const_str_plain_normcase );
if ( tmp_assign_source_16 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase, tmp_assign_source_16 );
tmp_import_name_from_7 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_7 );
tmp_assign_source_17 = IMPORT_NAME( tmp_import_name_from_7, const_str_plain_normpath );
if ( tmp_assign_source_17 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normpath, tmp_assign_source_17 );
tmp_import_name_from_8 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_8 );
tmp_assign_source_18 = IMPORT_NAME( tmp_import_name_from_8, const_str_plain_sep );
if ( tmp_assign_source_18 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sep, tmp_assign_source_18 );
goto try_end_1;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_import_from_1__module );
tmp_import_from_1__module = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto frame_exception_exit_1;
// End of try:
try_end_1:;
Py_XDECREF( tmp_import_from_1__module );
tmp_import_from_1__module = NULL;
tmp_name_name_5 = const_str_digest_dfb6e1abbed3113ee07234fdc458a320;
tmp_globals_name_5 = (PyObject *)moduledict_django$utils$_os;
tmp_locals_name_5 = Py_None;
tmp_fromlist_name_5 = const_tuple_str_plain_SuspiciousFileOperation_tuple;
tmp_level_name_5 = const_int_0;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 8;
tmp_import_name_from_9 = IMPORT_MODULE5( tmp_name_name_5, tmp_globals_name_5, tmp_locals_name_5, tmp_fromlist_name_5, tmp_level_name_5 );
if ( tmp_import_name_from_9 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 8;
goto frame_exception_exit_1;
}
tmp_assign_source_19 = IMPORT_NAME( tmp_import_name_from_9, const_str_plain_SuspiciousFileOperation );
Py_DECREF( tmp_import_name_from_9 );
if ( tmp_assign_source_19 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 8;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_SuspiciousFileOperation, tmp_assign_source_19 );
tmp_name_name_6 = const_str_digest_467c9722f19d9d40d148689532cdc0b1;
tmp_globals_name_6 = (PyObject *)moduledict_django$utils$_os;
tmp_locals_name_6 = Py_None;
tmp_fromlist_name_6 = const_tuple_str_plain_six_tuple;
tmp_level_name_6 = const_int_0;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 9;
tmp_import_name_from_10 = IMPORT_MODULE5( tmp_name_name_6, tmp_globals_name_6, tmp_locals_name_6, tmp_fromlist_name_6, tmp_level_name_6 );
if ( tmp_import_name_from_10 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 9;
goto frame_exception_exit_1;
}
tmp_assign_source_20 = IMPORT_NAME( tmp_import_name_from_10, const_str_plain_six );
Py_DECREF( tmp_import_name_from_10 );
if ( tmp_assign_source_20 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 9;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six, tmp_assign_source_20 );
tmp_name_name_7 = const_str_digest_e3393b2e61653c3df2c7d436c253bbee;
tmp_globals_name_7 = (PyObject *)moduledict_django$utils$_os;
tmp_locals_name_7 = Py_None;
tmp_fromlist_name_7 = const_tuple_str_plain_force_text_tuple;
tmp_level_name_7 = const_int_0;
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 10;
tmp_import_name_from_11 = IMPORT_MODULE5( tmp_name_name_7, tmp_globals_name_7, tmp_locals_name_7, tmp_fromlist_name_7, tmp_level_name_7 );
if ( tmp_import_name_from_11 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 10;
goto frame_exception_exit_1;
}
tmp_assign_source_21 = IMPORT_NAME( tmp_import_name_from_11, const_str_plain_force_text );
Py_DECREF( tmp_import_name_from_11 );
if ( tmp_assign_source_21 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 10;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_force_text, tmp_assign_source_21 );
tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six );
if (unlikely( tmp_source_name_1 == NULL ))
{
tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six );
}
if ( tmp_source_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 12;
goto frame_exception_exit_1;
}
tmp_cond_value_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_PY2 );
if ( tmp_cond_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 12;
goto frame_exception_exit_1;
}
tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_1 );
exception_lineno = 12;
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_called_instance_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sys );
if (unlikely( tmp_called_instance_1 == NULL ))
{
tmp_called_instance_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_sys );
}
if ( tmp_called_instance_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "sys" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 13;
goto frame_exception_exit_1;
}
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 13;
tmp_or_left_value_1 = CALL_METHOD_NO_ARGS( tmp_called_instance_1, const_str_plain_getfilesystemencoding );
if ( tmp_or_left_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 13;
goto frame_exception_exit_1;
}
tmp_or_left_truth_1 = CHECK_IF_TRUE( tmp_or_left_value_1 );
if ( tmp_or_left_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_or_left_value_1 );
exception_lineno = 13;
goto frame_exception_exit_1;
}
if ( tmp_or_left_truth_1 == 1 )
{
goto or_left_1;
}
else
{
goto or_right_1;
}
or_right_1:;
Py_DECREF( tmp_or_left_value_1 );
tmp_called_instance_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sys );
if (unlikely( tmp_called_instance_2 == NULL ))
{
tmp_called_instance_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_sys );
}
if ( tmp_called_instance_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "sys" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 13;
goto frame_exception_exit_1;
}
frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 13;
tmp_or_right_value_1 = CALL_METHOD_NO_ARGS( tmp_called_instance_2, const_str_plain_getdefaultencoding );
if ( tmp_or_right_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 13;
goto frame_exception_exit_1;
}
tmp_assign_source_22 = tmp_or_right_value_1;
goto or_end_1;
or_left_1:;
tmp_assign_source_22 = tmp_or_left_value_1;
or_end_1:;
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_fs_encoding, tmp_assign_source_22 );
branch_no_1:;
tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six );
if (unlikely( tmp_source_name_2 == NULL ))
{
tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six );
}
if ( tmp_source_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 21;
goto frame_exception_exit_1;
}
tmp_or_left_value_2 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_PY3 );
if ( tmp_or_left_value_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 21;
goto frame_exception_exit_1;
}
tmp_or_left_truth_2 = CHECK_IF_TRUE( tmp_or_left_value_2 );
if ( tmp_or_left_truth_2 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_or_left_value_2 );
exception_lineno = 21;
goto frame_exception_exit_1;
}
if ( tmp_or_left_truth_2 == 1 )
{
goto or_left_2;
}
else
{
goto or_right_2;
}
or_right_2:;
Py_DECREF( tmp_or_left_value_2 );
tmp_source_name_3 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os );
if (unlikely( tmp_source_name_3 == NULL ))
{
tmp_source_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os );
}
if ( tmp_source_name_3 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 21;
goto frame_exception_exit_1;
}
tmp_compexpr_left_1 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_name );
if ( tmp_compexpr_left_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 21;
goto frame_exception_exit_1;
}
tmp_compexpr_right_1 = const_str_plain_nt;
tmp_or_right_value_2 = RICH_COMPARE_EQ_NORECURSE( tmp_compexpr_left_1, tmp_compexpr_right_1 );
Py_DECREF( tmp_compexpr_left_1 );
if ( tmp_or_right_value_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 21;
goto frame_exception_exit_1;
}
tmp_cond_value_2 = tmp_or_right_value_2;
goto or_end_2;
or_left_2:;
tmp_cond_value_2 = tmp_or_left_value_2;
or_end_2:;
tmp_cond_truth_2 = CHECK_IF_TRUE( tmp_cond_value_2 );
if ( tmp_cond_truth_2 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_2 );
exception_lineno = 21;
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_2 );
if ( tmp_cond_truth_2 == 1 )
{
goto branch_yes_2;
}
else
{
goto branch_no_2;
}
branch_yes_2:;
tmp_assign_source_23 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspath );
if (unlikely( tmp_assign_source_23 == NULL ))
{
tmp_assign_source_23 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_abspath );
}
if ( tmp_assign_source_23 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "abspath" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 22;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspathu, tmp_assign_source_23 );
goto branch_end_2;
branch_no_2:;
tmp_assign_source_24 = MAKE_FUNCTION_django$utils$_os$$$function_1_abspathu( );
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspathu, tmp_assign_source_24 );
branch_end_2:;
// Restore frame exception if necessary.
#if 0
RESTORE_FRAME_EXCEPTION( frame_e3f2225c4277cee0cd5878c353c5494a );
#endif
popFrameStack();
assertFrameObject( frame_e3f2225c4277cee0cd5878c353c5494a );
goto frame_no_exception_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_e3f2225c4277cee0cd5878c353c5494a );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_e3f2225c4277cee0cd5878c353c5494a, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_e3f2225c4277cee0cd5878c353c5494a->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_e3f2225c4277cee0cd5878c353c5494a, exception_lineno );
}
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto module_exception_exit;
frame_no_exception_1:;
tmp_assign_source_25 = MAKE_FUNCTION_django$utils$_os$$$function_2_upath( );
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_upath, tmp_assign_source_25 );
tmp_assign_source_26 = MAKE_FUNCTION_django$utils$_os$$$function_3_npath( );
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_npath, tmp_assign_source_26 );
tmp_assign_source_27 = MAKE_FUNCTION_django$utils$_os$$$function_4_safe_join( );
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_safe_join, tmp_assign_source_27 );
tmp_assign_source_28 = MAKE_FUNCTION_django$utils$_os$$$function_5_symlinks_supported( );
UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_symlinks_supported, tmp_assign_source_28 );
return MOD_RETURN_VALUE( module_django$utils$_os );
module_exception_exit:
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return MOD_RETURN_VALUE( NULL );
}
| 33.741102 | 255 | 0.714514 |
f13f7aaa59f43d9abf2c92c59d09202cf868232e | 1,842 | cc | C++ | core/paddlefl_mpc/mpc_protocol/network/mesh_network_test.cc | barrierye/PaddleFL | eff6ef28491fa2011686ca3daa4f680e5ef83deb | [
"Apache-2.0"
] | 379 | 2019-09-27T14:26:42.000Z | 2022-03-29T14:28:12.000Z | core/paddlefl_mpc/mpc_protocol/network/mesh_network_test.cc | Sprate/PaddleFL | 583691acd5db0a7ca331cc9a72415017b18669b8 | [
"Apache-2.0"
] | 132 | 2019-10-16T03:22:03.000Z | 2022-03-23T08:54:29.000Z | core/paddlefl_mpc/mpc_protocol/network/mesh_network_test.cc | Sprate/PaddleFL | 583691acd5db0a7ca331cc9a72415017b18669b8 | [
"Apache-2.0"
] | 106 | 2019-09-27T12:47:18.000Z | 2022-03-29T09:07:25.000Z | // Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// 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 "core/paddlefl_mpc/mpc_protocol/network/mesh_network.h"
#include <thread>
#include "gtest/gtest.h"
namespace paddle {
namespace mpc {
class NetworkTest : public ::testing::Test {
public:
std::string _addr;
std::string _prefix;
std::shared_ptr<gloo::rendezvous::HashStore> _store;
MeshNetwork _n0;
MeshNetwork _n1;
AbstractNetwork *_p0;
AbstractNetwork *_p1;
NetworkTest()
: _addr("127.0.0.1"), _prefix("test_prefix"),
_store(std::make_shared<gloo::rendezvous::HashStore>()),
_n0(0, _addr, 2, _prefix, _store), _n1(1, _addr, 2, _prefix, _store),
_p0(&_n0), _p1(&_n1) {}
void SetUp() {
std::thread t0([this]() { _n0.init(); });
std::thread t1([this]() { _n1.init(); });
t0.join();
t1.join();
}
};
TEST_F(NetworkTest, basic_test) {
int buf[2] = {0, 1};
std::thread t0([this, &buf]() {
_p0->template send(1, buf[0]);
buf[0] = _p0->template recv<int>(1);
});
std::thread t1([this, &buf]() {
int to_send = buf[1];
buf[1] = _p1->template recv<int>(0);
_p1->template send(0, to_send);
});
t0.join();
t1.join();
EXPECT_EQ(1, buf[0]);
EXPECT_EQ(0, buf[1]);
}
} // namespace mpc
} // namespace paddle
| 24.891892 | 77 | 0.652552 |
f13fc487d8527459ed97e5c7d6f4c59b8252446b | 24,584 | cpp | C++ | Source/Controls/TextEditorPackage/GuiTextCommonInterface.cpp | JamesLinus/GacUI | b16f5919e03d5e24cb1e4509111e12aa28e6b827 | [
"MS-PL"
] | 1 | 2019-04-22T09:09:37.000Z | 2019-04-22T09:09:37.000Z | Source/Controls/TextEditorPackage/GuiTextCommonInterface.cpp | JamesLinus/GacUI | b16f5919e03d5e24cb1e4509111e12aa28e6b827 | [
"MS-PL"
] | null | null | null | Source/Controls/TextEditorPackage/GuiTextCommonInterface.cpp | JamesLinus/GacUI | b16f5919e03d5e24cb1e4509111e12aa28e6b827 | [
"MS-PL"
] | null | null | null | #include "GuiTextCommonInterface.h"
#include <math.h>
namespace vl
{
namespace presentation
{
namespace controls
{
using namespace elements;
using namespace elements::text;
using namespace compositions;
/***********************************************************************
GuiTextBoxCommonInterface::DefaultCallback
***********************************************************************/
GuiTextBoxCommonInterface::DefaultCallback::DefaultCallback(elements::GuiColorizedTextElement* _textElement, compositions::GuiGraphicsComposition* _textComposition)
:textElement(_textElement)
,textComposition(_textComposition)
{
}
GuiTextBoxCommonInterface::DefaultCallback::~DefaultCallback()
{
}
TextPos GuiTextBoxCommonInterface::DefaultCallback::GetLeftWord(TextPos pos)
{
return pos;
}
TextPos GuiTextBoxCommonInterface::DefaultCallback::GetRightWord(TextPos pos)
{
return pos;
}
void GuiTextBoxCommonInterface::DefaultCallback::GetWord(TextPos pos, TextPos& begin, TextPos& end)
{
begin=pos;
end=pos;
}
vint GuiTextBoxCommonInterface::DefaultCallback::GetPageRows()
{
return textComposition->GetBounds().Height()/textElement->GetLines().GetRowHeight();
}
bool GuiTextBoxCommonInterface::DefaultCallback::BeforeModify(TextPos start, TextPos end, const WString& originalText, WString& inputText)
{
return true;
}
/***********************************************************************
GuiTextBoxCommonInterface
***********************************************************************/
void GuiTextBoxCommonInterface::UpdateCaretPoint()
{
GuiGraphicsHost* host=textComposition->GetRelatedGraphicsHost();
if(host)
{
Rect caret=textElement->GetLines().GetRectFromTextPos(textElement->GetCaretEnd());
Point view=textElement->GetViewPosition();
vint x=caret.x1-view.x;
vint y=caret.y2-view.y;
host->SetCaretPoint(Point(x, y), textComposition);
}
}
void GuiTextBoxCommonInterface::Move(TextPos pos, bool shift)
{
TextPos oldBegin=textElement->GetCaretBegin();
TextPos oldEnd=textElement->GetCaretEnd();
pos=textElement->GetLines().Normalize(pos);
if(!shift)
{
textElement->SetCaretBegin(pos);
}
textElement->SetCaretEnd(pos);
if(textControl)
{
GuiGraphicsHost* host=textComposition->GetRelatedGraphicsHost();
if(host)
{
if(host->GetFocusedComposition()==textControl->GetFocusableComposition())
{
textElement->SetCaretVisible(true);
}
}
}
Rect bounds=textElement->GetLines().GetRectFromTextPos(pos);
Rect view=Rect(textElement->GetViewPosition(), textComposition->GetBounds().GetSize());
Point viewPoint=view.LeftTop();
if(view.x2>view.x1 && view.y2>view.y1)
{
if(bounds.x1<view.x1)
{
viewPoint.x=bounds.x1;
}
else if(bounds.x2>view.x2)
{
viewPoint.x=bounds.x2-view.Width();
}
if(bounds.y1<view.y1)
{
viewPoint.y=bounds.y1;
}
else if(bounds.y2>view.y2)
{
viewPoint.y=bounds.y2-view.Height();
}
}
callback->ScrollToView(viewPoint);
UpdateCaretPoint();
TextPos newBegin=textElement->GetCaretBegin();
TextPos newEnd=textElement->GetCaretEnd();
if(oldBegin!=newBegin || oldEnd!=newEnd)
{
ICommonTextEditCallback::TextCaretChangedStruct arguments;
arguments.oldBegin=oldBegin;
arguments.oldEnd=oldEnd;
arguments.newBegin=newBegin;
arguments.newEnd=newEnd;
arguments.editVersion=editVersion;
for(vint i=0;i<textEditCallbacks.Count();i++)
{
textEditCallbacks[i]->TextCaretChanged(arguments);
}
SelectionChanged.Execute(textControl->GetNotifyEventArguments());
}
}
void GuiTextBoxCommonInterface::Modify(TextPos start, TextPos end, const WString& input, bool asKeyInput)
{
if(start>end)
{
TextPos temp=start;
start=end;
end=temp;
}
TextPos originalStart=start;
TextPos originalEnd=end;
WString originalText=textElement->GetLines().GetText(start, end);
WString inputText=input;
if(callback->BeforeModify(start, end, originalText, inputText))
{
{
ICommonTextEditCallback::TextEditPreviewStruct arguments;
arguments.originalStart=originalStart;
arguments.originalEnd=originalEnd;
arguments.originalText=originalText;
arguments.inputText=inputText;
arguments.editVersion=editVersion;
arguments.keyInput=asKeyInput;
for(vint i=0;i<textEditCallbacks.Count();i++)
{
textEditCallbacks[i]->TextEditPreview(arguments);
}
inputText=arguments.inputText;
if(originalStart!=arguments.originalStart || originalEnd!=arguments.originalEnd)
{
originalStart=arguments.originalStart;
originalEnd=arguments.originalEnd;
originalText=textElement->GetLines().GetText(originalStart, originalEnd);
start=originalStart;
end=originalEnd;
}
}
SPIN_LOCK(elementModifyLock)
{
end=textElement->GetLines().Modify(start, end, inputText);
}
callback->AfterModify(originalStart, originalEnd, originalText, start, end, inputText);
editVersion++;
{
ICommonTextEditCallback::TextEditNotifyStruct arguments;
arguments.originalStart=originalStart;
arguments.originalEnd=originalEnd;
arguments.originalText=originalText;
arguments.inputStart=start;
arguments.inputEnd=end;
arguments.inputText=inputText;
arguments.editVersion=editVersion;
arguments.keyInput=asKeyInput;
for(vint i=0;i<textEditCallbacks.Count();i++)
{
textEditCallbacks[i]->TextEditNotify(arguments);
}
}
Move(end, false);
for(vint i=0;i<textEditCallbacks.Count();i++)
{
textEditCallbacks[i]->TextEditFinished(editVersion);
}
textControl->TextChanged.Execute(textControl->GetNotifyEventArguments());
}
}
bool GuiTextBoxCommonInterface::ProcessKey(vint code, bool shift, bool ctrl)
{
if(IGuiShortcutKeyItem* item=internalShortcutKeyManager->TryGetShortcut(ctrl, shift, false, code))
{
GuiEventArgs arguments;
item->Executed.Execute(arguments);
return true;
}
TextPos begin=textElement->GetCaretBegin();
TextPos end=textElement->GetCaretEnd();
switch(code)
{
case VKEY_ESCAPE:
if(autoComplete && autoComplete->IsListOpening() && !shift && !ctrl)
{
autoComplete->CloseList();
}
return true;
case VKEY_RETURN:
if(autoComplete && autoComplete->IsListOpening() && !shift && !ctrl)
{
if(autoComplete->ApplySelectedListItem())
{
preventEnterDueToAutoComplete=true;
return true;
}
}
break;
case VKEY_UP:
if(autoComplete && autoComplete->IsListOpening() && !shift && !ctrl)
{
autoComplete->SelectPreviousListItem();
}
else
{
end.row--;
Move(end, shift);
}
return true;
case VKEY_DOWN:
if(autoComplete && autoComplete->IsListOpening() && !shift && !ctrl)
{
autoComplete->SelectNextListItem();
}
else
{
end.row++;
Move(end, shift);
}
return true;
case VKEY_LEFT:
{
if(ctrl)
{
Move(callback->GetLeftWord(end), shift);
}
else
{
if(end.column==0)
{
if(end.row>0)
{
end.row--;
end=textElement->GetLines().Normalize(end);
end.column=textElement->GetLines().GetLine(end.row).dataLength;
}
}
else
{
end.column--;
}
Move(end, shift);
}
}
return true;
case VKEY_RIGHT:
{
if(ctrl)
{
Move(callback->GetRightWord(end), shift);
}
else
{
if(end.column==textElement->GetLines().GetLine(end.row).dataLength)
{
if(end.row<textElement->GetLines().GetCount()-1)
{
end.row++;
end.column=0;
}
}
else
{
end.column++;
}
Move(end, shift);
}
}
return true;
case VKEY_HOME:
{
if(ctrl)
{
Move(TextPos(0, 0), shift);
}
else
{
end.column=0;
Move(end, shift);
}
}
return true;
case VKEY_END:
{
if(ctrl)
{
end.row=textElement->GetLines().GetCount()-1;
}
end.column=textElement->GetLines().GetLine(end.row).dataLength;
Move(end, shift);
}
return true;
case VKEY_PRIOR:
{
end.row-=callback->GetPageRows();
Move(end, shift);
}
return true;
case VKEY_NEXT:
{
end.row+=callback->GetPageRows();
Move(end, shift);
}
return true;
case VKEY_BACK:
if(!readonly)
{
if(ctrl && !shift)
{
ProcessKey(VKEY_LEFT, true, true);
ProcessKey(VKEY_BACK, false, false);
}
else if(!ctrl && shift)
{
ProcessKey(VKEY_UP, true, false);
ProcessKey(VKEY_BACK, false, false);
}
else
{
if(begin==end)
{
ProcessKey(VKEY_LEFT, true, false);
}
SetSelectionTextAsKeyInput(L"");
}
return true;
}
break;
case VKEY_DELETE:
if(!readonly)
{
if(ctrl && !shift)
{
ProcessKey(VKEY_RIGHT, true, true);
ProcessKey(VKEY_DELETE, false, false);
}
else if(!ctrl && shift)
{
ProcessKey(VKEY_DOWN, true, false);
ProcessKey(VKEY_DELETE, false, false);
}
else
{
if(begin==end)
{
ProcessKey(VKEY_RIGHT, true, false);
}
SetSelectionTextAsKeyInput(L"");
}
return true;
}
break;
}
return false;
}
void GuiTextBoxCommonInterface::OnGotFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments)
{
textElement->SetFocused(true);
textElement->SetCaretVisible(true);
UpdateCaretPoint();
}
void GuiTextBoxCommonInterface::OnLostFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments)
{
textElement->SetFocused(false);
textElement->SetCaretVisible(false);
}
void GuiTextBoxCommonInterface::OnCaretNotify(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments)
{
textElement->SetCaretVisible(!textElement->GetCaretVisible());
}
void GuiTextBoxCommonInterface::OnLeftButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments)
{
if(textControl->GetVisuallyEnabled() && arguments.compositionSource==arguments.eventSource)
{
dragging=true;
TextPos pos=GetNearestTextPos(Point(arguments.x, arguments.y));
Move(pos, arguments.shift);
}
}
void GuiTextBoxCommonInterface::OnLeftButtonUp(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments)
{
if(textControl->GetVisuallyEnabled() && arguments.compositionSource==arguments.eventSource)
{
dragging=false;
}
}
void GuiTextBoxCommonInterface::OnMouseMove(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments)
{
if(textControl->GetVisuallyEnabled() && arguments.compositionSource==arguments.eventSource)
{
if(dragging)
{
TextPos pos=GetNearestTextPos(Point(arguments.x, arguments.y));
Move(pos, true);
}
}
}
void GuiTextBoxCommonInterface::OnKeyDown(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments)
{
if(textControl->GetVisuallyEnabled() && arguments.compositionSource==arguments.eventSource)
{
if(ProcessKey(arguments.code, arguments.shift, arguments.ctrl))
{
arguments.handled=true;
}
}
}
void GuiTextBoxCommonInterface::OnCharInput(compositions::GuiGraphicsComposition* sender, compositions::GuiCharEventArgs& arguments)
{
if(preventEnterDueToAutoComplete)
{
preventEnterDueToAutoComplete=false;
if(arguments.code==VKEY_RETURN)
{
return;
}
}
if(textControl->GetVisuallyEnabled() && arguments.compositionSource==arguments.eventSource)
{
if(!readonly && arguments.code!=VKEY_ESCAPE && arguments.code!=VKEY_BACK && !arguments.ctrl)
{
SetSelectionTextAsKeyInput(WString(arguments.code));
}
}
}
void GuiTextBoxCommonInterface::Install(elements::GuiColorizedTextElement* _textElement, compositions::GuiGraphicsComposition* _textComposition, GuiControl* _textControl)
{
textElement=_textElement;
textComposition=_textComposition;
textControl=_textControl;
textComposition->SetAssociatedCursor(GetCurrentController()->ResourceService()->GetSystemCursor(INativeCursor::IBeam));
SelectionChanged.SetAssociatedComposition(textControl->GetBoundsComposition());
GuiGraphicsComposition* focusableComposition=textControl->GetFocusableComposition();
focusableComposition->GetEventReceiver()->gotFocus.AttachMethod(this, &GuiTextBoxCommonInterface::OnGotFocus);
focusableComposition->GetEventReceiver()->lostFocus.AttachMethod(this, &GuiTextBoxCommonInterface::OnLostFocus);
focusableComposition->GetEventReceiver()->caretNotify.AttachMethod(this, &GuiTextBoxCommonInterface::OnCaretNotify);
textComposition->GetEventReceiver()->leftButtonDown.AttachMethod(this, &GuiTextBoxCommonInterface::OnLeftButtonDown);
textComposition->GetEventReceiver()->leftButtonUp.AttachMethod(this, &GuiTextBoxCommonInterface::OnLeftButtonUp);
textComposition->GetEventReceiver()->mouseMove.AttachMethod(this, &GuiTextBoxCommonInterface::OnMouseMove);
focusableComposition->GetEventReceiver()->keyDown.AttachMethod(this, &GuiTextBoxCommonInterface::OnKeyDown);
focusableComposition->GetEventReceiver()->charInput.AttachMethod(this, &GuiTextBoxCommonInterface::OnCharInput);
for(vint i=0;i<textEditCallbacks.Count();i++)
{
textEditCallbacks[i]->Attach(textElement, elementModifyLock, textComposition ,editVersion);
}
}
GuiTextBoxCommonInterface::ICallback* GuiTextBoxCommonInterface::GetCallback()
{
return callback;
}
void GuiTextBoxCommonInterface::SetCallback(ICallback* value)
{
callback=value;
}
bool GuiTextBoxCommonInterface::AttachTextEditCallback(Ptr<ICommonTextEditCallback> value)
{
if(textEditCallbacks.Contains(value.Obj()))
{
return false;
}
else
{
textEditCallbacks.Add(value);
if(textElement)
{
value->Attach(textElement, elementModifyLock, textComposition, editVersion);
}
return true;
}
}
bool GuiTextBoxCommonInterface::DetachTextEditCallback(Ptr<ICommonTextEditCallback> value)
{
if(textEditCallbacks.Remove(value.Obj()))
{
value->Detach();
return true;
}
else
{
return false;
}
}
void GuiTextBoxCommonInterface::AddShortcutCommand(vint key, const Func<void()>& eventHandler)
{
IGuiShortcutKeyItem* item=internalShortcutKeyManager->CreateShortcut(true, false, false, key);
item->Executed.AttachLambda([=](GuiGraphicsComposition* sender, GuiEventArgs& arguments)
{
eventHandler();
});
}
elements::GuiColorizedTextElement* GuiTextBoxCommonInterface::GetTextElement()
{
return textElement;
}
void GuiTextBoxCommonInterface::UnsafeSetText(const WString& value)
{
if(textElement)
{
TextPos end;
if(textElement->GetLines().GetCount()>0)
{
end.row=textElement->GetLines().GetCount()-1;
end.column=textElement->GetLines().GetLine(end.row).dataLength;
}
Modify(TextPos(), end, value, false);
}
}
GuiTextBoxCommonInterface::GuiTextBoxCommonInterface()
:textElement(0)
,textComposition(0)
,editVersion(0)
,textControl(0)
,callback(0)
,dragging(false)
,readonly(false)
,preventEnterDueToAutoComplete(false)
{
undoRedoProcessor=new GuiTextBoxUndoRedoProcessor;
AttachTextEditCallback(undoRedoProcessor);
internalShortcutKeyManager=new GuiShortcutKeyManager;
AddShortcutCommand('Z', Func<bool()>(this, &GuiTextBoxCommonInterface::Undo));
AddShortcutCommand('Y', Func<bool()>(this, &GuiTextBoxCommonInterface::Redo));
AddShortcutCommand('A', Func<void()>(this, &GuiTextBoxCommonInterface::SelectAll));
AddShortcutCommand('X', Func<bool()>(this, &GuiTextBoxCommonInterface::Cut));
AddShortcutCommand('C', Func<bool()>(this, &GuiTextBoxCommonInterface::Copy));
AddShortcutCommand('V', Func<bool()>(this, &GuiTextBoxCommonInterface::Paste));
}
GuiTextBoxCommonInterface::~GuiTextBoxCommonInterface()
{
if(colorizer)
{
DetachTextEditCallback(colorizer);
colorizer=0;
}
if(undoRedoProcessor)
{
DetachTextEditCallback(undoRedoProcessor);
undoRedoProcessor=0;
}
for(vint i=0;i<textEditCallbacks.Count();i++)
{
textEditCallbacks[i]->Detach();
}
textEditCallbacks.Clear();
}
//================ clipboard operations
bool GuiTextBoxCommonInterface::CanCut()
{
return !readonly && textElement->GetCaretBegin()!=textElement->GetCaretEnd() && textElement->GetPasswordChar()==L'\0';
}
bool GuiTextBoxCommonInterface::CanCopy()
{
return textElement->GetCaretBegin()!=textElement->GetCaretEnd() && textElement->GetPasswordChar()==L'\0';
}
bool GuiTextBoxCommonInterface::CanPaste()
{
return !readonly && GetCurrentController()->ClipboardService()->ContainsText() && textElement->GetPasswordChar()==L'\0';
}
bool GuiTextBoxCommonInterface::Cut()
{
if(CanCut())
{
GetCurrentController()->ClipboardService()->SetText(GetSelectionText());
SetSelectionText(L"");
return true;
}
else
{
return false;
}
}
bool GuiTextBoxCommonInterface::Copy()
{
if(CanCopy())
{
GetCurrentController()->ClipboardService()->SetText(GetSelectionText());
return true;
}
else
{
return false;
}
}
bool GuiTextBoxCommonInterface::Paste()
{
if(CanPaste())
{
SetSelectionText(GetCurrentController()->ClipboardService()->GetText());
return true;
}
else
{
return false;
}
}
//================ editing control
bool GuiTextBoxCommonInterface::GetReadonly()
{
return readonly;
}
void GuiTextBoxCommonInterface::SetReadonly(bool value)
{
readonly=value;
}
//================ text operations
void GuiTextBoxCommonInterface::Select(TextPos begin, TextPos end)
{
Move(begin, false);
Move(end, true);
}
void GuiTextBoxCommonInterface::SelectAll()
{
vint row=textElement->GetLines().GetCount()-1;
Move(TextPos(0, 0), false);
Move(TextPos(row, textElement->GetLines().GetLine(row).dataLength), true);
}
WString GuiTextBoxCommonInterface::GetSelectionText()
{
TextPos selectionBegin=textElement->GetCaretBegin()<textElement->GetCaretEnd()?textElement->GetCaretBegin():textElement->GetCaretEnd();
TextPos selectionEnd=textElement->GetCaretBegin()>textElement->GetCaretEnd()?textElement->GetCaretBegin():textElement->GetCaretEnd();
return textElement->GetLines().GetText(selectionBegin, selectionEnd);
}
void GuiTextBoxCommonInterface::SetSelectionText(const WString& value)
{
Modify(textElement->GetCaretBegin(), textElement->GetCaretEnd(), value, false);
}
void GuiTextBoxCommonInterface::SetSelectionTextAsKeyInput(const WString& value)
{
Modify(textElement->GetCaretBegin(), textElement->GetCaretEnd(), value, true);
}
WString GuiTextBoxCommonInterface::GetRowText(vint row)
{
TextPos start=textElement->GetLines().Normalize(TextPos(row, 0));
TextPos end=TextPos(start.row, textElement->GetLines().GetLine(start.row).dataLength);
return GetFragmentText(start, end);
}
WString GuiTextBoxCommonInterface::GetFragmentText(TextPos start, TextPos end)
{
start=textElement->GetLines().Normalize(start);
end=textElement->GetLines().Normalize(end);
return textElement->GetLines().GetText(start, end);
}
TextPos GuiTextBoxCommonInterface::GetCaretBegin()
{
return textElement->GetCaretBegin();
}
TextPos GuiTextBoxCommonInterface::GetCaretEnd()
{
return textElement->GetCaretEnd();
}
TextPos GuiTextBoxCommonInterface::GetCaretSmall()
{
TextPos c1=GetCaretBegin();
TextPos c2=GetCaretEnd();
return c1<c2?c1:c2;
}
TextPos GuiTextBoxCommonInterface::GetCaretLarge()
{
TextPos c1=GetCaretBegin();
TextPos c2=GetCaretEnd();
return c1>c2?c1:c2;
}
//================ position query
vint GuiTextBoxCommonInterface::GetRowWidth(vint row)
{
return textElement->GetLines().GetRowWidth(row);
}
vint GuiTextBoxCommonInterface::GetRowHeight()
{
return textElement->GetLines().GetRowHeight();
}
vint GuiTextBoxCommonInterface::GetMaxWidth()
{
return textElement->GetLines().GetMaxWidth();
}
vint GuiTextBoxCommonInterface::GetMaxHeight()
{
return textElement->GetLines().GetMaxHeight();
}
TextPos GuiTextBoxCommonInterface::GetTextPosFromPoint(Point point)
{
Point view=textElement->GetViewPosition();
return textElement->GetLines().GetTextPosFromPoint(Point(point.x+view.x, point.y+view.y));
}
Point GuiTextBoxCommonInterface::GetPointFromTextPos(TextPos pos)
{
Point view=textElement->GetViewPosition();
Point result=textElement->GetLines().GetPointFromTextPos(pos);
return Point(result.x-view.x, result.y-view.y);
}
Rect GuiTextBoxCommonInterface::GetRectFromTextPos(TextPos pos)
{
Point view=textElement->GetViewPosition();
Rect result=textElement->GetLines().GetRectFromTextPos(pos);
return Rect(Point(result.x1-view.x, result.y1-view.y), result.GetSize());
}
TextPos GuiTextBoxCommonInterface::GetNearestTextPos(Point point)
{
Point viewPosition=textElement->GetViewPosition();
Point mousePosition=Point(point.x+viewPosition.x, point.y+viewPosition.y);
TextPos pos=textElement->GetLines().GetTextPosFromPoint(mousePosition);
if(pos.column<textElement->GetLines().GetLine(pos.row).dataLength)
{
Rect rect=textElement->GetLines().GetRectFromTextPos(pos);
if(abs((int)(rect.x1-mousePosition.x))>=abs((int)(rect.x2-1-mousePosition.x)))
{
pos.column++;
}
}
return pos;
}
//================ colorizing
Ptr<GuiTextBoxColorizerBase> GuiTextBoxCommonInterface::GetColorizer()
{
return colorizer;
}
void GuiTextBoxCommonInterface::SetColorizer(Ptr<GuiTextBoxColorizerBase> value)
{
if(colorizer)
{
DetachTextEditCallback(colorizer);
}
colorizer=value;
if(colorizer)
{
AttachTextEditCallback(colorizer);
GetTextElement()->SetColors(colorizer->GetColors());
}
}
//================ auto complete
Ptr<GuiTextBoxAutoCompleteBase> GuiTextBoxCommonInterface::GetAutoComplete()
{
return autoComplete;
}
void GuiTextBoxCommonInterface::SetAutoComplete(Ptr<GuiTextBoxAutoCompleteBase> value)
{
if(autoComplete)
{
DetachTextEditCallback(autoComplete);
}
autoComplete=value;
if(autoComplete)
{
AttachTextEditCallback(autoComplete);
}
}
//================ undo redo control
vuint GuiTextBoxCommonInterface::GetEditVersion()
{
return editVersion;
}
bool GuiTextBoxCommonInterface::CanUndo()
{
return !readonly && undoRedoProcessor->CanUndo();
}
bool GuiTextBoxCommonInterface::CanRedo()
{
return !readonly && undoRedoProcessor->CanRedo();
}
void GuiTextBoxCommonInterface::ClearUndoRedo()
{
undoRedoProcessor->ClearUndoRedo();
}
bool GuiTextBoxCommonInterface::GetModified()
{
return undoRedoProcessor->GetModified();
}
void GuiTextBoxCommonInterface::NotifyModificationSaved()
{
undoRedoProcessor->NotifyModificationSaved();
}
bool GuiTextBoxCommonInterface::Undo()
{
if(CanUndo())
{
return undoRedoProcessor->Undo();
}
else
{
return false;
}
}
bool GuiTextBoxCommonInterface::Redo()
{
if(CanRedo())
{
return undoRedoProcessor->Redo();
}
else
{
return false;
}
}
}
}
} | 27.164641 | 173 | 0.662219 |
f142875b3b1a8d9350fb1c3c38053fdeae203392 | 1,361 | cpp | C++ | tape.cpp | teamLESLEY/tape | cd4b74b5872ec850c3b0dc9e8f26c863dd312fbf | [
"MIT"
] | null | null | null | tape.cpp | teamLESLEY/tape | cd4b74b5872ec850c3b0dc9e8f26c863dd312fbf | [
"MIT"
] | null | null | null | tape.cpp | teamLESLEY/tape | cd4b74b5872ec850c3b0dc9e8f26c863dd312fbf | [
"MIT"
] | null | null | null | #include <Wire.h>
#include "tape.hpp"
TapeSensor::TapeSensor(PinName leftPin, PinName rightPin, unsigned int threshold)
: LEFT_SENSOR(leftPin), RIGHT_SENSOR(rightPin) {
setup(threshold);
}
TapeSensor::TapeSensor(uint32_t leftPin, uint32_t rightPin, unsigned int threshold)
: LEFT_SENSOR(digitalPinToPinName(leftPin)), RIGHT_SENSOR(digitalPinToPinName(rightPin)) {
setup(threshold);
}
TapeSensor::TapeSensor(PinName leftPin, uint32_t rightPin, unsigned int threshold)
: LEFT_SENSOR(leftPin), RIGHT_SENSOR(digitalPinToPinName(rightPin)) {
setup(threshold);
}
TapeSensor::TapeSensor(uint32_t leftPin, PinName rightPin, unsigned int threshold)
: LEFT_SENSOR(digitalPinToPinName(leftPin)), RIGHT_SENSOR(rightPin) {
setup(threshold);
}
void TapeSensor::setup(unsigned int threshold) {
onThreshold = threshold;
pinMode(LEFT_SENSOR, INPUT);
pinMode(RIGHT_SENSOR, INPUT);
}
unsigned int TapeSensor::getLeftReading() {
return analogRead(LEFT_SENSOR);
}
bool TapeSensor::isLeftOn() {
return getLeftReading() > onThreshold;
}
unsigned int TapeSensor::getRightReading() {
return analogRead(RIGHT_SENSOR);
}
bool TapeSensor::isRightOn() {
return getRightReading() > onThreshold;
}
unsigned int TapeSensor::getThreshold() {
return onThreshold;
}
void TapeSensor::setThreshold(unsigned int threshold) {
onThreshold = threshold;
}
| 24.745455 | 92 | 0.768553 |
f1477f3ace2bd40604255b6996713b24abb8a69f | 15,362 | cpp | C++ | hihope_neptune-oh_hid/00_src/v0.1/foundation/distributedschedule/dmsfwk_lite/moduletest/dtbschedmgr_lite/source/tlv_parse_test.cpp | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | 1 | 2022-02-15T08:51:55.000Z | 2022-02-15T08:51:55.000Z | hihope_neptune-oh_hid/00_src/v0.3/foundation/distributedschedule/dmsfwk_lite/moduletest/dtbschedmgr_lite/source/tlv_parse_test.cpp | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | null | null | null | hihope_neptune-oh_hid/00_src/v0.3/foundation/distributedschedule/dmsfwk_lite/moduletest/dtbschedmgr_lite/source/tlv_parse_test.cpp | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* 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 "gtest/gtest.h"
#include "dmslite_msg_parser.h"
#include "dmslite_tlv_common.h"
using namespace testing::ext;
namespace OHOS {
namespace DistributedSchedule {
class TlvParseTest : public testing::Test {
protected:
static void SetUpTestCase() { }
static void TearDownTestCase() { }
virtual void SetUp() { }
virtual void TearDown() { }
static void RunTest(const uint8_t *buffer, uint16_t bufferLen,
const TlvParseCallback onTlvParseDone, const StartAbilityCallback onStartAbilityDone)
{
IDmsFeatureCallback dmsFeatureCallback = {
.onTlvParseDone = onTlvParseDone,
.onStartAbilityDone = onStartAbilityDone
};
CommuInterInfo interInfo;
interInfo.payloadLength = bufferLen;
interInfo.payload = buffer;
DmsLiteProcessCommuMsg(&interInfo, &dmsFeatureCallback);
}
};
/**
* @tc.name: NormalPackage_001
* @tc.desc: normal package with small bundle name and ability name
* @tc.type: FUNC
* @tc.require: SR000ELTHO
*/
HWTEST_F(TlvParseTest, NormalPackage_001, TestSize.Level0) {
uint8_t buffer[] = {
0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68,
0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e,
0x63, 0x68, 0x65, 0x72, 0x00, 0x03, 0x0c, 0x4d, 0x61, 0x69,
0x6e, 0x41, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x00, 0x04,
0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65, 0x79,
0x00
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
const TlvDmsMsgInfo *msg = reinterpret_cast<const TlvDmsMsgInfo *>(dmsMsg);
EXPECT_EQ(errCode, DMS_TLV_SUCCESS);
EXPECT_EQ(msg->commandId, 0);
EXPECT_EQ(string(msg->calleeBundleName), "com.huawei.launcher");
EXPECT_EQ(string(msg->calleeAbilityName), "MainAbility");
EXPECT_EQ(string(msg->callerSignature), "publickey");
};
RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr);
}
/**
* @tc.name: NormalPackageWithLongBundleName
* @tc.desc: normal package with 255 bytes long(upper boundary) bundle name
* @tc.type: FUNC
* @tc.require: AR000ENCTK
*/
HWTEST_F(TlvParseTest, NormalPackage_002, TestSize.Level0) {
uint8_t buffer[] = {
0x01, 0x01, 0x00, 0x02, 0x82, 0x00, 0x63, 0x6f, 0x6d, 0x2e, 0x61,
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c,
0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
0x78, 0x79, 0x7a, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53,
0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64,
0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,
0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b,
0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56,
0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72,
0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x41, 0x42, 0x43,
0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e,
0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a,
0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75,
0x76, 0x77, 0x78, 0x79, 0x7a, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46,
0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51,
0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62,
0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d,
0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
0x79, 0x7a, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
0x4a, 0x2e, 0x68, 0x75, 0x61, 0x77, 0x65, 0x69, 0x00, 0x03, 0x0c,
0x4d, 0x61, 0x69, 0x6e, 0x41, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79,
0x00, 0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65,
0x79, 0x00
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
const TlvDmsMsgInfo *msg = reinterpret_cast<const TlvDmsMsgInfo *>(dmsMsg);
EXPECT_EQ(errCode, DMS_TLV_SUCCESS);
std::stringstream ss;
ss << "com.";
for (int8_t i = 0; i < 4; i++) {
ss << "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
ss << "abcdefghijklmnopqrstuvwxyzABCDEFGHIJ";
ss << ".huawei";
EXPECT_EQ(msg->commandId, 0);
EXPECT_EQ(string(msg->calleeBundleName), ss.str());
EXPECT_EQ(string(msg->calleeAbilityName), "MainAbility");
EXPECT_EQ(string(msg->callerSignature), "publickey");
};
RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr);
}
/**
* @tc.name: AbnormalPackageOutOfOrder_001
* @tc.desc: abnormal package with node type sequence in disorder
* @tc.type: FUNC
* @tc.require: AR000ELTIG
*/
HWTEST_F(TlvParseTest, AbnormalPackageOutOfOrder_001, TestSize.Level0) {
uint8_t buffer[] = {
0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68, 0x75, 0x61, 0x77,
0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e, 0x63, 0x68, 0x65,
0x72, 0x01, 0x01, 0x00, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69,
0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
EXPECT_EQ(errCode, DMS_TLV_ERR_OUT_OF_ORDER);
};
RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr);
}
/**
* @tc.name: AbnormalPackageOutOfOrder_002
* @tc.desc: abnormal package with node type sequence in non-continuous order
* @tc.type: FUNC
* @tc.require: SR000DRR3L
*/
HWTEST_F(TlvParseTest, AbnormalPackageOutOfOrder_002, TestSize.Level0) {
uint8_t buffer[] = {
0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68,
0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e,
0x63, 0x68, 0x65, 0x72, 0x04, 0x00, 0x04, 0x6d, 0x80, 0xff,
0x00
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
EXPECT_EQ(errCode, DMS_TLV_ERR_OUT_OF_ORDER);
};
RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr);
}
/**
* @tc.name: AbnormalPackageBadNodeNum_001
* @tc.desc: abnormal package without node
* @tc.type: FUNC
* @tc.require: AR000E0DGE
*/
HWTEST_F(TlvParseTest, AbnormalPackageBadNodeNum_001, TestSize.Level0) {
uint8_t buffer[] = { };
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
EXPECT_EQ(errCode, DMS_TLV_ERR_LEN);
};
RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr);
}
/**
* @tc.name: AbnormalPackageBadNodeNum_002
* @tc.desc: abnormal package with only one mandatory node
* @tc.type: FUNC
* @tc.require: AR000E0DE5
*/
HWTEST_F(TlvParseTest, AbnormalPackageBadNodeNum_002, TestSize.Level0) {
uint8_t buffer[] = {
0x01, 0x01, 0x00,
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
EXPECT_EQ(errCode, DMS_TLV_ERR_BAD_NODE_NUM);
};
RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr);
}
/**
* @tc.name: AbnormalPackageBadNodeNum_003
* @tc.desc: abnormal package with only two mandatory nodes
* @tc.type: FUNC
* @tc.require: AR000E0DE0
*/
HWTEST_F(TlvParseTest, AbnormalPackageBadNodeNum_003, TestSize.Level0) {
uint8_t buffer[] = {
0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68,
0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e,
0x63, 0x68, 0x65, 0x72, 0x00
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
EXPECT_EQ(errCode, DMS_TLV_ERR_BAD_NODE_NUM);
};
RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr);
}
/**
* @tc.name: AbnormalPackageBadNodeNum_004
* @tc.desc: abnormal package with only three mandatory nodes
* @tc.type: FUNC
* @tc.require: AR000DSCRF
*/
HWTEST_F(TlvParseTest, AbnormalPackageBadNodeNum_004, TestSize.Level0) {
uint8_t buffer[] = {
0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68,
0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e,
0x63, 0x68, 0x65, 0x72, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69,
0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
EXPECT_EQ(errCode, DMS_TLV_ERR_BAD_NODE_NUM);
};
RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr);
}
/**
* @tc.name: AbnormalPackageBadNodeNum_005
* @tc.desc: abnormal package with an additional node
* @tc.type: FUNC
* @tc.require: AR000DSCRB
*/
HWTEST_F(TlvParseTest, AbnormalPackageBadNodeNum_005, TestSize.Level0) {
uint8_t buffer[] = {
0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68,
0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e,
0x63, 0x68, 0x65, 0x72, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69,
0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00,
0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65,
0x79, 0x00, 0x05, 0x01, 0x00
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
EXPECT_EQ(errCode, DMS_TLV_ERR_BAD_NODE_NUM);
};
RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr);
}
/**
* @tc.name: AbnormalPackageBadLength_001
* @tc.desc: abnormal package tlv node without value
* @tc.type: FUNC
* @tc.require: SR000E0DR9
*/
HWTEST_F(TlvParseTest, AbnormalPackageBadLength_001, TestSize.Level0) {
uint8_t buffer[] = {
0x01, 0x01
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
EXPECT_EQ(errCode, DMS_TLV_ERR_LEN);
};
RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr);
}
/**
* @tc.name: AbnormalPackageBadLength_002
* @tc.desc: abnormal package tlv node with zero-size length
* @tc.type: FUNC
* @tc.require: AR000E0ECR
*/
HWTEST_F(TlvParseTest, AbnormalPackageBadLength_002, TestSize.Level0) {
uint8_t buffer[] = {
0x01, 0x01, 0x00, 0x02, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69,
0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00,
0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65,
0x79, 0x00
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
EXPECT_EQ(errCode, DMS_TLV_ERR_LEN);
};
RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr);
}
/**
* @tc.name: AbnormalPackageBadLength_003
* @tc.desc: abnormal package with mismatched buffer size
* @tc.type: FUNC
* @tc.require: AR000E0DE0
*/
HWTEST_F(TlvParseTest, AbnormalPackageBadLength_003, TestSize.Level0) {
uint8_t buffer[] = {
0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68,
0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e,
0x63, 0x68, 0x65, 0x72, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69,
0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00,
0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65,
0x79, 0x00
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
EXPECT_EQ(errCode, DMS_TLV_ERR_LEN);
};
RunTest(buffer, sizeof(buffer) + 1, onTlvParseDone, nullptr);
}
/**
* @tc.name: AbnormalPackageBadLength_004
* @tc.desc: abnormal package with mismatched buffer size
* @tc.type: FUNC
* @tc.require: AR000E0DE0
*/
HWTEST_F(TlvParseTest, AbnormalPackageBadLength_004, TestSize.Level0) {
uint8_t buffer[] = {
0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68,
0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e,
0x63, 0x68, 0x65, 0x72, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69,
0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00,
0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65,
0x79, 0x00
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
EXPECT_EQ(errCode, DMS_TLV_ERR_LEN);
};
RunTest(buffer, sizeof(buffer) - 1, onTlvParseDone, nullptr);
}
/**
* @tc.name: AbnormalPackageBadLength_005
* @tc.desc: abnormal package with mismatched buffer size
* @tc.type: FUNC
* @tc.require: AR000E0DE0
*/
HWTEST_F(TlvParseTest, AbnormalPackageBadLength_005, TestSize.Level0) {
uint8_t buffer[] = {
0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68,
0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e,
0x63, 0x68, 0x65, 0x72, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69,
0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00,
0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65,
0x79, 0x00
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
bool condition = (errCode == DMS_TLV_ERR_LEN
|| errCode == DMS_TLV_ERR_BAD_NODE_NUM);
EXPECT_EQ(true, condition);
};
RunTest(buffer, MAX_DMS_MSG_LENGTH, onTlvParseDone, nullptr);
}
/**
* @tc.name: AbnormalPackageBadLength_006
* @tc.desc: abnormal package with mismatched buffer size
* @tc.type: FUNC
* @tc.require: AR000E0DE0
*/
HWTEST_F(TlvParseTest, AbnormalPackageBadLength_006, TestSize.Level0) {
uint8_t buffer[] = {
0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68,
0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e,
0x63, 0x68, 0x65, 0x72, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69,
0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00,
0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65,
0x79, 0x00
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
EXPECT_EQ(errCode, DMS_TLV_ERR_LEN);
};
RunTest(buffer, 0, onTlvParseDone, nullptr);
}
/**
* @tc.name: AbnormalPackageBadSource_001
* @tc.desc: abnormal package string field with no '\0' in the ending
* @tc.type: FUNC
* @tc.require: AR000E0DE0
*/
HWTEST_F(TlvParseTest, AbnormalPackageBadSource_001, TestSize.Level0) {
uint8_t buffer[] = {
0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68,
0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e,
0x63, 0x68, 0x65, 0x72, 0xff, 0x03, 0x0d, 0x4d, 0x61, 0x69,
0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0xff,
0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65,
0x79, 0xff
};
auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) {
EXPECT_EQ(errCode, DMS_TLV_ERR_BAD_SOURCE);
};
RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr);
}
}
}
| 35.725581 | 93 | 0.648744 |
f147a63ef44cc2117e7b3f5b5e19f0184f9e3d10 | 2,186 | cpp | C++ | src/randact/randomdata.cpp | nicholasjalbert/Thrille | 117dbdbe93f81eec9398a75aebc62543498363ac | [
"OLDAP-2.8"
] | 2 | 2015-02-19T13:15:08.000Z | 2018-05-30T05:34:15.000Z | src/randact/randomdata.cpp | nicholasjalbert/Thrille | 117dbdbe93f81eec9398a75aebc62543498363ac | [
"OLDAP-2.8"
] | null | null | null | src/randact/randomdata.cpp | nicholasjalbert/Thrille | 117dbdbe93f81eec9398a75aebc62543498363ac | [
"OLDAP-2.8"
] | null | null | null | #define UNLOCKASSERT
#include "randomdata.h"
RandomDataTester::RandomDataTester(thrID myself) : RandomActiveTester(myself) {
setTestingTargets();
printf("Random Active (Data) Testing started...\n");
printf("iid 1: %p, iid 2: %p\n", target1, target2);
}
RandomDataTester::RandomDataTester(thrID myself,
bool testing) : RandomActiveTester(myself) {
printf("TEST: Random Active (Data) Testing started...\n");
target1 = 0;
target2 = 0;
}
RandomDataTester::~RandomDataTester() {
if (raceFound) {
printf("Data Race Between %p and %p Found!\n",
target1, target2);
} else {
printf("Data Race Between %p and %p Not Reproduced\n",
target1, target2);
}
}
bool RandomDataTester::reenableThreadIfLegal(thrID thr) {
safe_assert(active_testing_paused[thr]);
active_testing_paused[thr] = false;
enableThread(thr);
return true;
}
void RandomDataTester::handleMyMemoryRead(thrID myself,
void * iid, void * addr) {
if (iid == target1 || iid == target2) {
ActiveRaceInfo tmp(myself, addr, false);
vector<thrID> racers = isRacing(tmp);
if (((int) racers.size()) > 0) {
raceFound = true;
if (log->getPrint()) {
printf("Racing access discovered\n");
}
enableSpecificActiveTestingPaused(racers);
} else {
active_testing_paused[myself] = true;
active_testing_info[myself] = tmp;
disableThread(myself);
}
}
}
void RandomDataTester::handleMyMemoryWrite(thrID myself,
void * iid, void * addr) {
if (iid == target1 || iid == target2) {
ActiveRaceInfo tmp(myself, addr, true);
vector<thrID> racers = isRacing(tmp);
if (((int) racers.size()) > 0) {
raceFound = true;
if (log->getPrint()) {
printf("Racing access discovered\n");
}
enableSpecificActiveTestingPaused(racers);
} else {
active_testing_paused[myself] = true;
active_testing_info[myself] = tmp;
disableThread(myself);
}
}
}
| 29.540541 | 79 | 0.587374 |
f149c82d43c60e6684a451990867bad9a9cb791c | 866 | cpp | C++ | InAirState.cpp | thomasvt/stuck | eb590f4218d8eb00199518c8f0c1d3225216d412 | [
"MIT"
] | 1 | 2022-03-13T09:02:50.000Z | 2022-03-13T09:02:50.000Z | InAirState.cpp | thomasvt/stuck | eb590f4218d8eb00199518c8f0c1d3225216d412 | [
"MIT"
] | 1 | 2022-03-13T09:04:33.000Z | 2022-03-13T18:56:32.000Z | InAirState.cpp | thomasvt/stuck | eb590f4218d8eb00199518c8f0c1d3225216d412 | [
"MIT"
] | null | null | null | #include <InAirState.h>
#include <Hero.h>
#include "HeroAnimations.h"
namespace actors
{
namespace hero
{
void InAirState::update(Hero& hero)
{
if (hero.rigid_body.is_on_floor())
hero.fsm_.change_state(HeroFsm::hero_state::on_floor);
if (hero.rigid_body.is_on_ladder() && !hero.rigid_body.is_going_up())
hero.fsm_.change_state(HeroFsm::hero_state::on_ladder);
const auto throttle8_x = hero.get_throttle8_x();
hero.rigid_body.set_velocity8_x(throttle8_x); // no inertia, classic feel
// bit dirty. can only do this because these animations are only 1 frame.
hero.animation_player_.set_animation(hero.rigid_body.is_going_up() ? &animations::hero::jump : &animations::hero::fall);
}
void InAirState::on_enter(Hero& hero)
{
hero.rigid_body.is_gravity_enabled = true;
}
void InAirState::on_exit(Hero& hero)
{
}
}
}
| 26.242424 | 123 | 0.720554 |
f149d8f61c22066d21811d6764bdac4816de4330 | 5,484 | cpp | C++ | external/webkit/Source/WebCore/bindings/v8/PageScriptDebugServer.cpp | ghsecuritylab/android_platform_sony_nicki | 526381be7808e5202d7865aa10303cb5d249388a | [
"Apache-2.0"
] | 6 | 2017-05-31T01:46:45.000Z | 2018-06-12T10:53:30.000Z | Source/WebCore/bindings/v8/PageScriptDebugServer.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 2 | 2017-07-25T09:37:22.000Z | 2017-08-04T07:18:56.000Z | Source/WebCore/bindings/v8/PageScriptDebugServer.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 2 | 2017-07-17T06:02:42.000Z | 2018-09-19T10:08:38.000Z | /*
* Copyright (c) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "PageScriptDebugServer.h"
#if ENABLE(JAVASCRIPT_DEBUGGER)
#include "Frame.h"
#include "Page.h"
#include "ScriptDebugListener.h"
#include "V8Binding.h"
#include "V8DOMWindow.h"
#include "V8Proxy.h"
#include <wtf/OwnPtr.h>
#include <wtf/PassOwnPtr.h>
#include <wtf/StdLibExtras.h>
namespace WebCore {
static Frame* retrieveFrame(v8::Handle<v8::Context> context)
{
if (context.IsEmpty())
return 0;
// Test that context has associated global dom window object.
v8::Handle<v8::Object> global = context->Global();
if (global.IsEmpty())
return 0;
global = V8DOMWrapper::lookupDOMWrapper(V8DOMWindow::GetTemplate(), global);
if (global.IsEmpty())
return 0;
return V8Proxy::retrieveFrame(context);
}
PageScriptDebugServer& PageScriptDebugServer::shared()
{
DEFINE_STATIC_LOCAL(PageScriptDebugServer, server, ());
return server;
}
PageScriptDebugServer::PageScriptDebugServer()
: ScriptDebugServer()
, m_pausedPage(0)
, m_enabled(true)
{
}
void PageScriptDebugServer::addListener(ScriptDebugListener* listener, Page* page)
{
if (!m_enabled)
return;
V8Proxy* proxy = V8Proxy::retrieve(page->mainFrame());
if (!proxy)
return;
v8::HandleScope scope;
v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
v8::Context::Scope contextScope(debuggerContext);
if (!m_listenersMap.size()) {
ensureDebuggerScriptCompiled();
ASSERT(!m_debuggerScript.get()->IsUndefined());
v8::Debug::SetDebugEventListener2(&PageScriptDebugServer::v8DebugEventCallback, v8::External::New(this));
}
m_listenersMap.set(page, listener);
V8DOMWindowShell* shell = proxy->windowShell();
if (!shell->isContextInitialized())
return;
v8::Handle<v8::Context> context = shell->context();
v8::Handle<v8::Function> getScriptsFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.get()->Get(v8::String::New("getScripts")));
v8::Handle<v8::Value> argv[] = { context->GetData() };
v8::Handle<v8::Value> value = getScriptsFunction->Call(m_debuggerScript.get(), 1, argv);
if (value.IsEmpty())
return;
ASSERT(!value->IsUndefined() && value->IsArray());
v8::Handle<v8::Array> scriptsArray = v8::Handle<v8::Array>::Cast(value);
for (unsigned i = 0; i < scriptsArray->Length(); ++i)
dispatchDidParseSource(listener, v8::Handle<v8::Object>::Cast(scriptsArray->Get(v8::Integer::New(i))));
}
void PageScriptDebugServer::removeListener(ScriptDebugListener* listener, Page* page)
{
if (!m_listenersMap.contains(page))
return;
if (m_pausedPage == page)
continueProgram();
m_listenersMap.remove(page);
if (m_listenersMap.isEmpty())
v8::Debug::SetDebugEventListener(0);
// FIXME: Remove all breakpoints set by the agent.
}
void PageScriptDebugServer::setClientMessageLoop(PassOwnPtr<ClientMessageLoop> clientMessageLoop)
{
m_clientMessageLoop = clientMessageLoop;
}
ScriptDebugListener* PageScriptDebugServer::getDebugListenerForContext(v8::Handle<v8::Context> context)
{
v8::HandleScope scope;
Frame* frame = retrieveFrame(context);
if (!frame)
return 0;
return m_listenersMap.get(frame->page());
}
void PageScriptDebugServer::runMessageLoopOnPause(v8::Handle<v8::Context> context)
{
v8::HandleScope scope;
Frame* frame = retrieveFrame(context);
m_pausedPage = frame->page();
// Wait for continue or step command.
m_clientMessageLoop->run(m_pausedPage);
// The listener may have been removed in the nested loop.
if (ScriptDebugListener* listener = m_listenersMap.get(m_pausedPage))
listener->didContinue();
m_pausedPage = 0;
}
void PageScriptDebugServer::quitMessageLoopOnPause()
{
m_clientMessageLoop->quitNow();
}
} // namespace WebCore
#endif // ENABLE(JAVASCRIPT_DEBUGGER)
| 33.036145 | 140 | 0.715536 |
f14b22aad4767d594ef33df2293217cfc40f5233 | 4,355 | cc | C++ | video.cc | SolraBizna/teg | 05a307f2f3b359f3462cba23e15dbda8d6af66fc | [
"Zlib"
] | null | null | null | video.cc | SolraBizna/teg | 05a307f2f3b359f3462cba23e15dbda8d6af66fc | [
"Zlib"
] | null | null | null | video.cc | SolraBizna/teg | 05a307f2f3b359f3462cba23e15dbda8d6af66fc | [
"Zlib"
] | null | null | null | #include "video.hh"
#include "config.hh"
#include "xgl.hh"
using namespace Video;
const uint32_t Video::uninitialized_context_cookie = 0;
uint32_t Video::opengl_context_cookie = uninitialized_context_cookie;
#ifndef DEFAULT_WINDOWED_WIDTH
#define DEFAULT_WINDOWED_WIDTH 640
#endif
#ifndef DEFAULT_WINDOWED_HEIGHT
#define DEFAULT_WINDOWED_HEIGHT 480
#endif
int32_t Video::fullscreen_width = 0, Video::fullscreen_height = 0;
int32_t Video::windowed_width = DEFAULT_WINDOWED_WIDTH,
Video::windowed_height = DEFAULT_WINDOWED_HEIGHT;
bool Video::fullscreen_mode = true;
bool Video::vsync = false;
static const char* video_config_file = "Video Configuration.utxt";
static const Config::Element video_config_elements[] = {
Config::Element("fullscreen_width", fullscreen_width),
Config::Element("fullscreen_height", fullscreen_height),
Config::Element("windowed_width", windowed_width),
Config::Element("windowed_height", windowed_height),
Config::Element("fullscreen_mode", fullscreen_mode),
Config::Element("vsync", vsync),
};
static SDL_Window* window = NULL;
static SDL_GLContext glcontext = NULL;
static bool inited = false;
static bool window_visible = true, window_minimized = false;
void Video::Kill() {
if(inited) {
SDL_Quit();
inited = false;
}
}
void Video::Init() {
if(!inited) {
if(SDL_Init(SDL_INIT_VIDEO))
die("Couldn't initialize SDL!");
inited = true;
}
if(glcontext) SDL_GL_DeleteContext(glcontext);
if(window) SDL_DestroyWindow(window);
int target_w, target_h;
Uint32 flags = SDL_WINDOW_OPENGL;
if(fullscreen_mode) {
target_w = fullscreen_width;
target_h = fullscreen_height;
if(target_w == 0 || target_h == 0)
flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
else
flags |= SDL_WINDOW_FULLSCREEN;
}
else {
target_w = windowed_width;
target_h = windowed_height;
}
do {
/* sanity */
if(target_w < 320) target_w = 320;
else if(target_h < 240) target_h = 240;
window = SDL_CreateWindow(GAME_WINDOW_TITLE,
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
target_w, target_h, flags);
if(window) break;
else if(flags & SDL_WINDOW_FULLSCREEN) {
fprintf(stderr, "Fullscreen mode %i x %i failed. Trying a window.\n",
target_w, target_h);
flags &= ~(SDL_WINDOW_FULLSCREEN_DESKTOP);
target_w = windowed_width;
target_h = windowed_height;
}
else
die("Could not create a window no matter how hard we tried. The last reason SDL gave was: %s", SDL_GetError());
} while(1);
/* TODO: set minimized/visible state? */
dprintf("SDL_CreateWindow(..., %i, %i, 0x%x) succeeded.\n",
target_w, target_h, flags);
glcontext = SDL_GL_CreateContext(window);
if(!glcontext)
die("Could not create an OpenGL context. The reason SDL gave was: %s", SDL_GetError());
++opengl_context_cookie;
dprintf("OpenGL initialized. Context cookie is %i.\n",
opengl_context_cookie);
xgl::Initialize();
/* OpenGL context setup */
glPixelStorei(GL_PACK_ALIGNMENT, TEG_PIXEL_PACK);
glPixelStorei(GL_UNPACK_ALIGNMENT, TEG_PIXEL_PACK);
}
void Video::ReadConfig() {
Config::Read(video_config_file, video_config_elements, elementcount(video_config_elements));
}
void Video::WriteConfig() {
Config::Write(video_config_file, video_config_elements, elementcount(video_config_elements));
}
uint32_t Video::GetScreenWidth() {
int w, h;
SDL_GL_GetDrawableSize(window, &w, &h);
return w;
}
uint32_t Video::GetScreenHeight() {
int w, h;
SDL_GL_GetDrawableSize(window, &w, &h);
return h;
}
double Video::GetAspect() {
int w, h;
SDL_GL_GetDrawableSize(window, &w, &h);
return (double)w / h;
}
void Video::Swap() {
SDL_GL_SwapWindow(window);
}
bool Video::IsScreenActive() {
return window_visible && !window_minimized;
}
bool Video::HandleEvent(SDL_Event& evt) {
switch(evt.type) {
case SDL_WINDOWEVENT:
switch(evt.window.event) {
case SDL_WINDOWEVENT_SHOWN:
window_visible = true;
break;
case SDL_WINDOWEVENT_HIDDEN:
window_visible = false;
break;
case SDL_WINDOWEVENT_MINIMIZED:
window_minimized = true;
break;
case SDL_WINDOWEVENT_RESTORED:
window_minimized = false;
break;
}
return true;
}
return false;
}
| 27.738854 | 117 | 0.702181 |
f14c2349718a37f8d01d88242163e8662d181f54 | 14,692 | cpp | C++ | OgreMain/src/OgreASTCCodec.cpp | resttime/ogre-next | 7435e60bd6df422d2fb4c742a493c3f37ef9a7a9 | [
"MIT"
] | 701 | 2019-09-08T15:56:41.000Z | 2022-03-31T05:51:26.000Z | OgreMain/src/OgreASTCCodec.cpp | resttime/ogre-next | 7435e60bd6df422d2fb4c742a493c3f37ef9a7a9 | [
"MIT"
] | 204 | 2019-09-01T23:02:32.000Z | 2022-03-28T14:58:39.000Z | OgreMain/src/OgreASTCCodec.cpp | resttime/ogre-next | 7435e60bd6df422d2fb4c742a493c3f37ef9a7a9 | [
"MIT"
] | 188 | 2019-09-05T05:14:46.000Z | 2022-03-22T21:51:39.000Z | /*
-----------------------------------------------------------------------------
This source file is part of OGRE-Next
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreASTCCodec.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
namespace Ogre {
const uint32 ASTC_MAGIC = 0x5CA1AB13;
typedef struct
{
uint8 magic[4];
uint8 blockdim_x;
uint8 blockdim_y;
uint8 blockdim_z;
uint8 xsize[3]; // x-size = xsize[0] + xsize[1] + xsize[2]
uint8 ysize[3]; // x-size, y-size and z-size are given in texels;
uint8 zsize[3]; // block count is inferred
} ASTCHeader;
float ASTCCodec::getBitrateForPixelFormat(PixelFormatGpu fmt)
{
switch (fmt)
{
case PFG_ASTC_RGBA_UNORM_4X4_LDR:
return 8.00;
case PFG_ASTC_RGBA_UNORM_5X4_LDR:
return 6.40;
case PFG_ASTC_RGBA_UNORM_5X5_LDR:
return 5.12;
case PFG_ASTC_RGBA_UNORM_6X5_LDR:
return 4.27;
case PFG_ASTC_RGBA_UNORM_6X6_LDR:
return 3.56;
case PFG_ASTC_RGBA_UNORM_8X5_LDR:
return 3.20;
case PFG_ASTC_RGBA_UNORM_8X6_LDR:
return 2.67;
case PFG_ASTC_RGBA_UNORM_8X8_LDR:
return 2.00;
case PFG_ASTC_RGBA_UNORM_10X5_LDR:
return 2.56;
case PFG_ASTC_RGBA_UNORM_10X6_LDR:
return 2.13;
case PFG_ASTC_RGBA_UNORM_10X8_LDR:
return 1.60;
case PFG_ASTC_RGBA_UNORM_10X10_LDR:
return 1.28;
case PFG_ASTC_RGBA_UNORM_12X10_LDR:
return 1.07;
case PFG_ASTC_RGBA_UNORM_12X12_LDR:
return 0.89;
default:
return 0;
}
}
// Utility function to determine 2D block dimensions from a target bitrate. Used for 3D textures.
// Taken from astc_toplevel.cpp in ARM's ASTC Evaluation Codec
void ASTCCodec::getClosestBlockDim2d(float targetBitrate, int *x, int *y) const
{
int blockdims[6] = { 4, 5, 6, 8, 10, 12 };
float best_error = 1000;
float aspect_of_best = 1;
int i, j;
// Y dimension
for (i = 0; i < 6; i++)
{
// X dimension
for (j = i; j < 6; j++)
{
// NxN MxN 8x5 10x5 10x6
int is_legal = (j==i) || (j==i+1) || (j==3 && i==1) || (j==4 && i==1) || (j==4 && i==2);
if(is_legal)
{
float bitrate = 128.0f / (blockdims[i] * blockdims[j]);
float bitrate_error = fabs(bitrate - targetBitrate);
float aspect = (float)blockdims[j] / blockdims[i];
if (bitrate_error < best_error || (bitrate_error == best_error && aspect < aspect_of_best))
{
*x = blockdims[j];
*y = blockdims[i];
best_error = bitrate_error;
aspect_of_best = aspect;
}
}
}
}
}
// Taken from astc_toplevel.cpp in ARM's ASTC Evaluation Codec
void ASTCCodec::getClosestBlockDim3d(float targetBitrate, int *x, int *y, int *z)
{
int blockdims[4] = { 3, 4, 5, 6 };
float best_error = 1000;
float aspect_of_best = 1;
int i, j, k;
for (i = 0; i < 4; i++) // Z
{
for (j = i; j < 4; j++) // Y
{
for (k = j; k < 4; k++) // X
{
// NxNxN MxNxN MxMxN
int is_legal = ((k==j)&&(j==i)) || ((k==j+1)&&(j==i)) || ((k==j)&&(j==i+1));
if(is_legal)
{
float bitrate = 128.0f / (blockdims[i] * blockdims[j] * blockdims[k]);
float bitrate_error = fabs(bitrate - targetBitrate);
float aspect = (float)blockdims[k] / blockdims[j] + (float)blockdims[j] / blockdims[i] + (float)blockdims[k] / blockdims[i];
if (bitrate_error < best_error || (bitrate_error == best_error && aspect < aspect_of_best))
{
*x = blockdims[k];
*y = blockdims[j];
*z = blockdims[i];
best_error = bitrate_error;
aspect_of_best = aspect;
}
}
}
}
}
}
size_t ASTCCodec::getMemorySize( uint32 width, uint32 height, uint32 depth,
int32 xdim, int32 ydim, PixelFormatGpu fmt )
{
float bitrate = getBitrateForPixelFormat(fmt);
int32 zdim = 1;
if(depth > 1)
{
getClosestBlockDim3d(bitrate, &xdim, &ydim, &zdim);
}
int xblocks = (width + xdim - 1) / xdim;
int yblocks = (height + ydim - 1) / ydim;
int zblocks = (depth + zdim - 1) / zdim;
return xblocks * yblocks * zblocks * 16;
}
//---------------------------------------------------------------------
ASTCCodec* ASTCCodec::msInstance = 0;
//---------------------------------------------------------------------
void ASTCCodec::startup()
{
if (!msInstance)
{
msInstance = OGRE_NEW ASTCCodec();
Codec::registerCodec(msInstance);
}
LogManager::getSingleton().logMessage(LML_NORMAL,
"ASTC codec registering");
}
//---------------------------------------------------------------------
void ASTCCodec::shutdown()
{
if(msInstance)
{
Codec::unregisterCodec(msInstance);
OGRE_DELETE msInstance;
msInstance = 0;
}
}
//---------------------------------------------------------------------
ASTCCodec::ASTCCodec():
mType("astc")
{
}
//---------------------------------------------------------------------
DataStreamPtr ASTCCodec::encode(MemoryDataStreamPtr& input, Codec::CodecDataPtr& pData) const
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"ASTC encoding not supported",
"ASTCCodec::encode" ) ;
}
//---------------------------------------------------------------------
void ASTCCodec::encodeToFile(MemoryDataStreamPtr& input,
const String& outFileName, Codec::CodecDataPtr& pData) const
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"ASTC encoding not supported",
"ASTCCodec::encodeToFile" ) ;
}
//---------------------------------------------------------------------
Codec::DecodeResult ASTCCodec::decode(DataStreamPtr& stream) const
{
ASTCHeader header;
// Read the ASTC header
stream->read(&header, sizeof(ASTCHeader));
if( memcmp( &ASTC_MAGIC, &header.magic, sizeof(uint32) ) != 0 )
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"This is not a valid ASTC file!", "ASTCCodec::decode");
}
int xdim = header.blockdim_x;
int ydim = header.blockdim_y;
int zdim = header.blockdim_z;
int xsize = header.xsize[0] + 256 * header.xsize[1] + 65536 * header.xsize[2];
int ysize = header.ysize[0] + 256 * header.ysize[1] + 65536 * header.ysize[2];
int zsize = header.zsize[0] + 256 * header.zsize[1] + 65536 * header.zsize[2];
ImageData2 *imgData = OGRE_NEW ImageData2();
imgData->box.width = xsize;
imgData->box.height = ysize;
imgData->box.depth = zsize;
imgData->box.numSlices = 1u; //Always one face, cubemaps are not currently supported
imgData->numMipmaps = 1u; // Always 1 mip level per file (ASTC file restriction)
if( zsize <= 1 )
imgData->textureType = TextureTypes::Type2D;
else
imgData->textureType = TextureTypes::Type3D;
// For 3D we calculate the bitrate then find the nearest 2D block size.
if(zdim > 1)
{
float bitrate = 128.0f / (xdim * ydim * zdim);
getClosestBlockDim2d(bitrate, &xdim, &ydim);
}
if(xdim == 4)
{
imgData->format = PFG_ASTC_RGBA_UNORM_4X4_LDR;
}
else if(xdim == 5)
{
if(ydim == 4)
imgData->format = PFG_ASTC_RGBA_UNORM_5X4_LDR;
else if(ydim == 5)
imgData->format = PFG_ASTC_RGBA_UNORM_5X5_LDR;
}
else if(xdim == 6)
{
if(ydim == 5)
imgData->format = PFG_ASTC_RGBA_UNORM_6X5_LDR;
else if(ydim == 6)
imgData->format = PFG_ASTC_RGBA_UNORM_6X6_LDR;
}
else if(xdim == 8)
{
if(ydim == 5)
imgData->format = PFG_ASTC_RGBA_UNORM_8X5_LDR;
else if(ydim == 6)
imgData->format = PFG_ASTC_RGBA_UNORM_8X6_LDR;
else if(ydim == 8)
imgData->format = PFG_ASTC_RGBA_UNORM_8X8_LDR;
}
else if(xdim == 10)
{
if(ydim == 5)
imgData->format = PFG_ASTC_RGBA_UNORM_10X5_LDR;
else if(ydim == 6)
imgData->format = PFG_ASTC_RGBA_UNORM_10X6_LDR;
else if(ydim == 8)
imgData->format = PFG_ASTC_RGBA_UNORM_10X8_LDR;
else if(ydim == 10)
imgData->format = PFG_ASTC_RGBA_UNORM_10X10_LDR;
}
else if(xdim == 12)
{
if(ydim == 10)
imgData->format = PFG_ASTC_RGBA_UNORM_12X10_LDR;
else if(ydim == 12)
imgData->format = PFG_ASTC_RGBA_UNORM_12X12_LDR;
}
const uint32 rowAlignment = 4u;
// imgData->box.bytesPerPixel = PixelFormatGpuUtils::getBytesPerPixel( imgData->format );
imgData->box.setCompressedPixelFormat( imgData->format );
imgData->box.bytesPerRow = PixelFormatGpuUtils::getSizeBytes( imgData->box.width,
1u, 1u, 1u,
imgData->format,
rowAlignment );
imgData->box.bytesPerImage = PixelFormatGpuUtils::getSizeBytes( imgData->box.width,
imgData->box.height,
1u, 1u,
imgData->format,
rowAlignment );
const size_t requiredBytes = PixelFormatGpuUtils::calculateSizeBytes( imgData->box.width,
imgData->box.height,
imgData->box.depth,
imgData->box.numSlices,
imgData->format,
imgData->numMipmaps,
rowAlignment );
// Bind output buffer
imgData->box.data = OGRE_MALLOC_SIMD( requiredBytes, MEMCATEGORY_RESOURCE );
// Now deal with the data
stream->read( imgData->box.data, requiredBytes );
DecodeResult ret;
ret.first.reset();
ret.second = CodecDataPtr( imgData );
return ret;
}
//---------------------------------------------------------------------
String ASTCCodec::getType() const
{
return mType;
}
//---------------------------------------------------------------------
void ASTCCodec::flipEndian(void * pData, size_t size, size_t count) const
{
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
for(unsigned int index = 0; index < count; index++)
{
flipEndian((void *)((long)pData + (index * size)), size);
}
#endif
}
//---------------------------------------------------------------------
void ASTCCodec::flipEndian(void * pData, size_t size) const
{
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
char swapByte;
for(unsigned int byteIndex = 0; byteIndex < size/2; byteIndex++)
{
swapByte = *(char *)((long)pData + byteIndex);
*(char *)((long)pData + byteIndex) = *(char *)((long)pData + size - byteIndex - 1);
*(char *)((long)pData + size - byteIndex - 1) = swapByte;
}
#endif
}
//---------------------------------------------------------------------
String ASTCCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const
{
if (maxbytes >= sizeof(uint32))
{
uint32 fileType;
memcpy(&fileType, magicNumberPtr, sizeof(uint32));
flipEndian(&fileType, sizeof(uint32), 1);
if (ASTC_MAGIC == fileType)
return String("astc");
}
return BLANKSTRING;
}
}
| 37.865979 | 148 | 0.487953 |
f14ccaa4af8babd8f33583d2a19d07f1d66fe96b | 1,409 | hh | C++ | include/Activia/ActGuiInput.hh | UniversityofWarwick/ACTIVIA | bbd0dfa71337602f94d911fa5101a440e8c16606 | [
"BSL-1.0"
] | 1 | 2020-11-04T08:32:23.000Z | 2020-11-04T08:32:23.000Z | include/Activia/ActGuiInput.hh | UniversityofWarwick/ACTIVIA | bbd0dfa71337602f94d911fa5101a440e8c16606 | [
"BSL-1.0"
] | null | null | null | include/Activia/ActGuiInput.hh | UniversityofWarwick/ACTIVIA | bbd0dfa71337602f94d911fa5101a440e8c16606 | [
"BSL-1.0"
] | 1 | 2020-11-04T08:32:30.000Z | 2020-11-04T08:32:30.000Z | #ifdef ACT_USE_QT
#ifndef ACT_GUI_INPUT_HH
#define ACT_GUI_INPUT_HH
#include "Activia/ActAbsInput.hh"
#include "Activia/ActOutputSelection.hh"
#include "Activia/ActGuiWindow.hh"
#include <iostream>
#include <fstream>
#include <string>
/// \brief Define the inputs (target, products, spectrum, algorithms) for the code via a GUI
class ActGuiInput : public ActAbsInput {
public:
/// Default constructor
ActGuiInput();
/// Constructor
ActGuiInput(ActOutputSelection* outputSelection, ActGuiWindow* theGui);
/// Destructor
virtual ~ActGuiInput();
/// Define the target isotopes
virtual void defineTarget();
/// Specify the calculation mode
virtual void defineCalcMode();
/// Define the product isotopes
virtual void defineNuclides();
/// Define the input beam spectrum
virtual void defineSpectrum();
/// Specify the cross-section algorithm
virtual void specifyXSecAlgorithm();
/// Define the exposure and decay times for radioactive decay yield calculations
virtual void defineTime();
/// Specify the decay yield calculation algorithm
virtual void specifyDecayAlgorithm();
/// Define the output file names, format and level of detail.
virtual void specifyOutput();
/// Print out the available calculation options.
virtual void printOptions(std::ofstream&) {;}
protected:
private:
void printIntro() {;}
ActGuiWindow* _theGui;
};
#endif
#endif
| 23.483333 | 92 | 0.74237 |
f14dd9ea676999232cb222f6795a7e021eb553e4 | 488 | cpp | C++ | Leetcode/Leaf-Similar Trees.cpp | Lucifermaniraj/Hacktoberfest2021 | ec62edfad0d483e4b65874f37c0142d7154adb7b | [
"MIT"
] | null | null | null | Leetcode/Leaf-Similar Trees.cpp | Lucifermaniraj/Hacktoberfest2021 | ec62edfad0d483e4b65874f37c0142d7154adb7b | [
"MIT"
] | null | null | null | Leetcode/Leaf-Similar Trees.cpp | Lucifermaniraj/Hacktoberfest2021 | ec62edfad0d483e4b65874f37c0142d7154adb7b | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> v;
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> v1, v2;
leaves(root1, v1);
leaves(root2, v2);
return v1==v2;
}
void leaves(TreeNode* root, vector<int>& v) {
if(!root)
return;
if(!root->left && !root->right)
v.push_back(root->val);
leaves(root->left, v);
leaves(root->right, v);
}
}; | 21.217391 | 56 | 0.471311 |
f14f99a466eaf87278065fade561b9f0e0ae7cae | 1,097 | hpp | C++ | libraries/include/Engine/Shader.hpp | kermado/Total-Resistance | debaf40ba3be6590a70c9922e1d1a5e075f4ede3 | [
"MIT"
] | 3 | 2015-04-25T22:57:58.000Z | 2019-11-05T18:36:31.000Z | libraries/include/Engine/Shader.hpp | kermado/Total-Resistance | debaf40ba3be6590a70c9922e1d1a5e075f4ede3 | [
"MIT"
] | 1 | 2016-06-23T15:22:41.000Z | 2016-06-23T15:22:41.000Z | libraries/include/Engine/Shader.hpp | kermado/Total-Resistance | debaf40ba3be6590a70c9922e1d1a5e075f4ede3 | [
"MIT"
] | null | null | null | #ifndef SHADER_H
#define SHADER_H
#include <string>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <Engine/NonCopyable.hpp>
namespace Engine
{
class Shader : private NonCopyable
{
public:
/**
* Shader types.
*/
enum Type
{
VertexShader = GL_VERTEX_SHADER,
FragmentShader = GL_FRAGMENT_SHADER
};
/**
* Constructor.
*
* @param shaderType Type of shader.
*/
Shader(Type shaderType);
/**
* Destructor.
*/
~Shader();
/**
* Initializes the shader from the specified source code file and
* attempts to compile it.
*
* @param filename Path to the shader source code file.
* @return True if shader was initialized successfully.
*/
bool LoadFromFile(std::string filename);
/**
* Returns the type of the shader.
*
* @return Shader type.
*/
Type GetShaderType() const;
/**
* Returns the shader object identifier.
*
* @return Shader ID.
*/
GLuint GetId() const;
private:
/**
* Shader object identifier.
*/
GLuint m_id;
/**
* Shader type.
*/
Type m_type;
};
}
#endif
| 14.824324 | 67 | 0.621696 |
f150a727cad6a3e7269e4ced9a2a70305180e5ea | 6,816 | hpp | C++ | include/intent/utils/Logger.hpp | open-intent-io/open-intent | 57d8c4fc89c038f51138d51e776880e728152194 | [
"MIT"
] | 47 | 2016-07-05T15:20:33.000Z | 2021-08-06T05:38:33.000Z | include/intent/utils/Logger.hpp | open-intent-io/open-intent | 57d8c4fc89c038f51138d51e776880e728152194 | [
"MIT"
] | 30 | 2016-07-03T22:42:11.000Z | 2017-11-17T15:58:10.000Z | include/intent/utils/Logger.hpp | open-intent-io/open-intent | 57d8c4fc89c038f51138d51e776880e728152194 | [
"MIT"
] | 8 | 2016-07-22T20:07:58.000Z | 2017-11-05T10:40:29.000Z | /*
|---------------------------------------------------------|
| ___ ___ _ _ |
| / _ \ _ __ ___ _ __ |_ _|_ __ | |_ ___ _ __ | |_ |
| | | | | '_ \ / _ \ '_ \ | || '_ \| __/ _ \ '_ \| __| |
| | |_| | |_) | __/ | | || || | | | || __/ | | | |_ |
| \___/| .__/ \___|_| |_|___|_| |_|\__\___|_| |_|\__| |
| |_| |
| |
| - The users first... |
| |
| Authors: |
| - Clement Michaud |
| - Sergei Kireev |
| |
| Version: 1.0.0 |
| |
|---------------------------------------------------------|
The MIT License (MIT)
Copyright (c) 2016 - Clement Michaud, Sergei Kireev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef INTENT_LOGGER_HPP
#define INTENT_LOGGER_HPP
#include <iostream>
#include "spdlog/spdlog.h"
#include <string>
#include <sstream>
namespace intent {
namespace log {
class Logger {
public:
/**
* \brief The severity levels handled by the logger
*/
struct SeverityLevel {
enum type { TRACE, DEBUG, INFO, WARNING, ERROR, FATAL };
};
/**
* @brief Initialize the logging system with the maximum severity level to
* use.
* \param severityLevel The maximum severity level to use.
*/
static void initialize(SeverityLevel::type severityLevel);
/**
* @brief Return the severity type for string. Return FATAL if nothing is
* matching.
* @param severity The string to convert into severity level
* @return the severity level
*/
static SeverityLevel::type severityLevelFromString(
const std::string& severity);
/**
* @brief Get the static instance of the logger
* \return The logger instance
*/
static Logger& getInstance() {
static Logger* logger = NULL;
if (logger == NULL) {
logger = new Logger();
SeverityLevel::type initialLevel = SeverityLevel::FATAL;
if (const char* env_p = std::getenv("LOG_LEVEL")) {
initialLevel = Logger::severityLevelFromString(env_p);
}
initialize(initialLevel);
}
return *logger;
}
template <int v>
struct Int2Type {
enum { value = v };
};
/**
* \brief Logger by level of severity.
*/
template <SeverityLevel::type LogLevel>
class LoggerWithLevel {
public:
/**
* \brief Log a message from a string stream.
*/
LoggerWithLevel& operator<<(const std::stringstream& message) {
//*this << message;
return *this;
}
/**
* \brief Log a message from an object that supports the stream operator.
*/
template <typename T>
LoggerWithLevel& operator<<(const T& message) {
std::stringstream ss;
ss << message;
log(ss.str(), Int2Type<LogLevel>());
return *this;
}
private:
void log(const std::string& message, Int2Type<SeverityLevel::TRACE>) {
spdlog::get("console")->trace(message);
}
void log(const std::string& message, Int2Type<SeverityLevel::DEBUG>) {
spdlog::get("console")->debug(message);
}
void log(const std::string& message, Int2Type<SeverityLevel::INFO>) {
spdlog::get("console")->info(message);
}
void log(const std::string& message, Int2Type<SeverityLevel::WARNING>) {
spdlog::get("console")->warn(message);
}
void log(const std::string& message, Int2Type<SeverityLevel::ERROR>) {
spdlog::get("console")->error(message);
}
void log(const std::string& message, Int2Type<SeverityLevel::FATAL>) {
spdlog::get("console")->critical(message);
}
};
/**
* @brief Get the trace logger
* \return the trace logger
*/
inline LoggerWithLevel<Logger::SeverityLevel::TRACE>& trace() {
return m_loggerTrace;
}
/**
* @brief Get the debug logger
* \return the debug logger
*/
inline LoggerWithLevel<Logger::SeverityLevel::DEBUG>& debug() {
return m_loggerDebug;
}
/**
* @brief Get the info logger
* \return the info logger
*/
inline LoggerWithLevel<Logger::SeverityLevel::INFO>& info() {
return m_loggerInfo;
}
/**
* @brief Get the warning logger
* \return the warning logger
*/
inline LoggerWithLevel<Logger::SeverityLevel::WARNING>& warning() {
return m_loggerWarning;
}
/**
* @brief Get the error logger
* \return the error logger
*/
inline LoggerWithLevel<Logger::SeverityLevel::ERROR>& error() {
return m_loggerError;
}
/**
* @brief Get the fatal logger
* \return the fatal logger
*/
inline LoggerWithLevel<Logger::SeverityLevel::FATAL>& fatal() {
return m_loggerFatal;
}
private:
Logger() {}
LoggerWithLevel<Logger::SeverityLevel::TRACE> m_loggerTrace;
LoggerWithLevel<Logger::SeverityLevel::DEBUG> m_loggerDebug;
LoggerWithLevel<Logger::SeverityLevel::INFO> m_loggerInfo;
LoggerWithLevel<Logger::SeverityLevel::WARNING> m_loggerWarning;
LoggerWithLevel<Logger::SeverityLevel::ERROR> m_loggerError;
LoggerWithLevel<Logger::SeverityLevel::FATAL> m_loggerFatal;
};
}
}
#define INTENT_LOG_TRACE() intent::log::Logger::getInstance().trace()
#define INTENT_LOG_DEBUG() intent::log::Logger::getInstance().debug()
#define INTENT_LOG_INFO() intent::log::Logger::getInstance().info()
#define INTENT_LOG_WARNING() intent::log::Logger::getInstance().warning()
#define INTENT_LOG_ERROR() intent::log::Logger::getInstance().error()
#define INTENT_LOG_FATAL() intent::log::Logger::getInstance().fatal()
#endif
| 30.841629 | 79 | 0.606808 |
f15150a1d26756736ba76e08aba31173a98f6fe0 | 1,631 | hpp | C++ | PhysicsSandbox/Physics2dTCS/Physics2dStandardTCS.hpp | jodavis42/PhysicsSandbox | 3119caaa77721041440cdc1b3cf96d4bd9e2d98b | [
"MIT"
] | 1 | 2022-03-26T21:08:19.000Z | 2022-03-26T21:08:19.000Z | PhysicsSandbox/Physics2dTCS/Physics2dStandardTCS.hpp | jodavis42/PhysicsSandbox | 3119caaa77721041440cdc1b3cf96d4bd9e2d98b | [
"MIT"
] | null | null | null | PhysicsSandbox/Physics2dTCS/Physics2dStandardTCS.hpp | jodavis42/PhysicsSandbox | 3119caaa77721041440cdc1b3cf96d4bd9e2d98b | [
"MIT"
] | null | null | null | #pragma once
#include "Common/CommonStandard.hpp"
#include "Physics2dCore/Detection/Broadphase/BroadphaseLayerType.hpp"
namespace SandboxGeometry
{
class Ray2d;
class RayResult2d;
}//SandboxBroadphase2d
namespace SandboxBroadphase2d
{
class IBroadphase2d;
}//SandboxBroadphase2d
namespace Physics2dCore
{
class RigidBody2d;
class Collider2d;
class Physics2dEffect;
class PropertyChangedEvent;
class Collider2dPair;
class ContactManifold2d;
class IBroadphase2dManager;
class Collider2dRaycastResult;
class IConstraint2dSolver;
class SimpleConstraint2dSolver;
}//namespace Physics2dCore
namespace Physics2dTCS
{
using Math::Vector2;
using Math::Vector3;
using Math::Vector4;
using Math::Matrix2;
using Math::Matrix3;
using Math::Matrix4;
using Math::Quaternion;
using Ray2d = SandboxGeometry::Ray2d;
using RayResult2d = SandboxGeometry::RayResult2d;
using IBroadphase2d = SandboxBroadphase2d::IBroadphase2d;
using RigidBody2d = Physics2dCore::RigidBody2d;
using Collider2d = Physics2dCore::Collider2d;
using Physics2dEffect = Physics2dCore::Physics2dEffect;
using Collider2dRaycastResult = Physics2dCore::Collider2dRaycastResult;
using PropertyChangedEvent = Physics2dCore::PropertyChangedEvent;
using IBroadphase2dManager = Physics2dCore::IBroadphase2dManager;
using IConstraint2dSolver = Physics2dCore::IConstraint2dSolver;
using SimpleConstraint2dSolver = Physics2dCore::SimpleConstraint2dSolver;
namespace BroadphaseLayerType = Physics2dCore::BroadphaseLayerType;
template <typename T>
using Array = Zero::Array<T>;
class PhysicsSpace2dTCS;
class RigidBody2dTCS;
class Collider2dTCS;
}//namespace Physics2dTCS
| 22.652778 | 73 | 0.83691 |
f153798264f9e5ceabb5a78ff90e481c3147998f | 5,048 | cxx | C++ | main/oox/source/drawingml/colorchoicecontext.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/oox/source/drawingml/colorchoicecontext.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/oox/source/drawingml/colorchoicecontext.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* 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 "oox/drawingml/colorchoicecontext.hxx"
#include "oox/helper/attributelist.hxx"
#include "oox/drawingml/color.hxx"
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::xml::sax::SAXException;
using ::com::sun::star::xml::sax::XFastAttributeList;
using ::com::sun::star::xml::sax::XFastContextHandler;
using ::oox::core::ContextHandler;
namespace oox {
namespace drawingml {
// ============================================================================
ColorValueContext::ColorValueContext( ContextHandler& rParent, Color& rColor ) :
ContextHandler( rParent ),
mrColor( rColor )
{
}
void ColorValueContext::startFastElement( sal_Int32 nElement, const Reference< XFastAttributeList >& rxAttribs )
throw (SAXException, RuntimeException)
{
AttributeList aAttribs( rxAttribs );
switch( nElement )
{
case A_TOKEN( scrgbClr ):
mrColor.setScrgbClr(
aAttribs.getInteger( XML_r, 0 ),
aAttribs.getInteger( XML_g, 0 ),
aAttribs.getInteger( XML_b, 0 ) );
break;
case A_TOKEN( srgbClr ):
mrColor.setSrgbClr( aAttribs.getIntegerHex( XML_val, 0 ) );
break;
case A_TOKEN( hslClr ):
mrColor.setHslClr(
aAttribs.getInteger( XML_hue, 0 ),
aAttribs.getInteger( XML_sat, 0 ),
aAttribs.getInteger( XML_lum, 0 ) );
break;
case A_TOKEN( sysClr ):
mrColor.setSysClr(
aAttribs.getToken( XML_val, XML_TOKEN_INVALID ),
aAttribs.getIntegerHex( XML_lastClr, -1 ) );
break;
case A_TOKEN( schemeClr ):
mrColor.setSchemeClr( aAttribs.getToken( XML_val, XML_TOKEN_INVALID ) );
break;
case A_TOKEN( prstClr ):
mrColor.setPrstClr( aAttribs.getToken( XML_val, XML_TOKEN_INVALID ) );
break;
}
}
Reference< XFastContextHandler > ColorValueContext::createFastChildContext(
sal_Int32 nElement, const Reference< XFastAttributeList >& rxAttribs ) throw (SAXException, RuntimeException)
{
AttributeList aAttribs( rxAttribs );
switch( nElement )
{
case A_TOKEN( alpha ):
case A_TOKEN( alphaMod ):
case A_TOKEN( alphaOff ):
case A_TOKEN( blue ):
case A_TOKEN( blueMod ):
case A_TOKEN( blueOff ):
case A_TOKEN( hue ):
case A_TOKEN( hueMod ):
case A_TOKEN( hueOff ):
case A_TOKEN( lum ):
case A_TOKEN( lumMod ):
case A_TOKEN( lumOff ):
case A_TOKEN( green ):
case A_TOKEN( greenMod ):
case A_TOKEN( greenOff ):
case A_TOKEN( red ):
case A_TOKEN( redMod ):
case A_TOKEN( redOff ):
case A_TOKEN( sat ):
case A_TOKEN( satMod ):
case A_TOKEN( satOff ):
case A_TOKEN( shade ):
case A_TOKEN( tint ):
mrColor.addTransformation( nElement, aAttribs.getInteger( XML_val, 0 ) );
break;
case A_TOKEN( comp ):
case A_TOKEN( gamma ):
case A_TOKEN( gray ):
case A_TOKEN( inv ):
case A_TOKEN( invGamma ):
mrColor.addTransformation( nElement );
break;
}
return 0;
}
// ============================================================================
ColorContext::ColorContext( ContextHandler& rParent, Color& rColor ) :
ContextHandler( rParent ),
mrColor( rColor )
{
}
Reference< XFastContextHandler > ColorContext::createFastChildContext(
sal_Int32 nElement, const Reference< XFastAttributeList >& ) throw (SAXException, RuntimeException)
{
switch( nElement )
{
case A_TOKEN( scrgbClr ):
case A_TOKEN( srgbClr ):
case A_TOKEN( hslClr ):
case A_TOKEN( sysClr ):
case A_TOKEN( schemeClr ):
case A_TOKEN( prstClr ):
return new ColorValueContext( *this, mrColor );
}
return 0;
}
// ============================================================================
} // namespace drawingml
} // namespace oox
| 32.152866 | 117 | 0.590729 |
f154891fe957b8a229fd4fc55bc08da83cf36c73 | 1,549 | cpp | C++ | Examples/SceneSwitch/src/main.cpp | dodoknight/CogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | 3 | 2016-06-01T10:14:00.000Z | 2016-10-11T15:53:45.000Z | Examples/SceneSwitch/src/main.cpp | dormantor/ofxCogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | null | null | null | Examples/SceneSwitch/src/main.cpp | dormantor/ofxCogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | 1 | 2020-08-15T17:01:00.000Z | 2020-08-15T17:01:00.000Z | #include "ofxCogMain.h"
#include "BehaviorEnt.h"
#include "NodeBuilder.h"
#include "ofxTextLabel.h"
#include "NetworkManager.h"
#include "Mesh.h"
#include "NetMessage.h"
#include "Interpolator.h"
#include "AttribAnimator.h"
#include "UpdateMessage.h"
#include "Stage.h"
#include "LuaScripting.h"
/*
*
* The code below is implemented in lua script
*
class SceneSwitcher : public Behavior {
public:
SceneSwitcher() {
}
void OnInit() {
SubscribeForMessages(ACT_BUTTON_CLICKED);
}
void OnMessage(Msg& msg) {
if (msg.HasAction(ACT_BUTTON_CLICKED)) {
auto stage = GETCOMPONENT(Stage);
string actualScene = stage->GetActualScene()->GetName();
string newScene = actualScene.compare("scene1") == 0 ? "scene2" : "scene1";
if (msg.GetContextNode()->GetTag().compare("previous_but") == 0) {
stage->SwitchToScene(stage->FindSceneByName(newScene), TweenDirection::RIGHT);
}
if (msg.GetContextNode()->GetTag().compare("next_but") == 0) {
stage->SwitchToScene(stage->FindSceneByName(newScene), TweenDirection::LEFT);
}
}
}
void Update(uint64 delta, uint64 absolute) {
}
};*/
class ExampleApp : public ofxCogApp {
void RegisterComponents() {
REGISTER_COMPONENT(new LuaScripting());
//REGISTER_BEHAVIOR(SceneSwitcher);
}
void InitEngine() {
ofxCogEngine::GetInstance().SetFps(100);
ofxCogEngine::GetInstance().Init();
ofxCogEngine::GetInstance().LoadStage();
}
void InitStage(Stage* stage) {
}
};
int main() {
ofSetupOpenGL(800, 450, OF_WINDOW);
ofRunApp(new ExampleApp());
return 0;
}
| 21.513889 | 82 | 0.701097 |
f1593e60eb478e7426da26ba59ec367786c7a7c7 | 18,733 | cpp | C++ | Source/AccelByteUe4Sdk/Private/Api/AccelByteEntitlementApi.cpp | leowind/accelbyte-unreal-sdk-plugin | 73a7bf289abbba8141767eb16005aaf8293f8a63 | [
"MIT"
] | null | null | null | Source/AccelByteUe4Sdk/Private/Api/AccelByteEntitlementApi.cpp | leowind/accelbyte-unreal-sdk-plugin | 73a7bf289abbba8141767eb16005aaf8293f8a63 | [
"MIT"
] | null | null | null | Source/AccelByteUe4Sdk/Private/Api/AccelByteEntitlementApi.cpp | leowind/accelbyte-unreal-sdk-plugin | 73a7bf289abbba8141767eb16005aaf8293f8a63 | [
"MIT"
] | null | null | null | // Copyright (c) 2018 - 2020 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.
#include "Api/AccelByteEntitlementApi.h"
#include "Core/AccelByteError.h"
#include "Core/AccelByteRegistry.h"
#include "Core/AccelByteReport.h"
#include "Core/AccelByteHttpRetryScheduler.h"
#include "JsonUtilities.h"
#include "EngineMinimal.h"
#include "Core/AccelByteSettings.h"
namespace AccelByte
{
namespace Api
{
Entitlement::Entitlement(const AccelByte::Credentials& Credentials, const AccelByte::Settings& Setting) : Credentials(Credentials), Settings(Setting){}
Entitlement::~Entitlement(){}
void Entitlement::QueryUserEntitlements(const FString& EntitlementName, const FString& ItemId, const int32& Offset, const int32& Limit, const THandler<FAccelByteModelsEntitlementPagingSlicedResult>& OnSuccess, const FErrorHandler& OnError, EAccelByteEntitlementClass EntitlementClass = EAccelByteEntitlementClass::NONE, EAccelByteAppType AppType = EAccelByteAppType::NONE )
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId());
FString Query = TEXT("");
if (!EntitlementName.IsEmpty())
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("entitlementName=%s"), *EntitlementName));
}
if (!ItemId.IsEmpty())
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("itemId=%s"), *ItemId));
}
if (Offset>=0)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("offset=%d"), Offset));
}
if (Limit>=0)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("limit=%d"), Limit));
}
if (EntitlementClass != EAccelByteEntitlementClass::NONE)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("entitlementClazz=%s"), *FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteEntitlementClass"), true)->GetNameStringByValue((int32)EntitlementClass)));
}
if (AppType != EAccelByteAppType::NONE)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("appType=%s"), *FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteAppType"), true)->GetNameStringByValue((int32)AppType)));
}
Url.Append(Query.IsEmpty() ? TEXT("") : FString::Printf(TEXT("?%s"),*Query));
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FString Content;
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::QueryUserEntitlements(const FString& EntitlementName, const TArray<FString>& ItemIds,
const int32& Offset, const int32& Limit, const THandler<FAccelByteModelsEntitlementPagingSlicedResult>& OnSuccess,
const FErrorHandler& OnError, EAccelByteEntitlementClass EntitlementClass, EAccelByteAppType AppType)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId());
FString Query = TEXT("");
if (!EntitlementName.IsEmpty())
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("entitlementName=%s"), *EntitlementName));
}
for (const FString& ItemId : ItemIds)
{
if (!ItemId.IsEmpty())
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("itemId=%s"), *ItemId));
}
}
if (Offset>=0)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("offset=%d"), Offset));
}
if (Limit>=0)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("limit=%d"), Limit));
}
if (EntitlementClass != EAccelByteEntitlementClass::NONE)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("entitlementClazz=%s"), *FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteEntitlementClass"), true)->GetNameStringByValue((int32)EntitlementClass)));
}
if (AppType != EAccelByteAppType::NONE)
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("appType=%s"), *FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteAppType"), true)->GetNameStringByValue((int32)AppType)));
}
Url.Append(Query.IsEmpty() ? TEXT("") : FString::Printf(TEXT("?%s"),*Query));
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FString Content;
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::GetUserEntitlementById(const FString& Entitlementid, const THandler<FAccelByteModelsEntitlementInfo>& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/%s"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *Entitlementid);
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::GetUserEntitlementOwnershipByAppId(const FString& AppId, const THandler<FAccelByteModelsEntitlementOwnership>& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/me/entitlements/ownership/byAppId?appId=%s"), *Settings.PlatformServerUrl, *Settings.PublisherNamespace, *AppId);
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::GetUserEntitlementOwnershipBySku(const FString& Sku, const THandler<FAccelByteModelsEntitlementOwnership>& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/me/entitlements/ownership/bySku?sku=%s"), *Settings.PlatformServerUrl, *Settings.PublisherNamespace, *Sku);
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::GetUserEntitlementOwnershipAny(const TArray<FString> ItemIds, const TArray<FString> AppIds, const TArray<FString> Skus,
const THandler<FAccelByteModelsEntitlementOwnership> OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
if (ItemIds.Num() < 1
&& AppIds.Num() < 1
&& Skus.Num() < 1)
{
OnError.ExecuteIfBound(EHttpResponseCodes::NotFound, TEXT("Please provide at least one itemId, AppId or Sku."));
}
else
{
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/me/entitlements/ownership/any"), *Settings.PlatformServerUrl, *Settings.PublisherNamespace);
int paramCount = 0;
for (int i = 0; i < ItemIds.Num(); i++)
{
Url.Append((paramCount == 0) ? TEXT("?") : TEXT("&")).Append(TEXT("itemIds=")).Append(ItemIds[i]);
paramCount++;
}
for (int i = 0; i < AppIds.Num(); i++)
{
Url.Append((paramCount == 0) ? TEXT("?") : TEXT("&")).Append(TEXT("appIds=")).Append(AppIds[i]);
paramCount++;
}
for (int i = 0; i < Skus.Num(); i++)
{
Url.Append((paramCount == 0) ? TEXT("?") : TEXT("&")).Append(TEXT("skus=")).Append(Skus[i]);
paramCount++;
}
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
}
void Entitlement::ConsumeUserEntitlement(const FString& EntitlementId, const int32& UseCount, const THandler<FAccelByteModelsEntitlementInfo>& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FAccelByteModelsConsumeUserEntitlementRequest ConsumeUserEntitlementRequest;
ConsumeUserEntitlementRequest.UseCount = UseCount;
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/%s/decrement"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *EntitlementId);
FString Verb = TEXT("PUT");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FString Content;
FJsonObjectConverter::UStructToJsonObjectString(ConsumeUserEntitlementRequest, Content);
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::CreateDistributionReceiver(const FString& ExtUserId, const FAccelByteModelsAttributes Attributes, const FVoidHandler& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/receivers/%s"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *ExtUserId);
FAccelByteModelsDistributionAttributes DistributionAttributes;
DistributionAttributes.Attributes = Attributes;
FString Verb = TEXT("POST");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FString Content;
FJsonObjectConverter::UStructToJsonObjectString(DistributionAttributes, Content);
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::DeleteDistributionReceiver(const FString& ExtUserId, const FString& UserId, const FVoidHandler& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/receivers/%s"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *UserId, *ExtUserId);
FString Verb = TEXT("DELETE");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::GetDistributionReceiver(const FString& PublisherNamespace, const FString& PublisherUserId, const THandler<TArray<FAccelByteModelsDistributionReceiver>>& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/receivers"), *Settings.PlatformServerUrl, *PublisherNamespace, *PublisherUserId);
FString Query = TEXT("");
if (!Credentials.GetNamespace().IsEmpty())
{
Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&"));
Query.Append(FString::Printf(TEXT("targetNamespace=%s"), *Credentials.GetNamespace()));
}
Url.Append(Query.IsEmpty() ? TEXT("") : FString::Printf(TEXT("?%s"),*Query));
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::UpdateDistributionReceiver(const FString& ExtUserId, const FAccelByteModelsAttributes Attributes, const FVoidHandler& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/receivers/%s"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *ExtUserId);
FAccelByteModelsDistributionAttributes DistributionAttributes;
DistributionAttributes.Attributes = Attributes;
FString Verb = TEXT("PUT");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FString Content;
FJsonObjectConverter::UStructToJsonObjectString(DistributionAttributes, Content);
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Entitlement::SyncPlatformPurchase(EAccelBytePlatformSync PlatformType, const FVoidHandler& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString PlatformText = TEXT("");
FString Content = TEXT("{}");
FString platformUserId = Credentials.GetPlatformUserId();
switch (PlatformType)
{
case EAccelBytePlatformSync::STEAM:
PlatformText = TEXT("steam");
if (platformUserId.IsEmpty()) {
OnError.ExecuteIfBound(static_cast<int32>(ErrorCodes::IsNotLoggedIn), TEXT("User not logged in with 3rd Party Platform"));
return;
}
Content = FString::Printf(TEXT("{\"steamId\": \"%s\", \"appId\": %s}"), *Credentials.GetPlatformUserId(), *Settings.AppId);
break;
case EAccelBytePlatformSync::XBOX_LIVE:
PlatformText = TEXT("xbl");
break;
case EAccelBytePlatformSync::PLAYSTATION:
PlatformText = TEXT("psn");
break;
default:
OnError.ExecuteIfBound(static_cast<int32>(ErrorCodes::InvalidRequest), TEXT("Platform Sync Type is not found"));
return;
}
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/iap/%s/sync"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *PlatformText);
FString Verb = TEXT("PUT");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
} // Namespace Api
}
| 43.363426 | 373 | 0.746917 |
f1598a41dbce24d7e5924bfd644a22825be54e6d | 5,663 | cpp | C++ | src/core/analyzer/StandardTokenizer.cpp | SRCH2/srch2-ngn | 925f36971aa6a8b31cdc59f7992790169e97ee00 | [
"BSD-3-Clause"
] | 14 | 2016-01-15T20:26:54.000Z | 2018-11-26T20:47:43.000Z | src/core/analyzer/StandardTokenizer.cpp | SRCH2/srch2-ngn | 925f36971aa6a8b31cdc59f7992790169e97ee00 | [
"BSD-3-Clause"
] | 2 | 2016-04-26T05:29:01.000Z | 2016-05-07T00:13:38.000Z | src/core/analyzer/StandardTokenizer.cpp | SRCH2/srch2-ngn | 925f36971aa6a8b31cdc59f7992790169e97ee00 | [
"BSD-3-Clause"
] | 7 | 2016-02-27T11:35:59.000Z | 2018-11-26T20:47:59.000Z | /*
* Copyright (c) 2016, SRCH2
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the SRCH2 nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL SRCH2 BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* StandardTokenizer.cpp
*
* Created on: 2013-5-17
*/
#include <iostream>
#include "StandardTokenizer.h"
#include "util/Assert.h"
namespace srch2 {
namespace instantsearch {
StandardTokenizer::StandardTokenizer()
:Tokenizer()
{}
bool StandardTokenizer::incrementToken() {
(tokenStreamContainer->currentToken).clear();
// CharOffset starts from 1.
tokenStreamContainer->currentTokenOffset = tokenStreamContainer->offset + 1;
CharType previousChar = (CharType) ' ';
//originally, set the previous character is ' ';
while (true) {
///check whether the scanning is over.
if ((tokenStreamContainer->offset)
>= (tokenStreamContainer->completeCharVector).size()) {
if (tokenStreamContainer->currentToken.empty()) {
return false;
} else {
tokenStreamContainer->currentTokenPosition++;
return true;
}
}
CharType currentChar =
(tokenStreamContainer->completeCharVector)[tokenStreamContainer->offset];
if ((tokenStreamContainer->offset) - 1 >= 0) //check whether the previous character exists.
{
previousChar =
(tokenStreamContainer->completeCharVector)[(tokenStreamContainer->offset)
- 1];
}
(tokenStreamContainer->offset)++;
///we need combine previous character and current character to decide a word
unsigned previousCharacterType = characterSet.getCharacterType(previousChar);
unsigned currentCharacterType = characterSet.getCharacterType(currentChar);
switch (currentCharacterType) {
case CharSet::WHITESPACE:
if (!(tokenStreamContainer->currentToken).empty()) {
tokenStreamContainer->currentTokenPosition++;
return true;
}
tokenStreamContainer->currentTokenOffset++;
break;
case CharSet::LATIN_TYPE:
case CharSet::BOPOMOFO_TYPE:
case CharSet::DELIMITER_TYPE:
//check if the types of previous character and current character are the same
if (previousCharacterType == currentCharacterType) {
(tokenStreamContainer->currentToken).push_back(currentChar);
} else if (previousCharacterType == CharSet::DELIMITER_TYPE ||
currentCharacterType == CharSet::DELIMITER_TYPE) {
/*
* delimiters will go with both LATIN and BOPPMOFO types.
* e.g for C++ C is Latin type and + is Delimiter type. We do not want to split
* them into to C and ++.
*
* We also do not want to tokenize "c+b" because NonalphaNumericFilter will tokenize
* it later.
*/
(tokenStreamContainer->currentToken).push_back(currentChar);
}else {
if (!(tokenStreamContainer->currentToken).empty()) //if the currentToken is not null, we need produce the token
{
(tokenStreamContainer->offset)--;
tokenStreamContainer->currentTokenPosition++;
return true;
} else
(tokenStreamContainer->currentToken).push_back(currentChar);
}
break;
default: //other character type
if (!(tokenStreamContainer->currentToken).empty()) {
(tokenStreamContainer->offset)--;
} else {
(tokenStreamContainer->currentToken).push_back(currentChar);
}
if (tokenStreamContainer->currentToken.empty()) {
return false;
} else {
tokenStreamContainer->currentTokenPosition++;
return true;
}
}
}
ASSERT(false);
return false;
}
bool StandardTokenizer::processToken() {
tokenStreamContainer->type = ANALYZED_ORIGINAL_TOKEN;
return this->incrementToken();
}
StandardTokenizer::~StandardTokenizer() {
// TODO Auto-generated destructor stub
}
}
}
| 41.036232 | 127 | 0.640473 |
f15dfc458f630348f1f54efe4cc1c3112c668762 | 3,125 | cpp | C++ | src/Lib/Messaging/Message.cpp | gravitationalwavedc/gwcloud_job_server | fb96ed1dc6baa240d1a38ac1adcd246577285294 | [
"MIT"
] | null | null | null | src/Lib/Messaging/Message.cpp | gravitationalwavedc/gwcloud_job_server | fb96ed1dc6baa240d1a38ac1adcd246577285294 | [
"MIT"
] | 8 | 2020-06-06T08:39:37.000Z | 2021-09-22T18:01:47.000Z | src/Lib/Messaging/Message.cpp | gravitationalwavedc/gwcloud_job_server | fb96ed1dc6baa240d1a38ac1adcd246577285294 | [
"MIT"
] | null | null | null | //
// Created by lewis on 2/26/20.
//
#include "Message.h"
#include <utility>
#include "../../Cluster/Cluster.h"
using namespace std;
#ifdef BUILD_TESTS
Message::Message(uint32_t msgId) {
// Constructor only used for testing
// Resize the data array to 64kb
data.reserve(1024 * 64);
// Reset the index
index = 0;
// Store the id
id = msgId;
}
#endif
Message::Message(uint32_t msgId, Message::Priority priority, const std::string& source) {
// Resize the data array to 64kb
data.reserve(1024 * 64);
// Reset the index
index = 0;
// Set the priority
this->priority = priority;
// Set the source
this->source = source;
// Push the source
push_string(source);
// Push the id
push_uint(msgId);
}
Message::Message(const vector<uint8_t>& vdata) {
data = vdata;
index = 0;
priority = Message::Priority::Lowest;
source = pop_string();
id = pop_uint();
}
void Message::push_bool(bool v) {
push_ubyte(v ? 1 : 0);
}
bool Message::pop_bool() {
auto result = pop_ubyte();
return result == 1;
}
void Message::push_ubyte(uint8_t v) {
data.push_back(v);
}
uint8_t Message::pop_ubyte() {
auto result = data[index++];
return result;
}
void Message::push_byte(int8_t v) {
push_ubyte((uint8_t) v);
}
int8_t Message::pop_byte() {
return (int8_t) pop_ubyte();
}
#define push_type(t, r) void Message::push_##t (r v) { \
uint8_t pdata[sizeof(v)]; \
\
*((typeof(v)*) &pdata) = v; \
\
for (unsigned char i : pdata) \
push_ubyte(i); \
}
#define pop_type(t, r) r Message::pop_##t() { \
uint8_t pdata[sizeof(r)]; \
\
for (auto i = 0; i < sizeof(r); i++) \
pdata[i] = pop_ubyte(); \
\
return *(r*) &pdata; \
}
#define add_type(t, r) push_type(t, r) pop_type(t, r)
add_type(ushort, uint16_t)
add_type(short, int16_t)
add_type(uint, uint32_t)
add_type(int, int32_t)
add_type(ulong, uint64_t)
add_type(long, int64_t)
add_type(float, float)
add_type(double, double)
void Message::push_string(const std::string& v) {
push_ulong(v.size());
data.insert(data.end(), v.begin(), v.end());
}
std::string Message::pop_string() {
auto result = pop_bytes();
// Write string terminator
result.push_back(0);
return std::string((char *) result.data());
}
void Message::push_bytes(const std::vector<uint8_t>& v) {
push_ulong(v.size());
data.insert(data.end(), v.begin(), v.end());
}
std::vector<uint8_t> Message::pop_bytes() {
auto len = pop_ulong();
auto result = std::vector<uint8_t>(&data[index], &data[index] + len);
index += len;
return result;
}
void Message::send(Cluster* pCluster) {
pCluster->queueMessage(source, &data, priority);
}
| 21.258503 | 89 | 0.54848 |
f15ecf14f7a6c51cc89702955d6718ec4b6947ea | 3,757 | cpp | C++ | 2009/regex_fsm/subset_construct.cpp | machsix/code-for-blog | 0f0daf8658854c7d5e9d1718165efc1f6c3d412a | [
"Unlicense"
] | 1,199 | 2015-01-06T14:09:37.000Z | 2022-03-29T19:39:51.000Z | 2009/regex_fsm/subset_construct.cpp | yingchuan-d/code-for-blog | f1049598746e228d44f7e8f7beabf7fd8e0a1143 | [
"Unlicense"
] | 25 | 2016-07-29T15:44:01.000Z | 2021-11-19T16:21:01.000Z | 2009/regex_fsm/subset_construct.cpp | yingchuan-d/code-for-blog | f1049598746e228d44f7e8f7beabf7fd8e0a1143 | [
"Unlicense"
] | 912 | 2015-01-04T00:39:50.000Z | 2022-03-29T06:50:22.000Z | // This code is in the public domain - feel free to do anything you
// wish with it.
//
// Eli Bendersky (eliben@gmail.com)
//
#include "subset_construct.h"
// Builds the epsilon closure of states for the given NFA
//
set<state> build_eps_closure(NFA nfa, set<state> states)
{
// push all states onto a stack
//
vector<state> unchecked_stack(states.begin(), states.end());
// initialize eps_closure(states) to states
//
set<state> eps_closure(states.begin(), states.end());
while (!unchecked_stack.empty())
{
// pop state t, the top element, off the stack
//
state t = unchecked_stack.back();
unchecked_stack.pop_back();
// for each state u with an edge from t to u labeled EPS
//
for ( vector<input>::const_iterator i = nfa.trans_table[t].begin();
i != nfa.trans_table[t].end(); ++i)
{
if (*i == EPS)
{
state u = i - nfa.trans_table[t].begin();
// if u is not already in eps_closure, add it and push it onto stack
//
if (eps_closure.find(u) == eps_closure.end())
{
eps_closure.insert(u);
unchecked_stack.push_back(u);
}
}
}
}
return eps_closure;
}
// Creates unique numbers for DFA states
//
static state gen_new_state()
{
static state num = 0;
return num++;
}
// Subset construction algorithm. Creates a DFA that recognizes the same
// language as the given NFA
//
//
DFA subset_construct(NFA nfa)
{
DFA dfa;
// state_rep: a set of NFA states which is represented by some DFA state
//
typedef set<state> state_rep;
set<state_rep> marked_states;
set<state_rep> unmarked_states;
// gives a number to each state in the DFA
//
map<state_rep, state> dfa_state_num;
set<state> nfa_initial;
nfa_initial.insert(nfa.initial);
// initially, eps-closure(nfa.initial) is the only state in the DFAs states
// and it's unmarked
//
state_rep first(build_eps_closure(nfa, nfa_initial));
unmarked_states.insert(first);
// the initial dfa state
//
state dfa_initial = gen_new_state();
dfa_state_num[first] = dfa_initial;
dfa.start = dfa_initial;
while (!unmarked_states.empty())
{
// Take out one unmarked state and mark it (remove from the unmarked set,
// insert into the marked set)
//
state_rep a_state = *(unmarked_states.begin());
unmarked_states.erase(unmarked_states.begin());
marked_states.insert(a_state);
// If this state contains the NFA's final state, add it to the DFA's set
// of final states
//
if (a_state.find(nfa.final) != a_state.end())
dfa.final.insert(dfa_state_num[a_state]);
// for each input symbol the nfa knows
//
for ( set<input>::const_iterator inp_i = nfa.inputs.begin();
inp_i != nfa.inputs.end(); ++inp_i)
{
// next state
//
state_rep next = build_eps_closure(nfa, nfa.move(a_state, *inp_i));
// if we haven't examined this state before, add it to the unmarked
// states, and make up a new number for it
//
if (unmarked_states.find(next) == unmarked_states.end() &&
marked_states.find(next) == marked_states.end())
{
unmarked_states.insert(next);
dfa_state_num[next] = gen_new_state();
}
dfa.trans_table[make_pair(dfa_state_num[a_state], *inp_i)] = dfa_state_num[next];
}
}
return dfa;
}
| 27.625 | 93 | 0.581581 |
f15f88b741604ccfffcee89d8b457a4d06de6c7f | 949 | cpp | C++ | src/logic/role/role_manager.cpp | lanhuanjun/game_server | 64fb7ca39db776fa9471f4c71a76c31759ace7a4 | [
"MIT"
] | null | null | null | src/logic/role/role_manager.cpp | lanhuanjun/game_server | 64fb7ca39db776fa9471f4c71a76c31759ace7a4 | [
"MIT"
] | 1 | 2020-01-15T12:46:05.000Z | 2020-01-15T12:46:05.000Z | src/logic/role/role_manager.cpp | lanhuanjun/game_server | 64fb7ca39db776fa9471f4c71a76c31759ace7a4 | [
"MIT"
] | null | null | null | #include "role_manager.h"
#include "role_rmi.h"
#include <third-party/coroutine/gs_co.h>
#include <core/tools/gs_random.h>
MNG_IMPL(role, IRoleManager, CRoleManager)
CRoleManager::CRoleManager()
: m_last_call(0)
{
}
CRoleManager::~CRoleManager()
{
}
void CRoleManager::Init()
{
}
void CRoleManager::Update()
{
if (svc_run_msec() - m_last_call > 1000) {
m_last_call = svc_run_msec();
START_TASK(&CRoleManager::TestCall, this);
}
}
void CRoleManager::TestCall()
{
Rmi<IRoleManager> svc_lobby(__ANY_LOBBY__);
int32_t a = gs::rand(1, 1000);
int32_t b = gs::rand(1, 1000);
int32_t res = svc_lobby.RmiTest_Add(a, b);
LOG(INFO) << a << " + " << b << " = " << res;
if (rmi_last_err() != RMI_CODE_OK) {
rmi_clear_err();
}
}
void CRoleManager::Destroy()
{
}
int CRoleManager::RmiTest_Add(int a, int b)
{
LOG(INFO) << "call: a:" << a << " b:" << b;
return a + b;
}
| 19.367347 | 50 | 0.610116 |
f161a296a2b14adc45ae38221a97574055384874 | 1,449 | hpp | C++ | ufora/BackendGateway/ComputedGraph/Typedefs.hpp | ufora/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 571 | 2015-11-05T20:07:07.000Z | 2022-01-24T22:31:09.000Z | ufora/BackendGateway/ComputedGraph/Typedefs.hpp | timgates42/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 218 | 2015-11-05T20:37:55.000Z | 2021-05-30T03:53:50.000Z | ufora/BackendGateway/ComputedGraph/Typedefs.hpp | timgates42/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 40 | 2015-11-07T21:42:19.000Z | 2021-05-23T03:48:19.000Z | /***************************************************************************
Copyright 2015 Ufora Inc.
Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
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.
****************************************************************************/
#pragma once
#include "../../FORA/Core/Type.hppml"
#include "../../core/PolymorphicSharedPtr.hpp"
#include <boost/python.hpp>
#include <map>
#include <string>
#define COMPUTED_GRAPH_TIMING 1
namespace ComputedGraph {
typedef boost::python::list py_list;
typedef unsigned long id_type;
typedef std::pair<id_type, id_type> class_id_type;
typedef enum {
attrKey,
attrMutable,
attrProperty,
attrFunction,
attrNotCached,
attrClassAttribute,
attrUnknown
} attr_type;
class Graph;
class Location;
class LocationProperty;
class Root;
class LocationType;
class PropertyStorage;
class InstanceStorage;
typedef PolymorphicSharedPtr<Root> RootPtr;
typedef PolymorphicSharedWeakPtr<Root> WeakRootPtr;
}
| 23.370968 | 77 | 0.6853 |
f1656e7e7093214be79d698b5e333ad40b8117f4 | 858 | cpp | C++ | Quasics2017Code/Nike/src/Commands/Lights/SetLightColor.cpp | quasics/quasics-frc-sw-2015 | e5a4f1b4e209ba941f12c2cc41759854f3c5420b | [
"BSD-3-Clause"
] | 5 | 2016-12-16T19:05:05.000Z | 2021-03-05T01:23:27.000Z | Quasics2017Code/Nike-2018/src/Commands/Lights/SetLightColor.cpp | quasics/quasics-frc-sw-2015 | e5a4f1b4e209ba941f12c2cc41759854f3c5420b | [
"BSD-3-Clause"
] | null | null | null | Quasics2017Code/Nike-2018/src/Commands/Lights/SetLightColor.cpp | quasics/quasics-frc-sw-2015 | e5a4f1b4e209ba941f12c2cc41759854f3c5420b | [
"BSD-3-Clause"
] | 2 | 2020-01-03T01:52:43.000Z | 2022-02-02T01:23:45.000Z | #include "SetLightColor.h"
SetLightColor::SetLightColor(ArduinoController::ColorMode colorMode) {
// Use Requires() here to declare subsystem dependencies
// eg. Requires(Robot::chassis.get());
Requires(Robot::arduinoController.get());
kColorMode = colorMode;
}
// Called just before this Command runs the first time
void SetLightColor::Initialize() {
Robot::arduinoController->SetLightColor(kColorMode);
}
// Called repeatedly when this Command is scheduled to run
void SetLightColor::Execute() {
}
// Make this return true when this Command no longer needs to run execute()
bool SetLightColor::IsFinished() {
return true;
}
// Called once after isFinished returns true
void SetLightColor::End() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void SetLightColor::Interrupted() {
}
| 24.514286 | 75 | 0.757576 |
f166428d95194f06fca58d2691a7c5a2a98b55c8 | 243 | cpp | C++ | main.cpp | Milerius/make_ui_great_again | c00ae4c5aab5d23ef7db1fe2052786ea57c580f4 | [
"MIT"
] | 1 | 2019-12-22T16:57:13.000Z | 2019-12-22T16:57:13.000Z | main.cpp | Milerius/make_ui_great_again | c00ae4c5aab5d23ef7db1fe2052786ea57c580f4 | [
"MIT"
] | null | null | null | main.cpp | Milerius/make_ui_great_again | c00ae4c5aab5d23ef7db1fe2052786ea57c580f4 | [
"MIT"
] | null | null | null | //
// Created by Roman Szterg on 18/12/2019.
//
#include "ui.wrapper.hpp"
int main()
{
antara_gui gui("example", 200, 200);
while (not gui.is_close()) {
gui.pre_update();
gui.show_demo();
gui.update();
}
} | 16.2 | 41 | 0.555556 |
f16775511f36e93433292026986065f31f690529 | 1,683 | hpp | C++ | lib/fizzy/leb128.hpp | imapp-pl/fizzy | 69e154ad7b910809f2219839d328b93168020135 | [
"Apache-2.0"
] | null | null | null | lib/fizzy/leb128.hpp | imapp-pl/fizzy | 69e154ad7b910809f2219839d328b93168020135 | [
"Apache-2.0"
] | null | null | null | lib/fizzy/leb128.hpp | imapp-pl/fizzy | 69e154ad7b910809f2219839d328b93168020135 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "types.hpp"
#include <cstdint>
#include <stdexcept>
namespace fizzy
{
template <typename T>
std::pair<T, const uint8_t*> leb128u_decode(const uint8_t* input)
{
static_assert(!std::numeric_limits<T>::is_signed);
T result = 0;
int result_shift = 0;
for (; result_shift < std::numeric_limits<T>::digits; ++input, result_shift += 7)
{
// TODO this ignores the bits in the last byte other than the least significant one
// So would not reject some invalid encoding with those bits set.
result |= static_cast<T>((static_cast<T>(*input) & 0x7F) << result_shift);
if ((*input & 0x80) == 0)
return {result, input + 1};
}
throw std::runtime_error("Invalid LEB128 encoding: too many bytes.");
}
template <typename T>
std::pair<T, const uint8_t*> leb128s_decode(const uint8_t* input)
{
static_assert(std::numeric_limits<T>::is_signed);
using T_unsigned = typename std::make_unsigned<T>::type;
T_unsigned result = 0;
int result_shift = 0;
for (; result_shift < std::numeric_limits<T_unsigned>::digits; ++input, result_shift += 7)
{
result |= static_cast<T_unsigned>((static_cast<T_unsigned>(*input) & 0x7F) << result_shift);
if ((*input & 0x80) == 0)
{
// sign extend
if ((*input & 0x40) != 0)
{
auto const mask = static_cast<T_unsigned>(~T_unsigned{0} << (result_shift + 7));
result |= mask;
}
return {static_cast<T>(result), input + 1};
}
}
throw std::runtime_error("Invalid LEB128 encoding: too many bytes.");
}
} // namespace fizzy | 30.053571 | 100 | 0.612002 |
f167c1efcef212b5f08300085e2c43bcc7d477af | 329 | hpp | C++ | cpp/include/cg3/common/test_scenes.hpp | tychota/cg3-path-tracer | 548519121cacb01a4be835c0bece21238b56f92b | [
"Beerware"
] | null | null | null | cpp/include/cg3/common/test_scenes.hpp | tychota/cg3-path-tracer | 548519121cacb01a4be835c0bece21238b56f92b | [
"Beerware"
] | null | null | null | cpp/include/cg3/common/test_scenes.hpp | tychota/cg3-path-tracer | 548519121cacb01a4be835c0bece21238b56f92b | [
"Beerware"
] | null | null | null | # pragma once
# include "cg3/common/scene.hpp"
# include <memory>
std::shared_ptr< Scene > create_rt_test_scene( tiny_vec< size_t, 2 > resolution );
std::shared_ptr< Scene > create_pt_test_scene( tiny_vec< size_t, 2 > resolution );
std::shared_ptr< Scene > create_cornell_box_test_scene( tiny_vec< size_t, 2 > resolution );
| 27.416667 | 91 | 0.744681 |
f167c309a65dcaef7f40a57b865f68687cdcdfc5 | 8,673 | cpp | C++ | test/posix/integration/stat/stat_tests.cpp | jaeh/IncludeOS | 1cc2bcf36758ff5ef3099e0c0c1ee55f0bb1de02 | [
"Apache-2.0"
] | 3,673 | 2015-12-01T22:14:02.000Z | 2019-03-22T03:07:20.000Z | test/posix/integration/stat/stat_tests.cpp | jaeh/IncludeOS | 1cc2bcf36758ff5ef3099e0c0c1ee55f0bb1de02 | [
"Apache-2.0"
] | 960 | 2015-12-01T20:40:36.000Z | 2019-03-22T13:21:21.000Z | test/posix/integration/stat/stat_tests.cpp | AndreasAakesson/IncludeOS | 891b960a0a7473c08cd0d93a2bba7569c6d88b48 | [
"Apache-2.0"
] | 357 | 2015-12-02T09:32:50.000Z | 2019-03-22T09:32:34.000Z | #include <service>
#include <info>
#include <cassert>
#define __SPU__
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
void print_stat(struct stat buffer);
void stat_tests()
{
int res;
char* nullbuf = nullptr;
char shortbuf[4];
char buf[1024];
struct stat buffer;
res = stat("folder1", nullptr);
printf("stat("") with nullptr result: %d\n", res);
if (res == -1)
{
printf("stat error: %s\n", strerror(errno));
}
else {
print_stat(buffer);
}
CHECKSERT(res == -1 && errno == EFAULT, "stat() with nullptr buffer fails with EFAULT");
res = stat("/mnt/disk/folder1", &buffer);
printf("stat(\"folder1\") result: %d\n", res);
if (res == -1)
{
printf("stat error: %s\n", strerror(errno));
}
else {
print_stat(buffer);
}
CHECKSERT(res == 0, "stat() of folder that exists is ok");
res = stat("/mnt/disk/file1", &buffer);
printf("stat(\"file1\") result: %d\n", res);
if (res == -1)
{
printf("stat error: %s\n", strerror(errno));
}
else {
print_stat(buffer);
}
CHECKSERT(res == 0, "stat() of file that exists is ok");
res = stat("folder666", &buffer);
printf("stat(\"folder1\") result: %d\n", res);
if (res == -1)
{
printf("stat error: %s\n", strerror(errno));
}
else {
print_stat(buffer);
}
CHECKSERT(res == -1, "stat() of folder that does not exist fails");
res = stat("file666", &buffer);
printf("stat(\"file666\") result: %d\n", res);
if (res == -1)
{
printf("stat error: %s\n", strerror(errno));
}
else {
print_stat(buffer);
}
CHECKSERT(res == -1, "stat() of file that does not exist fails");
res = chdir(nullptr);
printf("chdir result (to nullptr): %d\n", res);
if (res == -1)
{
printf("chdir error: %s\n", strerror(errno));
}
CHECKSERT(res == -1, "chdir(nullptr) should fail");
res = chdir("");
printf("chdir result (to empty string): %d\n", res);
if (res == -1)
{
printf("chdir error: %s\n", strerror(errno));
}
CHECKSERT(res == -1, "chdir(\"\") should fail");
res = chdir("file2");
printf("chdir result (not a folder): %d\n", res);
if (res == -1)
{
printf("chdir error: %s\n", strerror(errno));
}
CHECKSERT(res == -1, "chdir() to a file should fail");
res = chdir("/mnt/disk/folder1");
printf("chdir result (existing folder): %d\n", res);
if (res == -1)
{
printf("chdir error: %s\n", strerror(errno));
}
CHECKSERT(res == 0, "chdir (absolute) to folder that exists is ok");
printf("changing dir\n");
res = chdir("/mnt/disk/folder1");
printf("chdir res: %d\n", res);
res = fstatat(AT_FDCWD, "file1", &buffer, 0);
printf("fstatat(\"file1\") result: %d\n", res);
if (res == -1)
{
printf("fstatat error: %s\n", strerror(errno));
}
else {
print_stat(buffer);
}
CHECKSERT(res == 0, "fstatat() of file that exists is ok");
res = chdir("/folder1");
printf("chdir result (existing folder, absolute): %d\n", res);
if (res == -1)
{
printf("chdir error: %s\n", strerror(errno));
}
res = chdir(".");
printf("chdir result (to \".\"): %d\n", res);
if (res == -1)
{
printf("chdir error: %s\n", strerror(errno));
}
CHECKSERT(res == 0, "chdir(\".\") is ok");
res = chdir("foldera");
printf("chdir result (to subfolder of cwd): %d\n", res);
if (res == -1)
{
printf("chdir error: %s\n", strerror(errno));
}
CHECKSERT(res == 0, "chdir to subfolder of cwd is ok");
/**
If buf is a null pointer, the behavior of getcwd() is unspecified.
http://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html
Changed behavior of getcwd to Expect buf isn't nullptr.
TODO: It's nice to have these test cases in there, but it will require
the test to throw on contract violation
**/
/**
char* nullcwd = getcwd(nullbuf, 0);
printf("getcwd result (nullptr, size 0): %s\n", nullcwd == nullptr ? "NULL" : nullcwd);
if (nullcwd == nullptr)
{
printf("getcwd error: %s\n", strerror(errno));
}
CHECKSERT(nullcwd == nullptr && errno == EINVAL, "getcwd() with 0-size buffer should fail with EINVAL");
nullcwd = getcwd(nullptr, 1024);
printf("getcwd result (nullptr): %s\n", nullcwd == nullptr ? "NULL" : nullcwd);
if (nullcwd == nullptr)
{
printf("getcwd error: %s\n", strerror(errno));
}
CHECKSERT(nullcwd == nullptr, "getcwd() with nullptr buffer should fail");
**/
char* shortcwd = getcwd(shortbuf, 4);
printf("getcwd result (small buffer): %s\n", shortcwd == nullptr ? "NULL" : shortcwd);
if (shortcwd == nullptr)
{
printf("getcwd error: %s\n", strerror(errno));
}
CHECKSERT(shortcwd == nullptr && errno == ERANGE, "getcwd() with too small buffer should fail with ERANGE");
char* cwd = getcwd(buf, 1024);
printf("getcwd result (adequate buffer): %s\n", cwd);
if (cwd == nullptr)
{
printf("getcwd error: %s\n", strerror(errno));
}
CHECKSERT(cwd, "getcwd() with adequate buffer is ok");
res = chmod("/dev/null", S_IRUSR);
printf("chmod result: %d\n", res);
if (res == -1)
{
printf("chmod error: %s\n", strerror(errno));
}
CHECKSERT(res == -1, "chmod() should fail on read-only memdisk");
int fd = STDOUT_FILENO;
close(fd);
res = fchmod(fd, S_IWUSR);
printf("fchmod result: %d\n", res);
if (res == -1)
{
printf("fchmod error: %s\n", strerror(errno));
}
CHECKSERT(res == -1, "fchmod() on non-open FD should fail");
res = fchmodat(fd, "test", S_IRUSR, AT_SYMLINK_NOFOLLOW);
printf("fchmodat result: %d\n", res);
if (res == -1)
{
printf("fchmodat error: %s\n", strerror(errno));
}
CHECKSERT(res == -1, "fchmodat() on non-open FD should fail");
res = fstat(fd, &buffer);
printf("fstat result: %d\n", res);
if (res == -1)
{
printf("fstat error: %s\n", strerror(errno));
}
res = fstatat(fd, "test", &buffer, AT_SYMLINK_NOFOLLOW);
printf("fstatat result: %d\n", res);
if (res == -1)
{
printf("fstatat error: %s\n", strerror(errno));
}
CHECKSERT(res == -1, "fstatat() on non-open FD should fail");
res = futimens(fd, nullptr);
printf("futimens result: %d\n", res);
if (res == -1)
{
printf("futimens error: %s\n", strerror(errno));
}
CHECKSERT(res == -1, "futimens() on non-open FD should fail");
res = utimensat(fd, "test", nullptr, AT_SYMLINK_NOFOLLOW);
printf("utimensat result: %d\n", res);
if (res == -1)
{
printf("utimensat error: %s\n", strerror(errno));
}
CHECKSERT(res == -1, "utimensat() on non-open FD should fail");
/*
res = lstat("/", &buffer);
printf("lstat result: %d\n", res);
if (res == -1)
{
printf("lstat error: %s\n", strerror(errno));
}
*/
res = mkdir("/dev/sda1/root", S_IWUSR);
printf("mkdir result: %d\n", res);
if (res == -1)
{
printf("mkdir error: %s\n", strerror(errno));
}
CHECKSERT(res == -1, "mkdir() on read-only memdisk should fail");
res = mkdirat(fd, "root", S_IWUSR);
printf("mkdirat result: %d\n", res);
if (res == -1)
{
printf("mkdirat error: %s\n", strerror(errno));
}
CHECKSERT(res == -1, "mkdirat() on non-open FD should fail");
res = mkfifo("/FILE_FIFO", S_IWUSR);
printf("mkfifo result: %d\n", res);
if (res == -1)
{
printf("mkfifo error: %s\n", strerror(errno));
}
CHECKSERT(res == -1, "mkfifo() on read-only memdisk should fail");
res = mkfifoat(AT_FDCWD, "test", S_IWUSR);
printf("mkfifoat result: %d\n", res);
if (res == -1)
{
printf("mkfifoat error: %s\n", strerror(errno));
}
CHECKSERT(res == -1, "mkfifoat() on non-open FD should fail");
/*
res = mknod("/dev/null", S_IWUSR, 0);
printf("mknod result: %d\n", res);
if (res == -1) {
printf("mknod error: %s\n", strerror(errno));
}
*/
res = mknodat(AT_FDCWD, "test", S_IWUSR, 0);
printf("mknodat result: %d\n", res);
if (res == -1) {
printf("mknodat error: %s\n", strerror(errno));
}
CHECKSERT(res == -1, "mknodat() on non-open FD should fail");
mode_t old_umask = umask(0);
printf("Old umask: %d\n", old_umask);
}
void print_stat(struct stat buffer)
{
printf("st_dev: %d\n", buffer.st_dev);
printf("st_ino: %hu\n", buffer.st_ino);
printf("st_mode: %d\n", buffer.st_mode);
printf("st_nlink: %d\n", buffer.st_nlink);
printf("st_uid: %d\n", buffer.st_uid);
printf("st_gid: %d\n", buffer.st_gid);
printf("st_rdev: %d\n", buffer.st_rdev);
printf("st_size: %ld\n", buffer.st_size);
printf("st_atime: %ld\n", buffer.st_atime);
printf("st_ctime: %ld\n", buffer.st_ctime);
printf("st_mtime: %ld\n", buffer.st_mtime);
printf("st_blksize: %ld\n", buffer.st_blksize);
printf("st_blocks: %ld\n", buffer.st_blocks);
}
| 26.851393 | 110 | 0.597717 |
f167c38e4e81c73098fe1565099d4de20e0a5d9d | 1,828 | cpp | C++ | src/mupnp/device/ST.cpp | cybergarage/CyberLink4CC | ccbda234b920ec88a36392102c1d5247c074a734 | [
"BSD-3-Clause"
] | null | null | null | src/mupnp/device/ST.cpp | cybergarage/CyberLink4CC | ccbda234b920ec88a36392102c1d5247c074a734 | [
"BSD-3-Clause"
] | null | null | null | src/mupnp/device/ST.cpp | cybergarage/CyberLink4CC | ccbda234b920ec88a36392102c1d5247c074a734 | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************
*
* mUPnP for C++
*
* Copyright (C) Satoshi Konno 2002
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/
#include <mupnp/device/ST.h>
#include <uhttp/util/StringUtil.h>
using namespace std;
using namespace uHTTP;
bool mUPnP::ST::IsAllDevice(const std::string &value) {
String valStr = value;
if (valStr.equals(ALL_DEVICE) == true)
return true;
string quoteStr;
quoteStr.append("\"");
quoteStr.append(ALL_DEVICE);
quoteStr.append("\"");
return valStr.equals(quoteStr.c_str());
}
bool mUPnP::ST::IsRootDevice(const std::string &value) {
String valStr = value;
if (valStr.equals(ROOT_DEVICE) == true)
return true;
string quoteStr;
quoteStr.append("\"");
quoteStr.append(ROOT_DEVICE);
quoteStr.append("\"");
return valStr.equals(quoteStr.c_str());
}
bool mUPnP::ST::IsUUIDDevice(const std::string &value) {
String valStr = value;
if (valStr.startsWith(UUID_DEVICE) == true)
return true;
string quoteStr;
quoteStr.append("\"");
quoteStr.append(UUID_DEVICE);
quoteStr.append("\"");
return valStr.startsWith(quoteStr.c_str());
}
bool mUPnP::ST::IsURNDevice(const std::string &value) {
String valStr = value;
if (valStr.startsWith(URN_DEVICE) == true)
return true;
string quoteStr;
quoteStr.append("\"");
quoteStr.append(URN_DEVICE);
quoteStr.append("\"");
return valStr.startsWith(quoteStr.c_str());
}
bool mUPnP::ST::IsURNService(const std::string &value) {
String valStr = value;
if (valStr.startsWith(URN_SERVICE) == true)
return true;
string quoteStr;
quoteStr.append("\"");
quoteStr.append(URN_SERVICE);
quoteStr.append("\"");
return valStr.startsWith(quoteStr.c_str());
}
| 25.746479 | 68 | 0.637309 |
f16c2bc9b7aa5f81849334c7d7ca60f6aff3567a | 13,729 | cpp | C++ | testMultiplePutGet/src/pvaPutGetSleep.cpp | mrkraimer/testClientCPP | 2d1608678e173bd36bbf34fe64b4182b00ba4074 | [
"MIT"
] | null | null | null | testMultiplePutGet/src/pvaPutGetSleep.cpp | mrkraimer/testClientCPP | 2d1608678e173bd36bbf34fe64b4182b00ba4074 | [
"MIT"
] | null | null | null | testMultiplePutGet/src/pvaPutGetSleep.cpp | mrkraimer/testClientCPP | 2d1608678e173bd36bbf34fe64b4182b00ba4074 | [
"MIT"
] | null | null | null | /*
* Copyright information and license terms for this software can be
* found in the file LICENSE that is included with the distribution
*/
/**
* @author Marty Kraimer
* @date 2021.02
*/
#include <iostream>
#include <time.h>
#include <unistd.h>
#include <epicsGetopt.h>
#include <epicsThread.h>
#include <pv/pvAccess.h>
#include <pv/clientFactory.h>
#include <pv/caProvider.h>
#include <pv/convert.h>
#include <pv/createRequest.h>
using std::tr1::static_pointer_cast;
using namespace std;
using namespace epics::pvData;
using namespace epics::pvAccess;
using namespace epics::pvAccess::ca;
class ExampleRequester;
typedef std::tr1::shared_ptr<ExampleRequester> ExampleRequesterPtr;
class ExampleRequester :
public ChannelRequester,
public ChannelPutRequester,
public ChannelGetRequester,
public std::tr1::enable_shared_from_this<ExampleRequester>
{
private:
const string channelName;
public:
bool channelConnected = false;
bool channelPutConnected = false;
bool channelPutDone = false;
bool channelGetConnected = false;
bool channelGetDone = false;
Channel::shared_pointer theChannel;
ChannelPut::shared_pointer theChannelPut;
Structure::const_shared_pointer theChannelPutStructure;
ChannelGet::shared_pointer theChannelGet;
PVStructure::shared_pointer theChannelGetPVStructure;
ExampleRequester(const string & channelName)
: channelName(channelName)
{}
virtual std::string getRequesterName(){
throw std::runtime_error("getRequesterName not implemented");
}
virtual void channelCreated(const Status& status, Channel::shared_pointer const & channel)
{
if(status.isOK()) {return;}
string message = string("channel ") + channelName + " channelCreated status=" + status.getMessage();
throw std::runtime_error(message);
}
virtual void channelStateChange(Channel::shared_pointer const & channel,
Channel::ConnectionState connectionState)
{
if(connectionState==Channel::CONNECTED) {
channelConnected = true;
theChannel = channel;
} else {
string message = string("channel ") + channelName + " connection state "
+ Channel::ConnectionStateNames[connectionState];
throw std::runtime_error(message);
}
}
virtual void channelPutConnect(
const Status& status,
ChannelPut::shared_pointer const & channelPut,
Structure::const_shared_pointer const & structure)
{
if(status.isOK()) {
channelPutConnected = true;
theChannelPut = channelPut;
theChannelPutStructure = structure;
return;
}
string message = string("channel ") + channelName + " channelPutConnect status=" + status.getMessage();
throw std::runtime_error(message);
}
virtual void putDone(
const Status& status,
ChannelPut::shared_pointer const & channelPut)
{
channelPutDone = true;
if(status.isOK()) {return;}
cout << "channel=" << channelName << " channelPutDone status=" << status.getMessage() << "\n";
}
virtual void getDone(
const Status& status,
ChannelPut::shared_pointer const & channelPut,
PVStructure::shared_pointer const & pvStructure,
BitSet::shared_pointer const & bitSet)
{
string message = string("channel ") + channelName + " channelPut:get not implemented";
throw std::runtime_error(message);
}
virtual void channelGetConnect(
const Status& status,
ChannelGet::shared_pointer const & channelGet,
Structure::const_shared_pointer const & structure)
{
if(status.isOK()) {
channelGetConnected = true;
theChannelGet = channelGet;
return;
}
string message = string("channel ") + channelName + " channelGetConnect status=" + status.getMessage();
throw std::runtime_error(message);
}
virtual void getDone(
const Status& status,
ChannelGet::shared_pointer const & channelGet,
PVStructure::shared_pointer const & pvStructure,
BitSet::shared_pointer const & bitSet)
{
channelGetDone = true;
theChannelGetPVStructure = pvStructure;
if(status.isOK()) {return;}
cout << "channel=" << channelName << " channelGetDone status=" << status.getMessage() << "\n";
}
};
static PVDataCreatePtr pvDataCreate = getPVDataCreate();
static ConvertPtr convert = getConvert();
static void example(
string providerName,
shared_vector<const string> const &channelNames)
{
ChannelProviderRegistry::shared_pointer channelRegistry(ChannelProviderRegistry::clients());
if(providerName=="pva") {
ClientFactory::start();
} else if(providerName=="ca") {
CAClientFactory::start();
} else {
cerr << "provider " << providerName << " not known" << endl;
throw std::runtime_error("unknown provider");
}
int num = channelNames.size();
shared_vector<ExampleRequesterPtr> exampleRequester(num);
for(int i=0; i<num; i++) {
exampleRequester[i] = ExampleRequesterPtr(new ExampleRequester(channelNames[i]));
}
ChannelProvider::shared_pointer channelProvider;
shared_vector<Channel::shared_pointer> channels(num);
shared_vector<ChannelPut::shared_pointer> channelPuts(num);
shared_vector<ChannelGet::shared_pointer> channelGets(num);
channelProvider = channelRegistry->getProvider(providerName);
for(int i=0; i<num; i++) {
channels[i] = channelProvider->createChannel(
channelNames[i],exampleRequester[i],ChannelProvider::PRIORITY_DEFAULT);
}
clock_t startTime;
clock_t endTime;
startTime = clock();
while(true) {
epicsThreadSleep(.1);
endTime = clock();
double seconds = (double)(endTime - startTime)/CLOCKS_PER_SEC;
if(seconds>5.0) {
for(int i=0; i<num; i++) {
if(!exampleRequester[i]->channelConnected) {
cout << "channel=" << channelNames[i] << " connect failed " <<"\n";
}
}
throw std::runtime_error("connect exception");
}
int numConnected = 0;
for(int i=0; i<num; i++) {
if(exampleRequester[i]->channelConnected) numConnected++;
}
if(numConnected==num) break;
}
CreateRequest::shared_pointer createRequest(CreateRequest::create());
PVStructurePtr pvRequest = createRequest->createRequest("value");
for(int i=0; i<num; i++) {
channelPuts[i] = channels[i]->createChannelPut(exampleRequester[i],pvRequest);
channelGets[i] = channels[i]->createChannelGet(exampleRequester[i],pvRequest);
}
startTime = clock();
while(true) {
epicsThreadSleep(.1);
endTime = clock();
double seconds = (double)(endTime - startTime)/CLOCKS_PER_SEC;
if(seconds>5.0) {
for(int i=0; i<num; i++) {
if(!exampleRequester[i]->channelGetConnected) {
cout << "channel=" << channelNames[i] << " channelGetConnected failed " <<"\n";
}
}
throw std::runtime_error("connect exception");
}
int numConnected = 0;
for(int i=0; i<num; i++) {
if(exampleRequester[i]->channelGetConnected) numConnected++;
}
if(numConnected==num) break;
}
startTime = clock();
while(true) {
epicsThreadSleep(.1);
endTime = clock();
double seconds = (double)(endTime - startTime)/CLOCKS_PER_SEC;
if(seconds>5.0) {
for(int i=0; i<num; i++) {
if(!exampleRequester[i]->channelPutConnected) {
cout << "channel=" << channelNames[i] << " channelPutConnected failed " <<"\n";
}
}
throw std::runtime_error("connect exception");
}
int numConnected = 0;
for(int i=0; i<num; i++) {
if(exampleRequester[i]->channelPutConnected) numConnected++;
}
if(numConnected==num) break;
}
int successCount = 0;
int failedCount = 0;
startTime = clock();
int numiter = 10000;
int value = 0;
for(int i = 0; i< numiter; i+= 1) {
bool correctData = true;
value++;
if(value>127) value = 0;
string strValue = to_string(value);
for(int j=0; j<num; j++) {
PVStructurePtr pvStructure = pvDataCreate->createPVStructure(
exampleRequester[j]->theChannelPutStructure);
BitSetPtr bitSet(BitSetPtr(new BitSet(pvStructure->getNumberFields())));
PVScalarPtr pvScalar(pvStructure->getSubField<PVScalar>("value"));
bitSet->set(pvScalar->getFieldOffset());
convert->fromString(pvScalar,strValue);
try {
exampleRequester[j]->theChannelPut->put(pvStructure,bitSet);
} catch (std::exception& e) {
cout << "i=" << i << " channelName=" << channelNames[j]
<< " put exception " << e.what() << endl;
correctData = false;
}
}
int numTry = 0;
while(true) {
if(numTry>100) {
throw std::runtime_error("put timed out");
}
int numDone = 0;
for(int j=0; j<num; j++) {
if(exampleRequester[j]->channelPutDone) numDone++;
}
if(numDone==num) break;
epicsThreadSleep(.001);
}
for(int j=0; j<num; j++) {
try {
exampleRequester[j]->theChannelGet->get();
} catch (std::exception& e) {
cout << "i=" << i << " channelName=" << channelNames[j]
<< " get exception " << e.what() << endl;
}
}
numTry = 0;
while(true) {
if(numTry>100) {
throw std::runtime_error("get timed out");
}
int numDone = 0;
for(int j=0; j<num; j++) {
if(exampleRequester[j]->channelGetDone) numDone++;
}
if(numDone==num) break;
epicsThreadSleep(.001);
}
for(int j=0; j<num; j++) {
PVStructurePtr pvStructure = exampleRequester[j]->theChannelGetPVStructure;
PVScalarPtr pvScalar = pvStructure->getSubField<PVScalar>("value");
string getValue = convert->toString(pvScalar);
if(strValue!=getValue){
cout << "i=" << i << " channelName=" << channelNames[j]
<< " expected=" << strValue << " got=" << getValue << "\n";
correctData = false;
}
}
for(int j=0; j<num; j++) {
exampleRequester[j]->channelPutDone = false;
exampleRequester[j]->channelGetDone = false;
}
if(correctData) {
successCount++;
} else {
failedCount++;
}
}
double seconds = (double)(clock() - startTime)/CLOCKS_PER_SEC;
cout << "time=" << seconds << " per interation=" << seconds/numiter << "\n";
cout << "SUCCESS COUNT: " << successCount << endl;
cout << "FAILED COUNT: " << failedCount << endl;
channelGets.clear();
channelPuts.clear();
channels.clear();
exampleRequester.clear();
if(providerName=="pva") {
ClientFactory::stop();
} else {
CAClientFactory::stop();
}
channelRegistry.reset();
}
int main(int argc,char *argv[])
{
string provider("pva");
shared_vector<string> channelNames;
channelNames.push_back("PVRbyte");
channelNames.push_back("PVRshort");
channelNames.push_back("PVRint");
channelNames.push_back("PVRlong");
channelNames.push_back("PVRubyte");
channelNames.push_back("PVRushort");
channelNames.push_back("PVRuint");
channelNames.push_back("PVRulong");
channelNames.push_back("PVRfloat");
channelNames.push_back("PVRdouble");
int opt;
while((opt = getopt(argc, argv, "hp:")) != -1) {
switch(opt) {
case 'p':
provider = optarg;
break;
case 'h':
cout << " -h -p provider channelNames " << endl;
cout << "default" << endl;
cout << "-p " << provider
<< " " << channelNames
<< endl;
return 0;
default:
std::cerr<<"Unknown argument: "<<opt<<"\n";
return -1;
}
}
bool pvaSrv(((provider.find("pva")==string::npos) ? false : true));
bool caSrv(((provider.find("ca")==string::npos) ? false : true));
if(pvaSrv&&caSrv) {
cerr<< "multiple providers are not allowed\n";
return 1;
}
cout << "_____pvaClientPutGet starting_______\n";
try {
int nPvs = argc - optind; /* Remaining arg list are PV names */
if (nPvs!=0)
{
channelNames.clear();
while(optind < argc) {
channelNames.push_back(argv[optind]);
optind++;
}
}
cout << " channelNames " << channelNames << endl;
shared_vector<const string> names(freeze(channelNames));
example(provider,names);
cout << "_____pvaClientPutGet done_______\n";
} catch (std::exception& e) {
cout << "exception " << e.what() << endl;
return 1;
}
return 0;
}
| 35.845953 | 111 | 0.5771 |
f16cff1e25753675382ed1c15ea4d3165627f0a0 | 1,794 | cpp | C++ | graph-source-code/141-E/3793087.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/141-E/3793087.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/141-E/3793087.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cstdio>
using namespace std;
const int nmax = 1010;
int n,m;
int se[nmax][nmax],me[nmax][nmax],u,v;
int color_s[nmax],color[nmax];
int nc=1;
vector < int > res;
void dfs(int u,int c){
color_s[u] = c;
for(int j = 1;j<=n;j++)
if(color_s[j]==0 && me[u][j]>0)
dfs(j,c);
}
void uni(int u,int v){
int c = color[u];
for(int i=1;i<=n;i++)
if(color[i]==c)
color[i] = color[v];
}
int main() {
int u,v; char c;
scanf("%d%d", &n, &m);
for(int i=1;i<=m;i++){
scanf("%d %d %c",&u,&v,&c);
if(c == 'S') se[u][v] = i; else me[u][v] = i;
if(c == 'S') se[v][u] = i; else me[v][u] = i;
}
for(int i=1;i<=n;i++)
if(color_s[i]==0)
dfs(i,nc++);
if(n%2==0){ cout << -1 << endl; return 0; }
if(n == 1 ){ cout << 0 << endl; return 0; }
u = (n-1)/2;
for(int i=1;i<=n;i++) color[i] = i;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(se[i][j]>0 && color_s[i]!=color_s[j] && color[i]!=color[j] && u!=0)
{
uni(i,j); res.push_back(se[i][j]); u--;}
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(se[i][j]>0 && color_s[i]==color_s[j] && color[i]!=color[j] && u!=0)
{
uni(i,j); res.push_back(se[i][j]); u--;}
if(u!=0){
cout << -1 << endl; return 0;
}
u = (n-1) / 2;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(me[i][j]>0 && color[i]!=color[j] && u!=0)
{
uni(i,j); res.push_back(me[i][j]); u--;}
if(res.size()!=n-1){
cout << -1 << endl; return 0;
}
cout << n-1 << endl;
for(int i=0;i<n-1;i++)
cout << res[i] << ' ';
cout << endl;
return 0;
} | 24.243243 | 77 | 0.444259 |
f16d1cdb27f16e68f138487b6cdb79fe5e7f8f74 | 5,858 | hpp | C++ | rpc_examples/RpcServer.hpp | cd606/tm_examples | 5ea8e9774f5070fbcc073c71c39bcb7febef88a7 | [
"Apache-2.0"
] | 1 | 2020-05-22T08:47:00.000Z | 2020-05-22T08:47:00.000Z | rpc_examples/RpcServer.hpp | cd606/tm_examples | 5ea8e9774f5070fbcc073c71c39bcb7febef88a7 | [
"Apache-2.0"
] | null | null | null | rpc_examples/RpcServer.hpp | cd606/tm_examples | 5ea8e9774f5070fbcc073c71c39bcb7febef88a7 | [
"Apache-2.0"
] | null | null | null | #ifndef RPC_SERVER_HPP_
#define RPC_SERVER_HPP_
#include <tm_kit/infra/GenericLift.hpp>
#include <unordered_map>
#include "RpcInterface.hpp"
namespace rpc_examples {
template <class R>
auto simpleFacility()
-> typename R::template OnOrderFacilityPtr<Input,Output>
{
using namespace dev::cd606::tm;
using GL = typename infra::GenericLift<typename R::AppType>;
return GL::lift(infra::LiftAsFacility{}, [](Input &&input) -> Output {
return {input.y+":"+std::to_string(input.x)};
});
}
template <class R>
auto clientStreamFacility()
-> typename R::template OnOrderFacilityPtr<Input,Output>
{
using M = typename R::AppType;
class Facility final : public M::template AbstractOnOrderFacility<Input,Output> {
private:
struct PerIDData {
std::string res;
int remainingCount;
};
std::unordered_map<typename M::EnvironmentType::IDType, PerIDData> remainingInputs_;
public:
Facility() : remainingInputs_() {}
virtual ~Facility() = default;
virtual void handle(typename M::template InnerData<
typename M::template Key<Input>
> &&input) override final {
auto id = input.timedData.value.id();
auto const &realInput = input.timedData.value.key();
auto iter = remainingInputs_.find(id);
if (iter == remainingInputs_.end()) {
iter = remainingInputs_.insert({
id, PerIDData {
realInput.y+":"+std::to_string(realInput.x)
, realInput.x-1
}
}).first;
} else {
iter->second.res += ","+realInput.y+":"+std::to_string(realInput.x);
--iter->second.remainingCount;
}
if (iter->second.remainingCount <= 0) {
this->publish(
input.environment
, typename M::template Key<Output> {
id, {std::move(iter->second.res)}
}
, true //this is the last (and only) one output for this input
);
remainingInputs_.erase(iter);
}
}
};
return M::template fromAbstractOnOrderFacility(new Facility());
}
template <class R>
auto serverStreamFacility()
-> typename R::template OnOrderFacilityPtr<Input,Output>
{
using M = typename R::AppType;
class Facility final : public M::template AbstractOnOrderFacility<Input,Output> {
public:
Facility() {}
virtual ~Facility() = default;
virtual void handle(typename M::template InnerData<
typename M::template Key<Input>
> &&input) override final {
auto id = input.timedData.value.id();
auto const &realInput = input.timedData.value.key();
int resultCount = std::max(1,realInput.x);
Output o {realInput.y+":"+std::to_string(realInput.x)};
for (int ii=1; ii<=resultCount; ++ii) {
this->publish(
input.environment
, typename M::template Key<Output> {
id, o
}
, (ii == resultCount)
);
}
}
};
return M::template fromAbstractOnOrderFacility(new Facility());
}
template <class R>
auto bothStreamFacility()
-> typename R::template OnOrderFacilityPtr<Input,Output>
{
using M = typename R::AppType;
class Facility final : public M::template AbstractOnOrderFacility<Input,Output> {
private:
struct PerIDData {
std::vector<Output> res;
int remainingCount;
};
std::unordered_map<typename M::EnvironmentType::IDType, PerIDData> remainingInputs_;
public:
Facility() : remainingInputs_() {}
virtual ~Facility() = default;
virtual void handle(typename M::template InnerData<
typename M::template Key<Input>
> &&input) override final {
auto id = input.timedData.value.id();
auto const &realInput = input.timedData.value.key();
auto iter = remainingInputs_.find(id);
if (iter == remainingInputs_.end()) {
iter = remainingInputs_.insert({
id, PerIDData {
{Output {realInput.y+":"+std::to_string(realInput.x)}}
, realInput.x-1
}
}).first;
} else {
iter->second.res.push_back(Output {realInput.y+":"+std::to_string(realInput.x)});
--iter->second.remainingCount;
}
if (iter->second.remainingCount <= 0) {
int sz = iter->second.res.size();
for (int ii=0; ii<sz; ++ii) {
this->publish(
input.environment
, typename M::template Key<Output> {
id, std::move(iter->second.res[ii])
}
, (ii==sz-1)
);
}
remainingInputs_.erase(iter);
}
}
};
return M::template fromAbstractOnOrderFacility(new Facility());
}
}
#endif | 40.123288 | 101 | 0.485831 |
f16de14756fc2d2d5852a7a7a9a4b907937f8e5d | 1,348 | cpp | C++ | Plugins/Tweaks/FixArmorDexBonusUnderOne.cpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 111 | 2018-01-16T18:49:19.000Z | 2022-03-13T12:33:54.000Z | Plugins/Tweaks/FixArmorDexBonusUnderOne.cpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 636 | 2018-01-17T10:05:31.000Z | 2022-03-28T20:06:03.000Z | Plugins/Tweaks/FixArmorDexBonusUnderOne.cpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 110 | 2018-01-16T19:05:54.000Z | 2022-03-28T03:44:16.000Z | #include "nwnx.hpp"
#include "API/CNWRules.hpp"
#include "API/CNWSCreature.hpp"
#include "API/CNWSCreatureStats.hpp"
#include "API/CNWSInventory.hpp"
#include "API/CNWSItem.hpp"
#include "API/CTwoDimArrays.hpp"
namespace Tweaks {
using namespace NWNXLib;
using namespace NWNXLib::API;
void FixArmorDexBonusUnderOne() __attribute__((constructor));
void FixArmorDexBonusUnderOne()
{
if (!Config::Get<bool>("FIX_ARMOR_DEX_BONUS_UNDER_ONE", false))
return;
LOG_INFO("Allowing armors with max DEX bonus under 1.");
static Hooks::Hook s_ReplacedFunc = Hooks::HookFunction(Functions::_ZN17CNWSCreatureStats9GetDEXModEi,
(void*)+[](CNWSCreatureStats *pThis, int32_t bArmorDexCap) -> uint8_t
{
auto nDexAC = pThis->m_nDexterityModifier;
if (bArmorDexCap)
{
auto pArmor = pThis->m_pBaseCreature->m_pInventory->GetItemInSlot(Constants::EquipmentSlot::Chest);
int nTempValue = 0;
if (pArmor && (nTempValue = pArmor->ComputeArmorClass()) > 0)
{
Globals::Rules()->m_p2DArrays->m_pArmorTable->GetINTEntry(nTempValue, CExoString("DEXBONUS"), &nTempValue);
if (nTempValue < nDexAC)
nDexAC = static_cast<char>(nTempValue);
}
}
return nDexAC;
}, Hooks::Order::Final);
}
}
| 28.680851 | 123 | 0.660237 |
f16e00fb02c76edea15ca84b7c9d391418773adc | 159 | cpp | C++ | character/Character.cpp | iliam-12/Bomberman | 62c688704e34bf1ec762adc76390a545b056e0cc | [
"MIT"
] | null | null | null | character/Character.cpp | iliam-12/Bomberman | 62c688704e34bf1ec762adc76390a545b056e0cc | [
"MIT"
] | null | null | null | character/Character.cpp | iliam-12/Bomberman | 62c688704e34bf1ec762adc76390a545b056e0cc | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2021
** Projects
** File description:
** Character
*/
#include "Character.hpp"
Character::Character()
{
}
Character::~Character()
{
} | 9.9375 | 24 | 0.660377 |
f1703130c69af6364a5de7c77c94f25e1c1c0483 | 1,850 | hpp | C++ | debug/client/gdb/TcpTransport.hpp | myArea51/binnavi | 021e62dcb7c3fae2a99064b0ea497cb221dc7238 | [
"Apache-2.0"
] | 3,083 | 2015-08-19T13:31:12.000Z | 2022-03-30T09:22:21.000Z | debug/client/gdb/TcpTransport.hpp | Jason-Cooke/binnavi | b98b191d8132cbde7186b486d23a217fcab4ec44 | [
"Apache-2.0"
] | 99 | 2015-08-19T14:42:49.000Z | 2021-04-13T10:58:32.000Z | debug/client/gdb/TcpTransport.hpp | Jason-Cooke/binnavi | b98b191d8132cbde7186b486d23a217fcab4ec44 | [
"Apache-2.0"
] | 613 | 2015-08-19T14:15:44.000Z | 2022-03-26T04:40:55.000Z | // Copyright 2011-2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// 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.
#ifndef TCPTRANSPORT_HPP
#define TCPTRANSPORT_HPP
#include <string>
#include "Transport.hpp"
#include "../conns/GenericSocketFunctions.hpp"
/**
* Transport class that can be used to create TCP connections to the gbdserver.
*/
class TcpTransport : public Transport {
private:
// Address of the host where the gdbserver is running.
std::string host;
// Port where the gdbserver is listening.
unsigned int port;
// Socket that can be used to connect with the gdbserver.
SOCKET gdbSocket;
public:
/**
* Creates a new TCP/IP connection to the GDB server.
*
* @param host Host address of the GDB server connection.
* @param port Port of the GDB server.
*/
TcpTransport(const std::string& host, unsigned int port)
: host(host),
port(port) {
}
// Opens the TCP/IP connection to the GDB server.
NaviError open();
// Closes the TCP/IP connection to the GDB server.
NaviError close();
// Checks whether data is available from the GDB server.
bool hasData() const;
// Sends data to the GDB server.
NaviError send(const char* buffer, unsigned int size) const;
// Receives data from the GDB server.
NaviError read(char* buffer, unsigned int size) const;
};
#endif
| 27.205882 | 79 | 0.714595 |
f17333fa914f67298836ac2d09f1dc1d58bbd82f | 12,350 | cpp | C++ | tests/string.tests.cpp | dynamic-static/dynamic_static.string | ea28d847e97d5f83c2051b722f6b4e4f508e55a6 | [
"MIT"
] | null | null | null | tests/string.tests.cpp | dynamic-static/dynamic_static.string | ea28d847e97d5f83c2051b722f6b4e4f508e55a6 | [
"MIT"
] | null | null | null | tests/string.tests.cpp | dynamic-static/dynamic_static.string | ea28d847e97d5f83c2051b722f6b4e4f508e55a6 | [
"MIT"
] | null | null | null |
/*
==========================================
Copyright (c) 2016-2021 dynamic_static
Licensed under the MIT license
http://opensource.org/licenses/MIT
==========================================
*/
#include "dynamic_static/string.hpp"
#include "catch2/catch.hpp"
namespace dst {
namespace tests {
static const std::string TheQuickBrownFox { "The quick brown fox jumps over the lazy dog!" };
/**
Validates that string::Proxy constructs correctly
*/
TEST_CASE("string::Proxy::Proxy()", "[string]")
{
SECTION("string::Proxy::Proxy(char)")
{
string::Proxy proxy('c');
CHECK(proxy == "c");
}
SECTION("string::Proxy::Proxy(std::string)")
{
string::Proxy proxy(TheQuickBrownFox);
CHECK(proxy == TheQuickBrownFox);
}
SECTION("string::Proxy::Proxy(const char*) (valid)")
{
string::Proxy proxy(TheQuickBrownFox.c_str());
CHECK(proxy == TheQuickBrownFox);
}
SECTION("string::Proxy::Proxy(const char*) (invalid)")
{
char* pStr = nullptr;
string::Proxy proxy(pStr);
CHECK(proxy == std::string());
}
}
/**
Validates string::contains()
*/
TEST_CASE("string::contains()", "[string]")
{
SECTION("Successful true")
{
REQUIRE(string::contains(TheQuickBrownFox, "fox"));
REQUIRE(string::contains(TheQuickBrownFox, "rown fox ju"));
REQUIRE(string::contains(TheQuickBrownFox, 'j'));
REQUIRE(string::contains(TheQuickBrownFox, '!'));
}
SECTION("Successful false")
{
REQUIRE_FALSE(string::contains(TheQuickBrownFox, "bat"));
REQUIRE_FALSE(string::contains(TheQuickBrownFox, '7'));
REQUIRE_FALSE(string::contains(TheQuickBrownFox, '?'));
}
SECTION("Empty str true")
{
REQUIRE(string::contains(TheQuickBrownFox, std::string()));
REQUIRE(string::contains(std::string(), std::string()));
}
SECTION("Empty str false")
{
REQUIRE_FALSE(string::contains(std::string(), TheQuickBrownFox));
}
}
/**
Validates string::starts_with()
*/
TEST_CASE("string::starts_with()", "[string]")
{
SECTION("Successful true")
{
REQUIRE(string::starts_with(TheQuickBrownFox, 'T'));
REQUIRE(string::starts_with(TheQuickBrownFox, "The"));
REQUIRE(string::starts_with(TheQuickBrownFox, "The quick"));
REQUIRE(string::starts_with(TheQuickBrownFox, TheQuickBrownFox));
}
SECTION("Successful false")
{
REQUIRE_FALSE(string::starts_with(TheQuickBrownFox, "he quick brown fox"));
REQUIRE_FALSE(string::starts_with(TheQuickBrownFox, "the"));
REQUIRE_FALSE(string::starts_with(TheQuickBrownFox, '8'));
}
SECTION("Empty str true")
{
REQUIRE(string::starts_with(TheQuickBrownFox, std::string()));
REQUIRE(string::starts_with(std::string(), std::string()));
}
SECTION("Empty str false")
{
REQUIRE_FALSE(string::starts_with(std::string(), TheQuickBrownFox));
}
}
/**
Validates string::ends_with()
*/
TEST_CASE("string::ends_with()", "[string]")
{
SECTION("Successful true")
{
REQUIRE(string::ends_with(TheQuickBrownFox, '!'));
REQUIRE(string::ends_with(TheQuickBrownFox, "dog!"));
REQUIRE(string::ends_with(TheQuickBrownFox, "lazy dog!"));
REQUIRE(string::ends_with(TheQuickBrownFox, TheQuickBrownFox));
}
SECTION("Successful false")
{
REQUIRE_FALSE(string::ends_with(TheQuickBrownFox, "he quick brown fox"));
REQUIRE_FALSE(string::ends_with(TheQuickBrownFox, "the"));
REQUIRE_FALSE(string::ends_with(TheQuickBrownFox, '8'));
}
SECTION("Empty str true")
{
REQUIRE(string::ends_with(TheQuickBrownFox, std::string()));
REQUIRE(string::ends_with(std::string(), std::string()));
}
SECTION("Empty str false")
{
REQUIRE_FALSE(string::ends_with(std::string(), TheQuickBrownFox));
}
}
/**
Validates string::replace()
*/
TEST_CASE("string::replace()", "[string]")
{
SECTION("Successful replace")
{
auto str = TheQuickBrownFox;
str = string::replace(str, '!', '.');
str = string::replace(str, "quick", "slow");
str = string::replace(str, "jumps", "trips");
str = string::replace(str, "lazy", "sleeping");
REQUIRE(str == "The slow brown fox trips over the sleeping dog.");
}
SECTION("Unsuccessful replace")
{
auto str = TheQuickBrownFox;
str = string::replace(str, "fox", "fox");
str = string::replace(str, std::string(), "bird");
str = string::replace(str, "cat", "dog");
str = string::replace(str, "frog", std::string());
REQUIRE(str == TheQuickBrownFox);
}
SECTION("Empty str replace")
{
auto str = std::string();
str = string::replace(str, '!', '.');
str = string::replace(str, "quick", "slow");
str = string::replace(str, "jumps", "trips");
str = string::replace(str, "lazy", "sleeping");
REQUIRE(str == std::string());
}
SECTION("Successful multi Replacement")
{
auto str = string::replace(
TheQuickBrownFox,
{
{ '!', '.' },
{ "quick", "slow" },
{ "jumps", "trips" },
{ "lazy", "sleeping" },
}
);
REQUIRE(str == "The slow brown fox trips over the sleeping dog.");
}
SECTION("Unsuccessful multi Replacement")
{
auto str = string::replace(
TheQuickBrownFox,
{
{ "fox", "fox" },
{ std::string(), "bird" },
{ "cat", "dog" },
{ "frog", std::string() },
}
);
REQUIRE(str == TheQuickBrownFox);
}
SECTION("Empty str multi Replacement")
{
auto str = string::replace(
std::string(),
{
{ "!", "." },
{ "quick", "slow" },
{ "jumps", "trips" },
{ "lazy", "sleeping" },
}
);
REQUIRE(str == std::string());
}
}
/**
Validates string::remove()
*/
TEST_CASE("string::remove()", "[string]")
{
SECTION("Successful remove")
{
auto str = TheQuickBrownFox;
str = string::remove(str, "The ");
str = string::remove(str, '!');
str = string::remove(str, "brown ");
str = string::remove(str, "lazy ");
REQUIRE(str == "quick fox jumps over the dog");
}
SECTION("Unsuccessful remove")
{
auto str = TheQuickBrownFox;
str = string::remove(str, '9');
str = string::remove(str, "antelope");
str = string::remove(str, "The ");
str = string::remove(str, " fox ");
REQUIRE(str == TheQuickBrownFox);
}
}
/**
Validates string::reduce_sequence()
*/
TEST_CASE("string::reduce_sequence()", "[string]")
{
std::string str = "some\\ugly\\/\\//\\path\\with\\a/////broken\\\\extension.....ext";
str = string::replace(str, '\\', "/");
str = string::reduce_sequence(str, '/');
str = string::reduce_sequence(str, ".");
str = string::replace(str, "ugly", "nice");
str = string::replace(str, "broken", "decent");
REQUIRE(str == "some/nice/path/with/a/decent/extension.ext");
}
/**
Validates string::scrub_path()
*/
TEST_CASE("string::scrub_path()", "[string]")
{
std::string str = "some//file/\\path/with\\various\\//conventions.txt";
REQUIRE(string::scrub_path(str) == "some/file/path/with/various/conventions.txt");
}
/**
Validates string::scrub_path()
*/
TEST_CASE("string::is_whitespace()", "[string]")
{
SECTION("Successful true")
{
REQUIRE(string::is_whitespace(' '));
REQUIRE(string::is_whitespace('\f'));
REQUIRE(string::is_whitespace('\n'));
REQUIRE(string::is_whitespace('\r'));
REQUIRE(string::is_whitespace('\t'));
REQUIRE(string::is_whitespace('\v'));
REQUIRE(string::is_whitespace(" \f\n\r\t\v"));
}
SECTION("Successful false")
{
REQUIRE_FALSE(string::is_whitespace('0'));
REQUIRE_FALSE(string::is_whitespace(" \f\n\r text \t\v"));
}
}
/**
Validates string::trim_leading_whitespace()
*/
TEST_CASE("string::trim_leading_whitespace()", "[string]")
{
auto str = " " + TheQuickBrownFox + " ";
REQUIRE(string::trim_leading_whitespace(str) == TheQuickBrownFox + " ");
}
/**
Validates string::trim_trailing_whitespace()
*/
TEST_CASE("string::trim_trailing_whitespace()", "[string]")
{
auto str = " " + TheQuickBrownFox + " ";
REQUIRE(string::trim_trailing_whitespace(str) == " " + TheQuickBrownFox);
}
/**
Validates string::trim_whitespace()
*/
TEST_CASE("string::trim_whitespace()", "[string]")
{
auto str = " " + TheQuickBrownFox + " ";
REQUIRE(string::trim_whitespace(str) == TheQuickBrownFox);
}
/**
Validates string::is_upper()
*/
TEST_CASE("string::is_upper()", "[string]")
{
SECTION("Successful true")
{
REQUIRE(string::is_upper('Z'));
REQUIRE(string::is_upper("THE"));
}
SECTION("Successful false")
{
REQUIRE_FALSE(string::is_upper('z'));
REQUIRE_FALSE(string::is_upper(TheQuickBrownFox));
}
}
/**
Validates string::to_upper()
*/
TEST_CASE("string::to_upper()", "[string]")
{
REQUIRE(string::to_upper(TheQuickBrownFox) == "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG!");
}
/**
Validates string::is_lower()
*/
TEST_CASE("string::is_lower()", "[string]")
{
SECTION("Successful true")
{
REQUIRE(string::is_lower('z'));
REQUIRE(string::is_lower("the"));
}
SECTION("Successful false")
{
REQUIRE_FALSE(string::is_lower('Z'));
REQUIRE_FALSE(string::is_lower(TheQuickBrownFox));
}
}
/**
Validates string::to_lower()
*/
TEST_CASE("string::to_lower()", "[string]")
{
REQUIRE(string::to_lower("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG!") == "the quick brown fox jumps over the lazy dog!");
}
/**
Validates string::get_line()
*/
TEST_CASE("string::get_line()", "[string]")
{
std::vector<std::string> lines {
{ "The quick\n" },
{ "brown fox\n" },
{ "jumps over\n" },
{ "the lazy\n" },
{ "dog." },
};
std::string str;
for (auto const& line : lines) {
str += line;
}
CHECK(string::get_line(str, str.find("quick")) == lines[0]);
CHECK(string::get_line(str, str.find("brown")) == lines[1]);
CHECK(string::get_line(str, str.find("over")) == lines[2]);
CHECK(string::get_line(str, str.find("lazy")) == lines[3]);
CHECK(string::get_line(str, str.find("dog")) == lines[4]);
}
/**
Validates string::split()
*/
TEST_CASE("string::split()", "[string]")
{
const std::vector<std::string> Tokens { "The", "quick", "brown", "fox" };
SECTION("Empty str")
{
REQUIRE(string::split(std::string(), " ").empty());
}
SECTION("char delimiter")
{
REQUIRE(string::split("The;quick;brown;fox", ';') == Tokens);
}
SECTION("char delimiter (prefix)")
{
REQUIRE(string::split(";The;quick;brown;fox", ';') == Tokens);
}
SECTION("char delimiter (postfix)")
{
REQUIRE(string::split("The;quick;brown;fox;", ';') == Tokens);
}
SECTION("char delimiter (prefix and postfix)")
{
REQUIRE(string::split(";The;quick;brown;fox;", ';') == Tokens);
}
SECTION("std::string delimiter")
{
REQUIRE(string::split("The COW quick COW brown COW fox COW ", " COW ") == Tokens);
}
}
/**
Validates string::split_snake_case()
*/
TEST_CASE("string::split_snake_case()", "[string]")
{
const std::vector<std::string> Tokens { "the", "quick", "brown", "fox" };
REQUIRE(string::split_snake_case("the_quick_brown_fox") == Tokens);
}
/**
Validates string::split_camel_case()
*/
TEST_CASE("string::split_camel_case()", "[string]")
{
const std::vector<std::string> Tokens { "The", "Quick", "Brown", "FOX" };
REQUIRE(string::split_camel_case("TheQuickBrownFOX") == Tokens);
}
/**
Validates string::to_hex_string()
*/
TEST_CASE("to_hex_string()", "[string]")
{
REQUIRE(to_hex_string(3735928559) == "0xdeadbeef");
REQUIRE(to_hex_string(3735928559, false) == "deadbeef");
}
} // namespace tests
} // namespace dst
| 28.196347 | 128 | 0.576923 |
f1764c9614f45b517ed5a136610b6a355f71f426 | 1,638 | cc | C++ | components/permissions/notification_permission_ui_selector.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | components/permissions/notification_permission_ui_selector.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | components/permissions/notification_permission_ui_selector.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/permissions/notification_permission_ui_selector.h"
#include "base/optional.h"
namespace permissions {
// static
bool NotificationPermissionUiSelector::ShouldSuppressAnimation(
base::Optional<QuietUiReason> reason) {
if (!reason)
return true;
switch (*reason) {
case QuietUiReason::kEnabledInPrefs:
case QuietUiReason::kPredictedVeryUnlikelyGrant:
return false;
case QuietUiReason::kTriggeredByCrowdDeny:
case QuietUiReason::kTriggeredDueToAbusiveRequests:
case QuietUiReason::kTriggeredDueToAbusiveContent:
return true;
}
}
NotificationPermissionUiSelector::Decision::Decision(
base::Optional<QuietUiReason> quiet_ui_reason,
base::Optional<WarningReason> warning_reason)
: quiet_ui_reason(quiet_ui_reason), warning_reason(warning_reason) {}
NotificationPermissionUiSelector::Decision::~Decision() = default;
NotificationPermissionUiSelector::Decision::Decision(const Decision&) = default;
NotificationPermissionUiSelector::Decision&
NotificationPermissionUiSelector::Decision::operator=(const Decision&) =
default;
// static
NotificationPermissionUiSelector::Decision
NotificationPermissionUiSelector::Decision::UseNormalUiAndShowNoWarning() {
return Decision(UseNormalUi(), ShowNoWarning());
}
base::Optional<PermissionUmaUtil::PredictionGrantLikelihood>
NotificationPermissionUiSelector::PredictedGrantLikelihoodForUKM() {
return base::nullopt;
}
} // namespace permissions
| 32.76 | 80 | 0.795482 |
f176b8bcd1d2f3be8e21be281432fc659e9960be | 7,059 | cpp | C++ | src/lab_extra/compute_shaders/compute_shaders.cpp | MihaiAnghel07/Tema1-Elemente-de-Grafica-pe-Calculator | 6f6cc6645d036cf4997f9e8028389cdbb1bb6a56 | [
"MIT",
"BSD-3-Clause"
] | 6 | 2016-10-10T14:27:17.000Z | 2020-10-09T09:31:37.000Z | src/lab_extra/compute_shaders/compute_shaders.cpp | MihaiAnghel07/Tema1-Elemente-de-Grafica-pe-Calculator | 6f6cc6645d036cf4997f9e8028389cdbb1bb6a56 | [
"MIT",
"BSD-3-Clause"
] | 9 | 2021-10-05T11:03:59.000Z | 2022-02-25T19:01:53.000Z | src/lab_extra/compute_shaders/compute_shaders.cpp | MihaiAnghel07/Tema1-Elemente-de-Grafica-pe-Calculator | 6f6cc6645d036cf4997f9e8028389cdbb1bb6a56 | [
"MIT",
"BSD-3-Clause"
] | 23 | 2016-11-05T12:55:01.000Z | 2021-05-13T16:55:40.000Z | #include "lab_extra/compute_shaders/compute_shaders.h"
#include <string>
#include <vector>
#include <iostream>
using namespace std;
using namespace extra;
static inline GLuint NumGroupSize(int dataSize, int groupSize)
{
return (dataSize + groupSize - 1) / groupSize;
}
static void DispatchCompute(unsigned int sizeX, unsigned int sizeY, unsigned int sizeZ, unsigned int workGroupSize, bool synchronize = true)
{
glDispatchCompute(NumGroupSize(sizeX, workGroupSize), NumGroupSize(sizeY, workGroupSize), NumGroupSize(sizeZ, workGroupSize));
if (synchronize) {
glMemoryBarrier(GL_ALL_BARRIER_BITS);
}
CheckOpenGLError();
}
/*
* To find out more about `FrameStart`, `Update`, `FrameEnd`
* and the order in which they are called, see `world.cpp`.
*/
ComputeShaders::ComputeShaders()
{
}
ComputeShaders::~ComputeShaders()
{
delete frameBuffer;
delete texture1;
delete texture2;
}
void ComputeShaders::Init()
{
auto camera = GetSceneCamera();
camera->SetPositionAndRotation(glm::vec3(0, 5, 4), glm::quat(glm::vec3(-30 * TO_RADIANS, 0, 0)));
camera->Update();
// Load a mesh from file into GPU memory
{
Mesh* mesh = new Mesh("sphere");
mesh->LoadMesh(PATH_JOIN(window->props.selfDir, RESOURCE_PATH::MODELS, "primitives"), "sphere.obj");
meshes[mesh->GetMeshID()] = mesh;
}
{
Mesh* mesh = new Mesh("bamboo");
mesh->LoadMesh(PATH_JOIN(window->props.selfDir, RESOURCE_PATH::MODELS, "vegetation", "bamboo"), "bamboo.obj");
meshes[mesh->GetMeshID()] = mesh;
}
{
Mesh* mesh = new Mesh("quad");
mesh->LoadMesh(PATH_JOIN(window->props.selfDir, RESOURCE_PATH::MODELS, "primitives"), "quad.obj");
mesh->UseMaterials(false);
meshes[mesh->GetMeshID()] = mesh;
}
const string shaderPath = PATH_JOIN(window->props.selfDir, SOURCE_PATH::EXTRA, "compute_shaders", "shaders");
// Create a shader program for rendering to texture
{
Shader *shader = new Shader("ComputeShaders");
shader->AddShader(PATH_JOIN(shaderPath, "VertexShader.glsl"), GL_VERTEX_SHADER);
shader->AddShader(PATH_JOIN(shaderPath, "FragmentShader.glsl"), GL_FRAGMENT_SHADER);
shader->CreateAndLink();
shaders[shader->GetName()] = shader;
}
{
Shader *shader = new Shader("FullScreenPass");
shader->AddShader(PATH_JOIN(shaderPath, "FullScreenPass.VS.glsl"), GL_VERTEX_SHADER);
shader->AddShader(PATH_JOIN(shaderPath, "FullScreenPass.FS.glsl"), GL_FRAGMENT_SHADER);
shader->CreateAndLink();
shaders[shader->GetName()] = shader;
}
{
Shader *shader = new Shader("ComputeShader");
shader->AddShader(PATH_JOIN(shaderPath, "ComputeShader.CS.glsl"), GL_COMPUTE_SHADER);
shader->CreateAndLink();
shaders[shader->GetName()] = shader;
}
auto resolution = window->GetResolution();
frameBuffer = new FrameBuffer();
frameBuffer->Generate(resolution.x, resolution.y, 3);
texture1 = new Texture2D();
texture1->Create(nullptr, resolution.x, resolution.y, 4);
texture2 = new Texture2D();
texture2->Create(nullptr, resolution.x, resolution.y, 4);
}
void ComputeShaders::FrameStart()
{
}
void ComputeShaders::Update(float deltaTimeSeconds)
{
angle += 0.5f * deltaTimeSeconds;
ClearScreen();
{
frameBuffer->Bind();
DrawScene();
}
// Run compute shader
{
auto shader = shaders["ComputeShader"];
shader->Use();
glm::ivec2 resolution = frameBuffer->GetResolution();
glBindImageTexture(0, frameBuffer->GetTextureID(0), 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);
glBindImageTexture(1, texture1->GetTextureID(), 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA8);
DispatchCompute(resolution.x, resolution.y, 1, 16, true);
}
// Render the scene normaly
FrameBuffer::BindDefault();
if (fullScreenPass)
{
{
auto shader = shaders["FullScreenPass"];
shader->Use();
{
int locTexture = shader->GetUniformLocation("texture_1");
glUniform1i(locTexture, 0);
frameBuffer->BindTexture(0, GL_TEXTURE0);
}
{
int locTexture = shader->GetUniformLocation("texture_2");
glUniform1i(locTexture, 1);
frameBuffer->BindTexture(1, GL_TEXTURE0 + 1);
}
{
int locTexture = shader->GetUniformLocation("texture_3");
glUniform1i(locTexture, 2);
frameBuffer->BindTexture(2, GL_TEXTURE0 + 2);
}
{
int locTexture = shader->GetUniformLocation("texture_4");
glUniform1i(locTexture, 3);
glActiveTexture(GL_TEXTURE0 + 3);
glBindTexture(GL_TEXTURE_2D, texture1->GetTextureID());
}
int locTextureID = shader->GetUniformLocation("textureID");
glUniform1i(locTextureID, textureID);
glm::mat4 modelMatrix(1);
RenderMesh(meshes["quad"], shader, modelMatrix);
}
}
}
void ComputeShaders::DrawScene()
{
for (int i = 0; i < 16; i++)
{
float rotateAngle = (angle + i) * ((i % 2) * 2 - 1);
glm::vec3 position = glm::vec3(-4 + (i % 4) * 2.5, 0, -2 + (i / 4) * 2.5);
glm::mat4 modelMatrix = glm::translate(glm::mat4(1), position);
modelMatrix = glm::rotate(modelMatrix, rotateAngle, glm::vec3(0, 1, 0));
modelMatrix = glm::scale(modelMatrix, glm::vec3(0.1f));
RenderMesh(meshes["bamboo"], shaders["ComputeShaders"], modelMatrix);
}
}
void ComputeShaders::FrameEnd()
{
DrawCoordinateSystem();
}
/*
* These are callback functions. To find more about callbacks and
* how they behave, see `input_controller.h`.
*/
void ComputeShaders::OnInputUpdate(float deltaTime, int mods)
{
// Treat continuous update based on input
}
void ComputeShaders::OnKeyPress(int key, int mods)
{
// Add key press event
if (key == GLFW_KEY_F)
{
fullScreenPass = !fullScreenPass;
}
for (int i = 1; i < 9; i++)
{
if (key == GLFW_KEY_0 + i)
{
textureID = i - 1;
}
}
}
void ComputeShaders::OnKeyRelease(int key, int mods)
{
// Add key release event
}
void ComputeShaders::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY)
{
// Add mouse move event
}
void ComputeShaders::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods)
{
// Add mouse button press event
}
void ComputeShaders::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods)
{
// Add mouse button release event
}
void ComputeShaders::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY)
{
// Treat mouse scroll event
}
void ComputeShaders::OnWindowResize(int width, int height)
{
frameBuffer->Resize(width, height, 32);
// Treat window resize event
}
| 26.04797 | 140 | 0.627568 |
f179f7a91dfbb650165567c7a4008dfb576354df | 360 | cpp | C++ | Online Judges/UVALive/6758/2766212_AC_3ms_0kB.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | 4 | 2017-02-20T17:41:14.000Z | 2019-07-15T14:15:34.000Z | Online Judges/UVALive/6758/2766212_AC_3ms_0kB.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | null | null | null | Online Judges/UVALive/6758/2766212_AC_3ms_0kB.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
int ts,n,a,x,y,es,hd;
cin>>ts;
while(ts--)
{
cin>>n>>x>>y;
for(int i=0;i<n;i++)
{
cin>>a;
if(i==0) es=a;
if(i==n-1) hd=a;
}
if(es==x&&hd==y) cout<<"BOTH"<<endl;
else if(es==x) cout<<"EASY"<<endl;
else if(hd==y) cout<<"HARD"<<endl;
else cout<<"OKAY"<<endl;
}
return 0;
}
| 15.652174 | 38 | 0.516667 |
f17b57f4ccf32c1801240cb141d9cc052e330e35 | 2,859 | cpp | C++ | src_vc141/queue/MirrorBuffer.cpp | nneesshh/mytoolkit | 336ae9c7077c8687a8cf8a2ce4aec804c28ab90c | [
"Apache-2.0"
] | null | null | null | src_vc141/queue/MirrorBuffer.cpp | nneesshh/mytoolkit | 336ae9c7077c8687a8cf8a2ce4aec804c28ab90c | [
"Apache-2.0"
] | null | null | null | src_vc141/queue/MirrorBuffer.cpp | nneesshh/mytoolkit | 336ae9c7077c8687a8cf8a2ce4aec804c28ab90c | [
"Apache-2.0"
] | 2 | 2020-11-04T03:07:09.000Z | 2020-11-05T08:14:45.000Z | //------------------------------------------------------------------------------
// MirrorBuffer.cpp
// (C) 2016 n.lee
//------------------------------------------------------------------------------
#include "MirrorBuffer.h"
// Round up to the next power of two
static uint32_t
next_pot(uint32_t x) {
--x;
x |= x >> 1; // handle 2 bit numbers
x |= x >> 2; // handle 4 bit numbers
x |= x >> 4; // handle 8 bit numbers
x |= x >> 8; // handle 16 bit numbers
x |= x >> 16; // handle 32 bit numbers
return ++x;
}
//------------------------------------------------------------------------------
/**
*/
CMirrorBuffer::CMirrorBuffer(size_t size)
: _xbuf(new char[2 * size])
, _size(size)
, _datalen(0)
, _first(0)
, _last(0)
, _bytes(0) {
}
//------------------------------------------------------------------------------
/**
*/
CMirrorBuffer::~CMirrorBuffer() {
delete[] _xbuf;
}
//------------------------------------------------------------------------------
/**
*/
bool
CMirrorBuffer::Write(const char *s, size_t l) {
if (l > 0) {
if (_datalen + l > _size) {
char *tmp = _xbuf;
size_t sz = _size;
// realloc
_size = next_pot(_datalen + 1);
if (_size <= 64 * 1024 * 1024) {
_xbuf = new char[2 * _size]; // at max 2 * 64 Megabytes
memcpy(_xbuf, tmp, sz);
memcpy(_xbuf + _size, tmp, sz);
delete[] tmp;
}
else {
// overflow
return false;
}
}
_bytes += (unsigned long)l;
// check block crossed mirror border
if (_last + l > _size) {
// size left until mirror border crossing
size_t l1 = _size - _last;
// always copy full block to buffer(_xbuf) + tail pointer(_last)
// because we have doubled the buffer size as mirror for performance reasons
memcpy(_xbuf + _last, s, l);
memcpy(_xbuf, s + l1, l - l1);
_last = l - l1;
}
else {
memcpy(_xbuf + _last, s, l); // append tail
memcpy(_xbuf + _size + _last, s, l); // append double buffer tail
_last += l;
}
_datalen += l;
}
return true;
}
//------------------------------------------------------------------------------
/**
*/
bool
CMirrorBuffer::Read(size_t l, std::string& out) {
const char *start = GetStart();
if (Skip(l)) {
out += std::string(start, l);
return true;
}
return false;
}
//------------------------------------------------------------------------------
/**
*/
bool
CMirrorBuffer::Skip(size_t l) {
if (l > 0) {
if (l > _datalen) {
return false; // not enough chars
}
// check block crossed mirror border
if (_first + l > _size) {
size_t l1 = _size - _first;
_first = l - l1;
}
else {
_first += l;
}
_datalen -= l;
if (!_datalen) {
_first = _last = 0;
}
}
return true;
}
/** -- EOF -- **/
| 21.496241 | 81 | 0.434767 |
f17ba655540cfb9782ec5e74f3f052b3f38ac763 | 1,261 | cc | C++ | aiks/paint_pass_delegate.cc | eyebrowsoffire/impeller | bdb74c046327bf1203b4293806399ccf57bf1c6e | [
"BSD-3-Clause"
] | null | null | null | aiks/paint_pass_delegate.cc | eyebrowsoffire/impeller | bdb74c046327bf1203b4293806399ccf57bf1c6e | [
"BSD-3-Clause"
] | 2 | 2022-03-16T05:29:37.000Z | 2022-03-31T05:35:03.000Z | aiks/paint_pass_delegate.cc | eyebrowsoffire/impeller | bdb74c046327bf1203b4293806399ccf57bf1c6e | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/aiks/paint_pass_delegate.h"
#include "impeller/entity/contents/contents.h"
#include "impeller/entity/contents/texture_contents.h"
namespace impeller {
PaintPassDelegate::PaintPassDelegate(Paint paint, std::optional<Rect> coverage)
: paint_(std::move(paint)), coverage_(std::move(coverage)) {}
// |EntityPassDelgate|
PaintPassDelegate::~PaintPassDelegate() = default;
// |EntityPassDelgate|
std::optional<Rect> PaintPassDelegate::GetCoverageRect() {
return coverage_;
}
// |EntityPassDelgate|
bool PaintPassDelegate::CanElide() {
return paint_.color.IsTransparent();
}
// |EntityPassDelgate|
bool PaintPassDelegate::CanCollapseIntoParentPass() {
return paint_.color.IsOpaque();
}
// |EntityPassDelgate|
std::shared_ptr<Contents> PaintPassDelegate::CreateContentsForSubpassTarget(
std::shared_ptr<Texture> target) {
auto contents = std::make_shared<TextureContents>();
contents->SetTexture(target);
contents->SetSourceRect(IRect::MakeSize(target->GetSize()));
contents->SetOpacity(paint_.color.alpha);
return contents;
}
} // namespace impeller
| 28.659091 | 79 | 0.762887 |
f17e3fa2dd08809c92c8eb600fd8d011d386bf9f | 1,664 | cpp | C++ | src/xray/editor/world/sources/property_integer_values_value_getter.cpp | ixray-team/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 3 | 2021-10-30T09:36:14.000Z | 2022-03-26T17:00:06.000Z | src/xray/editor/world/sources/property_integer_values_value_getter.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | null | null | null | src/xray/editor/world/sources/property_integer_values_value_getter.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:08.000Z | 2022-03-26T17:00:08.000Z | ////////////////////////////////////////////////////////////////////////////
// Created : 09.01.2008
// Author : Dmitriy Iassenev
// Copyright (C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#include "property_integer_values_value_getter.h"
using System::Collections::IList;
using System::Collections::ArrayList;
using System::Object;
using System::String;
property_integer_values_value_getter::property_integer_values_value_getter (
integer_getter_type^ getter,
integer_setter_type^ setter,
string_collection_getter_type^ collection_getter,
string_collection_size_getter_type^ collection_size_getter
) :
inherited (getter, setter),
m_collection_getter (collection_getter),
m_collection_size_getter(collection_size_getter)
{
}
Object ^property_integer_values_value_getter::get_value ()
{
int value = safe_cast<int>(inherited::get_value());
if (value < 0)
value = 0;
int count = collection()->Count;
if (value >= count)
value = count - 1;
return (value);
}
void property_integer_values_value_getter::set_value (Object ^object)
{
String^ string_value = dynamic_cast<String^>(object);
int index = collection()->IndexOf(string_value);
ASSERT ((index >= 0));
inherited::set_value (index);
}
IList^ property_integer_values_value_getter::collection ()
{
ArrayList^ collection = gcnew ArrayList();
u32 count = m_collection_size_getter();
for (u32 i=0; i<count; ++i)
{
collection->Add (m_collection_getter(i));
}
return (collection);
} | 28.20339 | 77 | 0.631611 |
f181038812497d9604a0b6af20668d4db4e0b5f5 | 1,847 | hpp | C++ | tensors++/exceptions/tensor_formation.hpp | Razdeep/ml-plus-plus | 02c2c2cc2e05c9e7de4c7155ebdab78a3c519ed2 | [
"Apache-2.0"
] | null | null | null | tensors++/exceptions/tensor_formation.hpp | Razdeep/ml-plus-plus | 02c2c2cc2e05c9e7de4c7155ebdab78a3c519ed2 | [
"Apache-2.0"
] | null | null | null | tensors++/exceptions/tensor_formation.hpp | Razdeep/ml-plus-plus | 02c2c2cc2e05c9e7de4c7155ebdab78a3c519ed2 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2018 Ashar <ashar786khan@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
#ifndef TENSOR_FORMATION_HPP
#define TENSOR_FORMATION_HPP
#include <exception>
#include <string>
namespace tensors {
namespace exceptions {
class tensor_index_exception : public std::exception {
const char *message;
public:
tensor_index_exception(std::string z) : message(z.c_str()){};
virtual const char *what() const noexcept final override {
return ("Index for the tensor is invalid :" + std::string(message)).c_str();
}
};
class initializer_exception : public std::exception {
const char *message;
public:
initializer_exception(std::string z) : message(z.c_str()){};
virtual const char *what() const noexcept final override {
return ("Unable to initialize, check that you have a valid constructor in "
"the template type : " +
std::string(message))
.c_str();
}
};
class bad_init_shape : public std::exception {
const char *message;
public:
bad_init_shape(std::string z) : message(z.c_str()){};
virtual const char *what() const noexcept final override {
return ("Shape for Construction of Tensor is invalid. " +
std::string(message))
.c_str();
}
};
} // namespace exceptions
} // namespace tensors
#endif
| 28.415385 | 80 | 0.691933 |
f181881e8df62be95726c998d262bd3c1e562926 | 5,528 | hpp | C++ | code/w32/Delta.hpp | AndreLouisCaron/w32 | 75b26a149e268138cbcf43e6f4669756ac4ac850 | [
"BSD-2-Clause"
] | 9 | 2015-12-30T15:21:20.000Z | 2021-03-21T04:23:14.000Z | code/w32/Delta.hpp | AndreLouisCaron/w32 | 75b26a149e268138cbcf43e6f4669756ac4ac850 | [
"BSD-2-Clause"
] | 1 | 2022-01-02T11:12:57.000Z | 2022-01-02T11:12:57.000Z | code/w32/Delta.hpp | AndreLouisCaron/w32 | 75b26a149e268138cbcf43e6f4669756ac4ac850 | [
"BSD-2-Clause"
] | 5 | 2018-04-09T04:44:58.000Z | 2020-04-10T12:51:51.000Z | #ifndef _w32_Delta_hpp__
#define _w32_Delta_hpp__
// Copyright (c) 2009-2012, Andre Caron (andre.l.caron@gmail.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*!
* @file w32/Delta.hpp
* @brief Relative offsets for @c w32::Time instances.
*/
#include "__configure__.hpp"
#include <w32/types.hpp>
namespace w32 {
//! @addtogroup w32
//! @{
/*!
* @brief Relative offset for @c Time instances.
*
* The native resolution for time deltas is a 100 nanoseconds (1/10 of a
* microsecond). Keep in mind that not all functions that accept a @c Time
* instance support such a fine-grained resolution. Many operate at a
* resolution larger than 1 millisecond.
*
* @see Time
*/
class Delta
{
/* class methods. */
public:
/*!
* @brief One microsecond (us) delta.
*/
static Delta microsecond ();
/*!
* @brief One millisecond (ms) delta.
*/
static Delta millisecond ();
/*!
* @brief One second (s) delta.
*/
static Delta second ();
/*!
* @brief One minute (m) delta.
*/
static Delta minute ();
/*!
* @brief One hour (h) delta.
*/
static Delta hour ();
/*!
* @brief One day (d) delta.
*/
static Delta day ();
/*!
* @brief One year (d) delta (365 days).
* @see leap_year()
*/
static Delta year ();
/*!
* @brief One leap year (d) delta (366 days).
* @see year()
*/
static Delta leap_year ();
/* data. */
private:
// Number of slices of 100 nanoseconds.
qword myTicks;
/* construction. */
public:
/*!
* @brief Create a null delta, represents "no offset".
*/
Delta ();
private:
// For internal use only.
Delta ( qword ticks );
/* methods. */
public:
/*!
* @brief Get the delta as an integer multiple of the native resolution.
*
* @note The native resolution is 100 nanoseconds (1/10 us).
*/
qword ticks () const;
dword microseconds () const;
dword milliseconds () const;
dword seconds () const;
/* operators. */
public:
/*!
* @brief Compute an integer multiple of the delta.
*/
Delta& operator*= ( int rhs );
/*!
* @brief Compute a multiple of the delta.
*/
Delta& operator*= ( double rhs );
/*!
* @brief Compute an integer fraction of the delta.
*/
Delta& operator/= ( int rhs );
/*!
* @brief Increase the time delta.
*/
Delta& operator+= ( const Delta& rhs );
/*!
* @brief Decrease the time delta.
*/
Delta& operator-= ( const Delta& rhs );
};
/*!
* @brief Increase the time delta.
*/
Delta operator+ ( const Delta& lhs, const Delta& rhs );
/*!
* @brief Decrease the time delta.
*/
Delta operator- ( const Delta& lhs, const Delta& rhs );
/*!
* @brief Compute an integer multiple of a delta.
*/
Delta operator* ( const Delta& lhs, int rhs );
/*!
* @brief Compute an integer multiple of a delta.
*/
Delta operator* ( int lhs, const Delta& rhs );
/*!
* @brief Compute a multiple of a delta.
*/
Delta operator* ( const Delta& lhs, double rhs );
/*!
* @brief Compute a multiple of a delta.
*/
Delta operator* ( double lhs, const Delta& rhs );
/*!
* @brief Compute an integer fraction of a delta.
*/
Delta operator/ ( const Delta& lhs, int rhs );
/*!
* @brief Compute the relative size of two delta.
*/
double operator/ ( const Delta& lhs, const Delta& rhs );
bool operator> ( const Delta& lhs, const Delta& rhs );
bool operator< ( const Delta& lhs, const Delta& rhs );
bool operator<= ( const Delta& lhs, const Delta& rhs );
bool operator>= ( const Delta& lhs, const Delta& rhs );
//! @}
}
#endif /* _w32_Delta_hpp__ */
| 26.834951 | 80 | 0.577605 |
f1851e849cd7953caf46756e9ef8b5f3dd425704 | 11,788 | cpp | C++ | main/main.cpp | WuXiaoqiao/HAModule1 | a1b88a608325c0a20901736ef2908016f436cc8c | [
"Apache-2.0"
] | null | null | null | main/main.cpp | WuXiaoqiao/HAModule1 | a1b88a608325c0a20901736ef2908016f436cc8c | [
"Apache-2.0"
] | null | null | null | main/main.cpp | WuXiaoqiao/HAModule1 | a1b88a608325c0a20901736ef2908016f436cc8c | [
"Apache-2.0"
] | null | null | null | #include "freertos/FreeRTOS.h"
#include "freertos/task.h"
//#include "Arduino.h"
#include <WiFi.h>
#include <WiFiType.h>
#include "Esp.h"
#include "esp_log.h"
#include "sdkconfig.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_event_loop.h"
#include "nvs_flash.h"
#include "esp_task_wdt.h"
#include "time.h"
#include <vector>
#include "Schalter.h"
#define TAG "MODULE1"
#include "Common.h"
#include "html.h"
#include "WetterDaten.h"
#define ARDUINO_RUNNING_CORE 0
#define MINUTE (60*1000)
#define STUNDE (60*MINUTE)
#define TAGE (24*STUNDE)
#define JAHR (365*TAGE)
char ssid[] = SSID_MACRO; // your network SSID (name)
char pass[] = PASS_MACRO; // your network password (use for WPA, or use as key for WEP)
std::vector<Raum*> vecRaum;
WiFiServer server(80);
// connect to UDP returns true if successful or false if not
void ws_server(void *pvParameters);
bool inited = false;
bool TIME_OBTAINED = false;
int64_t lastCheck;
WetterDaten daten;
String requestHost;
String requestHost2;
Schalter * pGlobalSchalter;
void setup() {
uint64_t chipid = ESP.getEfuseMac();
ESP_LOGI(TAG, "ESP32 Chip ID = %04X", (uint16_t )(chipid >> 32)); //print High 2 bytes
ESP_LOGI(TAG, "%08X", (uint32_t )chipid); //print Low 4bytes.
uint32_t chipidLow = (chipid >> 32) % 65536;
ESP_LOGI(TAG, "chipidLow %d", chipidLow);
Raum* raum;
if ((chipidLow == 15363) || (chipidLow == 54686) || (chipidLow == 31852)) { // module 1
ESP_LOGI(TAG, "module 1 init");
raum = new Raum("Zimmer Jayde");
vecRaum.push_back(raum);
raum->vecSchaltern.push_back(new LichtSchalter(13, 4, "Jayde"));
raum->vecSchaltern.push_back(
new RolloSchalter(14, 17, 12, 16, 600, 2000, "Jayde"));
raum = new Raum("Arbeitszimmer");
vecRaum.push_back(raum);
raum->vecSchaltern.push_back(new LichtSchalter(27, 15, "AZ"));
raum->vecSchaltern.push_back(
new RolloSchalter(26, 0, 25, 2, 600, 2000, "AZ"));
raum = new Raum("Elternzimmer");
vecRaum.push_back(raum);
raum->vecSchaltern.push_back(new LichtSchalter(33, 5, "EZ"));
raum->vecSchaltern.push_back(
new RolloSchalter(22, 19, 32, 18, 530, 2000, "EZ"));
} //4610366690621131300 247728676
if ((chipidLow == 20500)) { // module 2
ESP_LOGI(TAG, "module2 init");
raum = new Raum("Wohnzimmer");
vecRaum.push_back(raum);
raum->vecSchaltern.push_back(new LichtSchalter(13, 15, "Mitte"));
raum->vecSchaltern.push_back(new LichtSchalter(12, 2, "Fenster"));
raum->vecSchaltern.push_back(new LichtSchalter(14, 0, "Küche"));
raum->vecSchaltern.push_back(
new RolloSchalter(26, 4, 27, 16, 500, 2000, "Fenster"));
raum->vecSchaltern.push_back(
new RolloSchalter(25, 17, 33, 5, 500, 2000, "Tür"));
raum = new Raum("Gang");
vecRaum.push_back(raum);
raum->vecSchaltern.push_back(new AutoLichtSchalter(32, 18, "Gang"));
raum->vecSchaltern.push_back(
new RolloSchalter(22, 19, 23, 21, 500, 2000, "Gang"));
}
if ((chipidLow == 21614)) { // module 3
ESP_LOGI(TAG, "module3 init");
raum = new Raum("Haupteingang");
vecRaum.push_back(raum);
raum->vecSchaltern.push_back(new TasterSchalter(13, 4, "Tür"));
raum = new Raum("Wohnung");
vecRaum.push_back(raum);
raum->vecSchaltern.push_back(new LichtSchalter(13, 15, "Tür"));
}
raum = new Raum("Global");
pGlobalSchalter = new GlobalSchalter();
raum->vecSchaltern.push_back(pGlobalSchalter);
vecRaum.push_back(raum);
ESP_LOGI(TAG, "First Init ");
for (auto itr : vecRaum) {
itr->Init();
}
//int readin = digitalRead(23);
//ESP_LOGI(TAG, "GPIO IN: %d, state: %d\n", 23, readin);
ESP_LOGI(TAG, "Connecting to ");ESP_LOGI(TAG, "ESP_HWID %llu", ESP.getEfuseMac());
//WiFi.onEvent(WiFiGotIP, WiFiEvent_t::SYSTEM_EVENT_STA_GOT_IP);
WiFi.begin(ssid, pass);
/*if ((chipidLow == 60436) || (chipidLow == 20500)) { // module 1
connectUDP();
}*/
//LogCrashDump();
ESP_LOGI(TAG, "Start Server");
//Create Websocket Server Task
xTaskCreatePinnedToCore(ws_server, "ws_server", 4096, NULL, 2, NULL, 1);
lastCheck = hmMillis();
}
void loop() {
if (((lastCheck + MINUTE) < hmMillis()) || (lastCheck > hmMillis())) {
if (WiFi.status() != WL_CONNECTED) {
WiFi.reconnect();
}
lastCheck = hmMillis();
}
if (WiFi.status() == WL_CONNECTED) {
if (!TIME_OBTAINED) {
obtain_time();
TIME_OBTAINED = true;
for (auto itr : vecRaum) {
itr->Init();
}
}
//daten.Check();
}
for (auto itrRaum : vecRaum) {
for (auto itr : itrRaum->vecSchaltern) {
itr->CheckIO();
}
}
for (auto itrRaum : vecRaum) {
for (auto itr : itrRaum->vecSchaltern) {
itr->Switch();
}
}
vTaskDelay(100 / portTICK_PERIOD_MS);
}
void loopTask(void *pvParameters) {
setup();
for (;;) {
micros(); //update overflow
loop();
}
}
void PutOperations(WiFiClient& client) {
for (auto itrRaum : vecRaum) {
itrRaum->PutOperations(client, requestHost);
}
}
void PutSettings(WiFiClient& client) {
for (auto itrRaum : vecRaum) {
itrRaum->PutSettings(client, requestHost);
}
}
void PutInfo(WiFiClient& client) {
client.print(TOSTRING(HTML_INFO));
client.print("<table>");
char buffer[500];
time_t now = hmMillis() / 1000;
struct tm* ti = gmtime(&now);
client.print("");
snprintf(buffer, 500,
"<tr><th>Time since restart</th><td>%d Tage %02d:%02d:%02d</td>",
ti->tm_yday, ti->tm_hour, ti->tm_min, ti->tm_sec);
client.print(buffer);
client.print("<th>Local Time</th><td>");
tm tmnow = Schalter::GetTime();
strftime(buffer, sizeof(buffer), "%X", &tmnow);
client.print(buffer);
client.print("</td></tr>");
for (auto itrRaum : vecRaum) {
for (auto itr : itrRaum->vecSchaltern) {
if (itr->Putinfo(buffer, 500)) {
client.print(buffer);
}
}
}
client.print("</table>");
}
void decodeUrlComponent(String* value) {
//ESP_LOGI(TAG, "URL Comp: %s", value->c_str()); // print a message out the serial port
value->replace("%20", " ");
value->replace("%C3%BC", "ü");
/* value>replace("%21", "!");
value>replace("%22", "\"");
value>replace("%23", "#");
value>replace("%24", "$");
value>replace("%25", "%");
value>replace("%26", "&");
value>replace("%27", "'");
value>replace("%28", "(");
value>replace("%29", ")");
value>replace("%2A", "*");
value>replace("%2B", "+");
value>replace("%2C", ",");
value>replace("%2D", "");
value>replace("%2E", ".");
value>replace("%2F", "/");
value>replace("%3A", ":");
value>replace("%3B", ";");
value>replace("%3C", "<");
value>replace("%3D", "=");
value>replace("%3E", ">");
value>replace("%3F", "?");
value>replace("%40", "@");*/
}
void ws_server(void *pvParameters) {
//connection references
server.begin();
boolean serverStarted = true;
boolean directIP = true;
for (;;) {
if ((WiFi.status() == WL_CONNECTED) && (serverStarted)) {
requestHost = WiFi.localIP().toString();
WiFiClient client = server.available(); // listen for incoming clients
if (client) {
ESP_LOGI(TAG, "New Client."); // print a message out the serial port
Schalter* pSchalter = NULL;
String currentLine = ""; // make a String to hold incoming data from the client
int64_t start = hmMillis();
while (client.connected() && ((hmMillis() - start) < 500)) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
ESP_LOGI(TAG, "Write Response");
client.print(TOSTRING(RESPONSE_HEADER));
client.print(TOSTRING(HTML_HEAD_TOP));
char buffer[1024];
std::string ip1 = "192.168.0.103";
std::string ip2 = "192.168.0.104";
std::string ip3 = "192.168.0.105";
if (!directIP) {
ip1 = "localhost:103";
ip2 = "localhost:104";
ip3 = "localhost:105";
}
snprintf(buffer, 1024,
TOSTRING(HTML_HEAD_CENTER), ip1.c_str(),
ip2.c_str());
client.print(buffer);
client.print(TOSTRING(HTML_HEAD_BOTTOM));
snprintf(buffer, 1024, TOSTRING(HTML_BODY),
ip1.c_str(), ip2.c_str(), ip3.c_str(),
requestHost.c_str());
client.print(buffer);
PutInfo(client);
client.print(TOSTRING(HTML_FOOTER));
// The HTTP response ends with another blank line:
client.println();
client.flush();
// break out of the while loop:
break;
} else {
if (strncmp("Host: ", currentLine.c_str(), 6)
== 0) {
requestHost = currentLine.substring(
strlen("Host: "));
if (strncmp(requestHost.c_str(), "192.168",
7) == 0) {
directIP = true;
} else {
directIP = false;
}ESP_LOGI(TAG, "URL Host: %s", requestHost.c_str());
} else {
requestHost = WiFi.localIP().toString();
}
currentLine = "";
}
} else if ((c != '/') && (c != '\r')) { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
} else if (c == '/') {
decodeUrlComponent(¤tLine);
//ESP_LOGI(TAG, " Process %s", currentLine.c_str());
if (pSchalter == NULL) {
if (currentLine == "GET_OPERATIONS") {
client.print(TOSTRING(RESPONSE_HEADER));
PutOperations(client);
client.println();
client.flush();
// break out of the while loop:
break;
} else if (currentLine == "GET_SETTINGS") {
client.print(TOSTRING(RESPONSE_HEADER));
PutSettings(client);
client.println();
client.flush();
// break out of the while loop:
break;
} else if (currentLine.length() > 3) {
//ESP_LOGI(TAG, " currentLine: \"%s\"",currentLine.c_str());
//ESP_LOGI(TAG, " currentLine: \"%d\"",(int)currentLine.toInt());
unsigned int currNumber =
currentLine.toInt();
for (auto itrRaum : vecRaum) {
for (auto itr : itrRaum->vecSchaltern) {
boolean found = strcmp(
itr->bezeichnung.c_str(),
currentLine.c_str()) == 0;
unsigned int bezAddr =
(unsigned int) &(itr->bezeichnung);
if ((bezAddr == currNumber)
|| found) {
pSchalter = itr;
ESP_LOGI(TAG, " Found: \"%s\"",
currentLine.c_str());
break;
}
}
if (pSchalter != NULL) {
break;
}
}
}
} else {
ESP_LOGI(TAG, " ProcessCommand: \"%s\"",
currentLine.c_str());
pSchalter->ProcessCommand(
std::string(currentLine.c_str()),
client);
pSchalter = NULL;
}
currentLine = ""; // add it to the end of the currentLine
}
}
}
}
// close the connection:
client.stop();
} else if ((WiFi.status() == WL_CONNECTED)
&& (serverStarted == false)) {
ESP_LOGI(TAG, "WLan Reconnected server restarted");
server.begin();
serverStarted = true;
} else if ((WiFi.status() != WL_CONNECTED) && (serverStarted)) {
ESP_LOGI(TAG, "WLan disconnected server stoped");
serverStarted = false;
server.stop();
}
vTaskDelay(100 / portTICK_PERIOD_MS);
}
}
extern "C" void app_main() {
initArduino();
xTaskCreatePinnedToCore(loopTask, "loopTask", 4096, NULL, 1, NULL, 0);
}
| 30.697917 | 106 | 0.606804 |
f187285a2755508662a53f8b5719f3edde0b0143 | 10,386 | cpp | C++ | util/stream/ios_ut.cpp | jjzhang166/balancer | 84addf52873d8814b8fd30289f2fcfcec570c151 | [
"Unlicense"
] | 39 | 2015-03-12T19:49:24.000Z | 2020-11-11T09:58:15.000Z | util/stream/ios_ut.cpp | jjzhang166/balancer | 84addf52873d8814b8fd30289f2fcfcec570c151 | [
"Unlicense"
] | null | null | null | util/stream/ios_ut.cpp | jjzhang166/balancer | 84addf52873d8814b8fd30289f2fcfcec570c151 | [
"Unlicense"
] | 11 | 2016-01-14T16:42:00.000Z | 2022-01-17T11:47:33.000Z | #include "ios.h"
#include "glue.h"
#include "tokenizer.h"
#include <string>
#include <iostream>
#include <library/unittest/registar.h>
#include <util/string/cast.h>
#include <util/memory/tempbuf.h>
#include <util/charset/recyr.hh>
class TStreamsTest: public TTestBase {
UNIT_TEST_SUITE(TStreamsTest);
UNIT_TEST(TestGenericRead);
UNIT_TEST(TestGenericWrite);
UNIT_TEST(TestReadLine);
UNIT_TEST(TestMemoryStream);
UNIT_TEST(TestStreamBufAdaptor);
UNIT_TEST(TestBufferedIO);
UNIT_TEST(TestBufferStream);
UNIT_TEST(TestTokenizer);
UNIT_TEST(TestStringStream);
UNIT_TEST(TestWtrokaInput);
UNIT_TEST(TestWtrokaOutput);
UNIT_TEST(TestIStreamOperators);
UNIT_TEST_SUITE_END();
public:
void TestGenericRead();
void TestGenericWrite();
void TestReadLine();
void TestMemoryStream();
void TestStreamBufAdaptor();
void TestBufferedIO();
void TestBufferStream();
void TestTokenizer();
void TestStringStream();
void TestWtrokaInput();
void TestWtrokaOutput();
void TestIStreamOperators();
};
UNIT_TEST_SUITE_REGISTRATION(TStreamsTest);
void TStreamsTest::TestIStreamOperators()
{
Stroka data ("first line\r\nsecond\t\xd1\x82\xd0\xb5\xd1\x81\xd1\x82 line\r\n 1 -4 59 4320000000009999999 c\n -1.5 1e-110");
TStringInput si(data);
Stroka l1;
Stroka l2;
Stroka l3;
Wtroka w1;
Stroka l4;
ui16 i1;
i16 i2;
i32 i3;
ui64 i4;
char c1;
unsigned char c2;
float f1;
double f2;
si >> l1 >> l2 >> l3 >> w1 >> l4 >> i1 >> i2 >> i3 >> i4 >> c1 >> c2 >> f1 >> f2;
UNIT_ASSERT_EQUAL(l1, "first");
UNIT_ASSERT_EQUAL(l2, "line");
{
char buf[128];
size_t in_readed = 0;
size_t out_writed = 0;
RecodeFromUnicode(CODES_WIN, w1.c_str(), buf, w1.size(), sizeof(buf) - 1, in_readed, out_writed);
buf[out_writed] = 0;
UNIT_ASSERT_EQUAL(strcmp(buf, "\xf2\xe5\xf1\xf2"), 0);
}
UNIT_ASSERT_EQUAL(l3, "second");
UNIT_ASSERT_EQUAL(l4, "line");
UNIT_ASSERT_EQUAL(i1, 1);
UNIT_ASSERT_EQUAL(i2, -4);
UNIT_ASSERT_EQUAL(i3, 59);
UNIT_ASSERT_EQUAL(i4, 4320000000009999999ULL);
UNIT_ASSERT_EQUAL(c1, 'c');
UNIT_ASSERT_EQUAL(c2, '\n');
UNIT_ASSERT_EQUAL(f1, -1.5);
UNIT_ASSERT_EQUAL(f2, 1e-110);
}
void TStreamsTest::TestStringStream() {
TStringStream s;
s << "qw\r\n1234" << "\n" << 34;
UNIT_ASSERT_EQUAL(s.ReadLine(), "qw");
UNIT_ASSERT_EQUAL(s.ReadLine(), "1234");
s << "\r\n" << 123.1;
UNIT_ASSERT_EQUAL(s.ReadLine(), "34");
UNIT_ASSERT_EQUAL(s.ReadLine(), "123.1");
UNIT_ASSERT_EQUAL(s.Str(), "qw\r\n1234\n34\r\n123.1");
}
void TStreamsTest::TestGenericRead() {
Stroka s("1234567890");
TStringInput si(s);
char buf[1024];
UNIT_ASSERT_EQUAL(si.Read(buf, 6), 6);
UNIT_ASSERT_EQUAL(memcmp(buf, "123456", 6), 0);
UNIT_ASSERT_EQUAL(si.Read(buf, 6), 4);
UNIT_ASSERT_EQUAL(memcmp(buf, "7890", 4), 0);
}
void TStreamsTest::TestGenericWrite() {
Stroka s;
TStringOutput so(s);
so.Write("123456", 6);
so.Write("7890", 4);
UNIT_ASSERT_EQUAL(s, "1234567890");
}
void TStreamsTest::TestReadLine() {
Stroka data("1234\r\n5678\nqw");
TStringInput si(data);
UNIT_ASSERT_EQUAL(si.ReadLine(), "1234");
UNIT_ASSERT_EQUAL(si.ReadLine(), "5678");
UNIT_ASSERT_EQUAL(si.ReadLine(), "qw");
}
void TStreamsTest::TestMemoryStream() {
char buf[1024];
TMemoryOutput mo(buf, sizeof(buf));
bool ehandled = false;
try {
for (size_t i = 0; i < sizeof(buf) + 1; ++i) {
mo.Write(i % 127);
}
} catch (...) {
ehandled = true;
}
UNIT_ASSERT_EQUAL(ehandled, true);
for (size_t i = 0; i < sizeof(buf); ++i) {
UNIT_ASSERT_EQUAL(buf[i], (char)(i % 127));
}
}
class TIO: public std::iostream {
public:
inline TIO(TStreamBufAdaptor* buf)
: std::iostream(0)
{
std::istream::init(buf);
std::ostream::init(buf);
}
};
void TStreamsTest::TestStreamBufAdaptor() {
Stroka in("1234\r\n123456\r\n");
Stroka out;
TStringInput si(in);
TStringOutput so(out);
{
TStreamBufAdaptor strbuf(&si, 1024, &so, 1024);
TIO io(&strbuf);
std::string st;
io >> st;
UNIT_ASSERT_EQUAL(st, "1234");
io >> st;
UNIT_ASSERT_EQUAL(st, "123456");
io << "qwerty";
io.flush();
io << "123456";
}
UNIT_ASSERT_EQUAL(out, "qwerty123456");
}
class TMyStringOutput: public TOutputStream {
public:
inline TMyStringOutput(Stroka& s, size_t buflen) throw ()
: S_(s)
, BufLen_(buflen)
{
}
virtual ~TMyStringOutput() throw () {
}
virtual void DoWrite(const void* data, size_t len) {
S_.Write(data, len);
UNIT_ASSERT(len < BufLen_ || ((len % BufLen_) == 0));
}
virtual void DoWriteV(const TPart* p, size_t count) {
Stroka s;
for (size_t i = 0; i < count; ++i) {
s.append((const char*)p[i].buf, p[i].len);
}
DoWrite(~s, +s);
}
private:
TStringOutput S_;
const size_t BufLen_;
};
void TStreamsTest::TestBufferedIO() {
Stroka s;
{
const size_t buflen = 7;
TBuffered<TMyStringOutput> bo(buflen, s, buflen);
for (size_t i = 0; i < 1000; ++i) {
Stroka str(" ");
str += ToString(i % 10);
bo.Write(~str, +str);
}
bo.Finish();
}
UNIT_ASSERT_EQUAL(+s, 2000);
{
const size_t buflen = 11;
TBuffered<TStringInput> bi(buflen, s);
for (size_t i = 0; i < 1000; ++i) {
Stroka str(" ");
str += ToString(i % 10);
char buf[3];
UNIT_ASSERT_EQUAL(bi.Load(buf, 2), 2);
buf[2] = 0;
UNIT_ASSERT_EQUAL(str, buf);
}
}
s.clear();
{
const size_t buflen = 13;
TBuffered<TMyStringOutput> bo(buflen, s, buflen);
Stroka f = "1234567890";
for (size_t i = 0; i < 10; ++i) {
f += f;
}
for (size_t i = 0; i < 1000; ++i) {
bo.Write(~f, i);
}
bo.Finish();
}
}
void TStreamsTest::TestBufferStream() {
TBufferStream stream;
Stroka s = "test";
stream.Write(~s, +s);
char buf[5];
size_t readed = stream.Read(buf, 4);
UNIT_ASSERT_EQUAL(4, readed);
UNIT_ASSERT_EQUAL(0, strncmp(~s, buf, 4));
stream.Write(~s, +s);
readed = stream.Read(buf, 2);
UNIT_ASSERT_EQUAL(2, readed);
UNIT_ASSERT_EQUAL(0, strncmp("te", buf, 2));
readed = stream.Read(buf, 2);
UNIT_ASSERT_EQUAL(2, readed);
UNIT_ASSERT_EQUAL(0, strncmp("st", buf, 2));
readed = stream.Read(buf, 2);
UNIT_ASSERT_EQUAL(0, readed);
}
struct TTestEof {
inline bool operator() (char ch) const throw () {
return ch == '\n';
}
};
void TStreamsTest::TestTokenizer() {
const Stroka parts[] = {
"qwerty",
"1234567890"
};
const size_t count = sizeof(parts) / sizeof(*parts);
Stroka s;
for (size_t i = 0; i < count; ++i) {
s += parts[i];
s += "\n";
}
TMemoryInput mi(~s, +s);
typedef TStreamTokenizer<TTestEof> TTokenizer;
TTokenizer tokenizer(&mi);
size_t cur = 0;
for (TTokenizer::TIterator it = tokenizer.Begin(); it != tokenizer.End(); ++it) {
UNIT_ASSERT(cur < count);
UNIT_ASSERT_EQUAL(Stroka(it->Data(), it->Length()), parts[cur]);
++cur;
}
}
#if defined (_MSC_VER)
# pragma warning(disable:4309) /*truncation of constant value*/
#endif
namespace {
const char Text[] = {
// UTF8 encoded "one \ntwo\r\nthree\n\tfour\nfive\n" in russian and ...
0xD1, 0x80, 0xD0, 0xB0, 0xD0, 0xB7, ' ', '\n',
0xD0, 0xB4, 0xD0, 0xB2, 0xD0, 0xB0, '\r', '\n',
0xD1, 0x82, 0xD1, 0x80, 0xD0, 0xB8, '\n',
'\t', 0xD1, 0x87, 0xD0, 0xB5, 0xD1, 0x82, 0xD1, 0x8B, 0xD1, 0x80, 0xD0, 0xB5, '\n',
0xD0, 0xBF, 0xD1, 0x8F, 0xD1, 0x82, 0xD1, 0x8C, '\n',
// ... additional test cases
'\r', '\n',
'\n', '\r', // this char goes to the front of the next string
'o', 'n', 'e', ' ', 't', 'w', 'o', '\n',
'1', '2', '3', '\r', '\n',
'\t', '\r', ' ', 0 };
const char Expected[][20] = {
// UTF8 encoded "one ", "two", "three", "\tfour", "five" in russian and ...
{ 0xD1, 0x80, 0xD0, 0xB0, 0xD0, 0xB7, 0x20, 0x00 },
{ 0xD0, 0xB4, 0xD0, 0xB2, 0xD0, 0xB0, 0x00 },
{ 0xD1, 0x82, 0xD1, 0x80, 0xD0, 0xB8, 0x00 },
{ 0x09, 0xD1, 0x87, 0xD0, 0xB5, 0xD1, 0x82, 0xD1, 0x8B, 0xD1, 0x80, 0xD0, 0xB5, 0x00 },
{ 0xD0, 0xBF, 0xD1, 0x8F, 0xD1, 0x82, 0xD1, 0x8C, 0x00 },
// ... additional test cases
{ 0x00 },
{ 0x00 },
{ '\r', 'o', 'n', 'e', ' ', 't', 'w', 'o' },
{ '1', '2', '3' },
{ '\t', '\r', ' ' } };
}
void TStreamsTest::TestWtrokaInput() {
TTempBuf buffer(sizeof(Text) * sizeof(wchar16));
wchar16* const data = (wchar16*)buffer.Data();
const Stroka s(Text);
TStringInput is(s);
Wtroka w;
size_t i = 0;
while (is.ReadLine(w)) {
UNIT_ASSERT(i < sizeof(Expected) / sizeof(Expected[0]));
size_t read = 0, written = 0;
RecodeToUnicode(CODES_UTF8, Expected[i], data, strlen(Expected[i]), sizeof(Text) - 1, read, written);
data[written] = 0;
UNIT_ASSERT(w == data);
++i;
}
}
void TStreamsTest::TestWtrokaOutput() {
Stroka s;
TStringOutput os(s);
const size_t n = sizeof(Expected) / sizeof(Expected[0]);
for (size_t i = 0; i < n; ++i) {
const size_t len = strlen(Expected[i]);
Wtroka w((int)len);
size_t read = 0, written = 0;
RecodeToUnicode(CODES_UTF8, Expected[i], w.begin(), len, len, read, written);
w.remove(written);
os << w;
if (i == 1 || i == 5 || i == 8)
os << '\r';
if (i < n - 1)
os << '\n';
}
UNIT_ASSERT(s == Text);
}
| 25.208738 | 128 | 0.547083 |
f18e4b27b552d210e912eaf35ef4a0d5efb20573 | 1,030 | cpp | C++ | Source/GUI/Submenus/HUD.cpp | HatchesPls/GrandTheftAutoV-Cheat | f06011362a0a8297439b260a670f5091118ef5de | [
"curl",
"MIT"
] | 31 | 2021-07-13T21:24:58.000Z | 2022-03-31T13:04:38.000Z | Source/GUI/Submenus/HUD.cpp | HatchesPls/GrandTheftAutoV-Cheat | f06011362a0a8297439b260a670f5091118ef5de | [
"curl",
"MIT"
] | 12 | 2021-07-28T16:53:58.000Z | 2022-03-31T22:51:03.000Z | Source/GUI/Submenus/HUD.cpp | HowYouDoinMate/GrandTheftAutoV-Cheat | 1a345749fc676b7bf2c5cd4df63ed6c9b80ff377 | [
"curl",
"MIT"
] | 12 | 2020-08-16T15:57:52.000Z | 2021-06-23T13:08:53.000Z | #include "../Header/Cheat Functions/FiberMain.h"
using namespace Cheat;
int HUDColorRed, HUDColorGreen, HUDColorBlue, HUDColorAlpha;
void GUI::Submenus::HUD()
{
GUI::Title("HUD");
GUI::Toggle("Disable HUD", CheatFeatures::DisableHUDBool, "Prevents all HUD elements from being visible");
GUI::Toggle("Hide Minimap", CheatFeatures::HideMinimapBool, "Not needed when Disable HUD is enabled");
GUI::Break("Color", SELECTABLE_CENTER_TEXT);
GUI::Int("Red", HUDColorRed, 0, 255, 1, "", SELECTABLE_DISABLE_SAVE | SELECTABLE_RETURN_VALUE_CHANGE);
GUI::Int("Green", HUDColorGreen, 0, 255, 1, "", SELECTABLE_DISABLE_SAVE | SELECTABLE_RETURN_VALUE_CHANGE);
GUI::Int("Blue", HUDColorBlue, 0, 255, 1, "", SELECTABLE_DISABLE_SAVE | SELECTABLE_RETURN_VALUE_CHANGE);
GUI::Int("Alpha", HUDColorAlpha, 0, 255, 1, "", SELECTABLE_DISABLE_SAVE | SELECTABLE_RETURN_VALUE_CHANGE);
if (GUI::Option("Change", ""))
{
for (int i = 0; i <= 223; i++)
{
UI::_SET_HUD_COLOUR(i, HUDColorRed, HUDColorGreen, HUDColorBlue, HUDColorAlpha);
}
}
} | 46.818182 | 107 | 0.73301 |
f1939d344d0611eefaf236413473731281bb235f | 15,136 | cpp | C++ | DotGenerator2.cpp | PollyP/TraceVizPintool | 0c76e660834c6b77ffe944169d4afbd04e16ed0a | [
"MIT"
] | 6 | 2020-04-25T12:45:52.000Z | 2021-12-15T01:24:54.000Z | DotGenerator2.cpp | PollyP/TraceVizPintool | 0c76e660834c6b77ffe944169d4afbd04e16ed0a | [
"MIT"
] | 5 | 2020-04-17T21:03:30.000Z | 2020-04-24T20:17:28.000Z | DotGenerator2.cpp | PollyP/TraceVizPintool | 0c76e660834c6b77ffe944169d4afbd04e16ed0a | [
"MIT"
] | null | null | null | /***
Copyright 2020 P.S.Powledge
Permission is hereby granted, free of charge, to any person obtaining a copy
of this softwareand associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and /or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright noticeand this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***/
#include <algorithm>
#include <assert.h>
#include <fstream>
#include <sstream>
#include <map>
#include <set>
#include <string>
#include <vector>
#include "DotGenerator2.h"
using namespace std;
extern ofstream logfile;
extern string get_filename(string pathplusfname);
extern string truncate_string(string inputs, int new_length);;
extern void find_and_replace_all(string& data, string replacee, string replacer);
/**********************************************************************************************************************************
* *
* Section2Color: map section indexes to colors *
* *
/*********************************************************************************************************************************/
Section2ColorPtr Section2Color::inst = NULL;
const string Section2Color::colors[] = { "yellow", "pink", "lightblue", "orange", "green", "tan", };
Section2Color *Section2Color::getInstance()
{
if (Section2Color::inst == NULL)
{
Section2Color::inst = new Section2Color();
}
return Section2Color::inst;
}
string Section2Color::getColor(int section_idx)
{
int idx = section_idx % Section2Color::colors->length();
return Section2Color::inst->colors[idx];
}
/**********************************************************************************************************************************
* *
* NodeItem: class to hold info about nodes *
* *
/*********************************************************************************************************************************/
ostream& operator<<(ostream& os, const DotNodeItem& n)
{
os << " nodeid: " << n.nodeid << " label " << n.label << " color: " << n.color ;
return os;
}
/**********************************************************************************************************************************
* *
* NodeManager: class to manage nodes *
* *
/*********************************************************************************************************************************/
DotNodeManager::DotNodeManager()
{
this->node_counter = 0;
}
DotNodeManager::~DotNodeManager()
{
this->node_counter = 0;
// clean up the heap from all the internally-created (ie placeholder) nodes
// note: the class that added nodes via addNode() is responsible for reclaiming that heap.
for (auto n : this->placeholder_nodes)
{
delete n;
}
}
vector<int> DotNodeManager::getTids()
{
vector<int> ret;
for (map<int, string>::iterator it = this->tidlist.begin(); it != this->tidlist.end(); ++it)
{
ret.push_back(it->first);
}
sort(ret.begin(), ret.end());
return ret;
}
void DotNodeManager::addNode(DotNodeItemPtr n)
{
this->tidlist[n->tid] = "";
this->node_map[this->node_counter] = n;
this->node_counter++;
}
vector<DotNodeItemPtr> DotNodeManager::getNodes()
{
vector<DotNodeItemPtr> ret;
for (pair<int, DotNodeItemPtr> element : this->node_map)
{
DotNodeItemPtr n = element.second;
ret.push_back(n);
}
return ret;
}
vector<DotNodeItemPtr> DotNodeManager::getNodesForTid(int tid)
{
vector<DotNodeItemPtr> ret;
for (pair<int, DotNodeItemPtr> element : this->node_map)
{
int node_idx = element.first;
DotNodeItemPtr n = element.second;
// does this node come from this tid?
if (n->tid != tid)
{
// no, generate a placeholder node first
n = this->getPlaceholderNode(tid, node_idx);
}
ret.push_back(n);
}
return ret;
}
vector<pair<DotNodeItemPtr,DotNodeItemPtr>> DotNodeManager::getNodesThatJumpTids()
{
vector<pair<DotNodeItemPtr,DotNodeItemPtr>> ret;
for (pair<int, DotNodeItemPtr> kv : this->node_map)
{
int i = kv.first;
DotNodeItemPtr n = kv.second;
if (this->node_map.find(i + 1) != this->node_map.end())
{
DotNodeItemPtr nextnode = this->node_map[i + 1];
if (n->tid != nextnode->tid)
{
pair<DotNodeItemPtr, DotNodeItemPtr> apair = { n, nextnode };
ret.push_back(apair);
}
}
}
return ret;
}
DotNodeItemPtr DotNodeManager::getPlaceholderNode(int tid, int node_idx)
{
// build unique node id
stringstream ss;
ss << "cluster_" << tid << "_node_" << node_idx;
// create the nodeitem
// heap management is in class dtor
DotNodeItemPtr ret = new DotNodeItem(tid, ss.str(), "placeholder", "red");
ret->isplaceholder = true;
// add the placeholder node on a list so we can reclaim the heap
this->placeholder_nodes.push_back(ret);
return ret;
}
ostream& operator<<(ostream& os, DotNodeManager& nm)
{
os << "nm state:\n";
os << "\tnode counter: " << nm.node_counter << "\n";
vector<int> tids = nm.getTids();
os << "\ttid count = " << tids.size() << "\n";
for (auto t : tids)
{
os << "\ttid = " << t << "\n";
vector<DotNodeItemPtr> nodes = nm.getNodesForTid(t);
for (auto n : nodes)
{
os << "\t\t" << *n << "\n";
}
}
return os;
}
/**********************************************************************************************************************************
* *
* DotGenerator2: class to generate the dot file *
* *
/*********************************************************************************************************************************/
DotGenerator::DotGenerator(const char * fname, const char *comment)
{
this->fname = fname;
this->file_output.open(this->fname.c_str(), ios::out | ios::trunc);
if (this->file_output.is_open() != true)
{
logfile << "could not open " << fname << endl;
return;
}
this->node_manager = new DotNodeManager();
assert(this->node_manager != NULL);
this->sections2colors = Section2Color::getInstance();
this->file_output << "digraph {" << endl;
this->file_output << "\t# " << comment << endl;
this->file_output << "\tlabel=\"" << comment << "\";" << endl;
this->file_output << "\tcompound=true;" << endl;
this->file_output << "\tedge[style=\"invis\"];" << endl;
this->file_output << "\tnode [shape=rectangle, style=filled, height=1.5, width=6.0, fixedsize=true, margin=.25]; # units=inches" << endl;
this->file_output << endl;
}
DotGenerator::~DotGenerator()
{
// finish writing output file
this->closeOutputFile();
// clean up heap'ed memory
vector<DotNodeItemPtr> nodes = this->node_manager->getNodes();
for (auto n : nodes)
{
delete n;
}
// clean up heap'ed memory, part two
delete this->node_manager;
}
void DotGenerator::addNewImage(int tid, string imgname, int secidx, ADDRINT start_address )
{
// build a unique node id
string node_id = this->buildNodeId(tid);
// build a label for the node
string filename = get_filename(imgname);
find_and_replace_all(imgname, "\\", "\\\\");
string trunc_imgname = truncate_string(imgname, max_imgname_len);
stringstream ss2;
ss2 << "image load: mapped " << filename << " to " << hex << showbase << start_address << "\\lfull path: " << trunc_imgname << "\\l";
string label = ss2.str();
// turn this into a node and add it to our nodemanager
DotNodeItemPtr n = new DotNodeItem(tid, node_id, label, "lightgray");
assert(n != NULL);
this->addImageLoadNode(n);
}
void DotGenerator::addNewLibCall(int tid, string symbol, string imgname, int secidx, ADDRINT addr, string calling_address, string details)
{
// if there's a lot of text, make the node larger
bool needsLargeNode = false;
if (details != "")
{
needsLargeNode = true;
}
// build a unique node id
string node_id = this->buildNodeId(tid);
// build a label for the node
string filename = get_filename(imgname);
find_and_replace_all(imgname, "\\", "\\\\");
string trunc_imgname = truncate_string(imgname, max_imgname_len);
string trunc_symbol = truncate_string(symbol, max_symbol_len);
stringstream ss2;
ss2 << "library call from " << calling_address << " \\l" << trunc_symbol << " (" << hex << showbase << addr << ", " << filename << ") \\l" << "full path: " << trunc_imgname << " \\l";
ss2 << details;
string label = ss2.str();
// map the section idx to a background color
string color = this->sections2colors->getColor(secidx);
// turn this into a node and add it to our nodemanager
DotNodeItemPtr n = new DotNodeItem(tid, node_id, label, color);
assert(n != NULL);
if (needsLargeNode)
{
this->addLargeLibCallNode(n);
}
else
{
this->addLibCallNode(n);
}
}
string DotGenerator::formatDetailsLines(vector<string> input_strings)
{
stringstream ss;
for (auto is : input_strings)
{
ss << is << "\\l";
}
return ss.str();
}
void DotGenerator::closeOutputFile()
{
if (this->file_output.is_open())
{
this->buildClusters();
this->file_output << "}" << endl;
this->file_output.close();
}
}
void DotGenerator::buildClusters()
{
// for every thread we saw ...
vector<int> tids = this->node_manager->getTids();
for (const auto tid : tids)
{
// get the nodes associated with that thread
vector<DotNodeItemPtr> nodes = this->node_manager->getNodesForTid(tid);
if (nodes.size() == 0)
{
continue;
}
// turn the nodes into a cluster
// step 1. build cluster header
stringstream ss;
ss << "cluster_" << tid;
string cluster_id = ss.str();
this->file_output << endl;
this->file_output << "\tsubgraph " << cluster_id << " {" << endl;
this->file_output << "\t\t# " << cluster_id << endl;
this->file_output << "\t\tlabel=\"thread #" << tid << "\"" << endl;
// step 2. xdot doesn't give you a way to line up the nodes
// as a grid, so I create placeholder nodes to get things to
// line up. yes, it's a horrible hack. :( anyway, i need to first
// define the placeholder nodes in the cluster.
this->file_output << "\t\t# placeholder nodes" << endl;
for (int i = 0; i < (int)nodes.size(); i++)
{
if (nodes[i]->isplaceholder)
{
this->file_output << "\t\tnode [label=\"" << nodes[i]->label << "\", style=invis, fillcolor=\"" << nodes[i]->color << "\", height=1.25] " << nodes[i]->nodeid << ";" << endl;
}
}
// step 3. link up the nodes in this cluster.
stringstream ss2;
ss2 << "\t\t" << nodes.front()->nodeid;
for ( int i = 1 ; i < (int)nodes.size() ; i++ )
{
ss2 << " -> " << nodes[i]->nodeid << " ";
}
// step 4. build cluster tail
this->file_output << ss2.str() << ";" << endl;
this->file_output << "\t} # subgraph for " << cluster_id << endl;
}
// is the application multithreaded? If so make the various threads line us nicely in the output
// by building links for each node in thread x that is followed by a node in thread y
vector<pair<DotNodeItemPtr,DotNodeItemPtr>> jumppairs = this->node_manager->getNodesThatJumpTids();
if ( jumppairs.size() > 0 )
{
this->file_output << "\n\n\t# thread jumps" << endl;
for (const auto jumppair : jumppairs)
{
// xdot builds really strange diagrams when you have descendent clusters linking back to ancestor clusters. leave them out.
//if (true)
if (jumppair.first->nodeid < jumppair.second->nodeid)
{
this->file_output << "\t" << jumppair.first->nodeid << " -> " << jumppair.second->nodeid << ";" << endl;
}
}
}
}
// build a unique node id
string DotGenerator::buildNodeId(int tid)
{
stringstream ss;
ss << "cluster_" << tid << "_node_" << this->node_manager->node_counter;
return ss.str();
}
// write this node to file output and add it to the node manager for later clustering/linking.
void DotGenerator::addImageLoadNode(DotNodeItemPtr n)
{
this->file_output << "\tnode [label=\"" << n->label << "\", style=\"filled, rounded\", fillcolor=\"" << n->color << "\", height=0.75] " << n->nodeid << ";" << endl;
this->node_manager->addNode(n);
}
// write this node to file output and add it to the node manager for later clustering/linking.
void DotGenerator::addLargeLibCallNode(DotNodeItemPtr n)
{
this->file_output << "\tnode [label=\"" << n->label << "\", style=filled, fillcolor=\"" << n->color << "\", height=1.25] " << n->nodeid << ";" << endl;
this->node_manager->addNode(n);
}
// write this node to file output and add it to the node manager for later clustering/linking.
void DotGenerator::addLibCallNode(DotNodeItemPtr n)
{
this->file_output << "\tnode [label=\"" << n->label << "\", style=filled, fillcolor=\"" << n->color << "\", height=1.0] " << n->nodeid << ";" << endl;
this->node_manager->addNode(n);
}
// dump the state to an ostream
inline ostream& operator<<(ostream& os, const DotGenerator& dg)
{
os << "dg state:\n";
os << "\tfname: " << dg.fname;
os << "\tnm: " << *(dg.node_manager);
return os;
}
| 34.636156 | 185 | 0.544662 |
f1968e5e82d78cd2ab6a7204e17c7b55d9f51753 | 202 | cpp | C++ | ue4_c++/1/bp2/bp2.cpp | mohamadem60mdem/a5 | c6f53364cc148862129acd1c6334d104f5e6bef3 | [
"MIT"
] | null | null | null | ue4_c++/1/bp2/bp2.cpp | mohamadem60mdem/a5 | c6f53364cc148862129acd1c6334d104f5e6bef3 | [
"MIT"
] | null | null | null | ue4_c++/1/bp2/bp2.cpp | mohamadem60mdem/a5 | c6f53364cc148862129acd1c6334d104f5e6bef3 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "bp2.h"
#include "Modules/ModuleManager.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, bp2, "bp2" );
| 28.857143 | 78 | 0.787129 |
1af1a096b969ffab648d5b3eb8c9befc9bc2734c | 4,255 | cpp | C++ | graph.cpp | SelYui/OptimizationStochasticSystems | 6fc7467156268f1df533b0cebee41d59dede82b3 | [
"MIT"
] | null | null | null | graph.cpp | SelYui/OptimizationStochasticSystems | 6fc7467156268f1df533b0cebee41d59dede82b3 | [
"MIT"
] | null | null | null | graph.cpp | SelYui/OptimizationStochasticSystems | 6fc7467156268f1df533b0cebee41d59dede82b3 | [
"MIT"
] | null | null | null | #include "graph.h"
#include "ui_graph.h"
#include <iostream>
Graph::Graph(QWidget *parent) :
QWidget(parent),
ui(new Ui::Graph)
{
ui->setupUi(this);
// Добавляем график 1 на полотно
ui->customPlot_1->addGraph();
// Инициализируем трассировщик
tracer_1 = new QCPItemTracer(ui->customPlot_1);
// Подписываем оси координат
ui->customPlot_1->xAxis->setLabel("k");
ui->customPlot_1->yAxis->setLabel("X(k)");
// Подписываем название графика
ui->customPlot_1->plotLayout()->insertRow(0);
ui->customPlot_1->plotLayout()->addElement(0, 0, new QCPTextElement(ui->customPlot_1, "Состояние системы", QFont("Arial", 12, QFont::Bold)));
// Строим второй график
ui->customPlot_2->addGraph();
tracer_2 = new QCPItemTracer(ui->customPlot_2);
ui->customPlot_2->xAxis->setLabel("k");
ui->customPlot_2->yAxis->setLabel("e(k)");
ui->customPlot_2->plotLayout()->insertRow(0);
ui->customPlot_2->plotLayout()->addElement(0, 0, new QCPTextElement(ui->customPlot_2, "Ошибка оценивания", QFont("Arial", 12, QFont::Bold)));
// Подключаем сигналы событий мыши от полотна графика к слотам для их обработки
connect(ui->customPlot_1, &QCustomPlot::mouseMove, this, &Graph::slotMouseMove_1);
connect(ui->customPlot_2, &QCustomPlot::mouseMove, this, &Graph::slotMouseMove_2);
}
Graph::~Graph()
{
delete ui;
}
void Graph::PlotXandE(unsigned int N, double A, double B, double Deps, double Dnu, double X0, double ocX0, double D0, double mu)
{
QVector<double> e(N), X(N); // Объявляем наши векторы ошибкт и состояния системы
// Строим модель
Graph::Optimization(e, X, N, A, B, Deps, Dnu, X0, ocX0, D0, mu);
// создаём вектора для графика
QVector<double> k(X.size());
for (int i=0; i < X.size(); i++)
{
k[i] = i;
}
// Для графика 1
ui->customPlot_1->graph(0)->setData(k,X); // Устанавливаем координаты точек графика
tracer_1->setGraph(ui->customPlot_1->graph(0)); // Трассировщик будет работать с графиком
// Устанавливаем максимальные и минимальные значения координат
ui->customPlot_1->xAxis->setRange(0,0);
ui->customPlot_1->yAxis->setRange(0,0);
// Позволяем увеличивать и передвигать график
ui->customPlot_1->rescaleAxes();
ui->customPlot_1->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
// Отрисовываем содержимое полотна
ui->customPlot_1->replot();
ui->customPlot_2->graph(0)->setData(k, e);
tracer_2->setGraph(ui->customPlot_2->graph(0)); // Трассировщик будет работать с графиком
ui->customPlot_2->xAxis->setRange(0, 0);
ui->customPlot_2->yAxis->setRange(0, 0);
ui->customPlot_2->rescaleAxes();
ui->customPlot_2->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
// отрисовка графика
ui->customPlot_2->replot();
this->show();
}
void Graph::slotMouseMove_1(QMouseEvent *event)
{
// Определяем координату X на графике, где был произведён клик мышью
double coordX = ui->customPlot_1->xAxis->pixelToCoord(event->pos().x());
// По координате X клика мыши определим ближайшие координаты для трассировщика
tracer_1->setGraphKey(coordX);
tracer_1->updatePosition();
// Выводим координаты точки графика, где установился трассировщик, в lineEdit
ui->lineEdit_1->setText("k: " + QString::number(tracer_1->position->key()) +
" X(k): " + QString::number(tracer_1->position->value()));
ui->customPlot_1->replot(); // Перерисовываем содержимое полотна графика
}
void Graph::slotMouseMove_2(QMouseEvent *event)
{
// Определяем координату X на графике, где был произведён клик мышью
double coordX = ui->customPlot_2->xAxis->pixelToCoord(event->pos().x());
// По координате X клика мыши определим ближайшие координаты для трассировщика
tracer_2->setGraphKey(coordX);
tracer_2->updatePosition();
// Выводим координаты точки графика, где установился трассировщик, в lineEdit
ui->lineEdit_2->setText("k: " + QString::number(tracer_2->position->key()) +
" e(k): " + QString::number(tracer_2->position->value()));
ui->customPlot_2->replot(); // Перерисовываем содержимое полотна графика
}
| 39.398148 | 145 | 0.681551 |
1af940e1d38d3161c5216d6fae8d230388d44cce | 18,618 | cpp | C++ | hi_snex/unit_test/snex_jit_IndexTest.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | hi_snex/unit_test/snex_jit_IndexTest.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | hi_snex/unit_test/snex_jit_IndexTest.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | /* ===========================================================================
*
* This file is part of HISE.
* Copyright 2016 Christoph Hart
*
* HISE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option any later version.
*
* HISE 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HISE. If not, see <http://www.gnu.org/licenses/>.
*
* Commercial licences for using HISE in an closed source project are
* available on request. Please visit the project's website to get more
* information about commercial licencing:
*
* http://www.hartinstruments.net/hise/
*
* HISE is based on the JUCE library,
* which also must be licenced for commercial applications:
*
* http://www.juce.com
*
* ===========================================================================
*/
namespace snex {
namespace jit {
using namespace juce;
#define TEST_ALL_INDEXES 1
template <typename IndexType> struct IndexTester
{
using Type = typename IndexType::Type;
static constexpr int Limit = IndexType::LogicType::getUpperLimit();
static constexpr bool isLoopTest()
{
return std::is_same<index::looped_logic<Limit>, typename IndexType::LogicType>();
}
IndexTester(UnitTest* test_, StringArray opt, int dynamicSize = 0) :
test(*test_),
indexName(IndexType::toString()),
optimisations(opt),
ArraySize(Limit != 0 ? Limit : dynamicSize)
{
test.beginTest("Testing " + indexName);
runTest();
}
private:
const int ArraySize;
const String indexName;
void runTest()
{
testLoopRange(0.0, 0.0);
testLoopRange(0.0, 1.0);
testLoopRange(0.5, 1.0);
testLoopRange(0.3, 0.6);
#if TEST_ALL_INDEXES
testIncrementors(FunctionClass::SpecialSymbols::IncOverload);
testIncrementors(FunctionClass::SpecialSymbols::DecOverload);
testIncrementors(FunctionClass::SpecialSymbols::PostIncOverload);
testIncrementors(FunctionClass::SpecialSymbols::PostDecOverload);
testAssignAndCast();
testFloatAlphaAndIndex();
testSpanAccess();
testDynAccess();
#endif
testInterpolators();
}
Range<int> getLoopRange(double nStart, double nEnd)
{
auto s = roundToInt(jlimit(0.0, 1.0, nStart) * (double)Limit);
auto e = roundToInt(jlimit(0.0, 1.0, nEnd) * (double)Limit);
return Range<int>(s, e);
}
String getLoopRangeCode(double start, double end)
{
auto l = getLoopRange(start, end);
String c;
c << ".setLoopRange(" << l.getStart() << ", " << l.getEnd() << ");";
return c;
}
void testLoopRange(double normalisedStart, double normalisedEnd)
{
if constexpr (isLoopTest() && IndexType::LogicType::hasBoundCheck())
{
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
span<Type, Limit> data;
String spanCode;
initialiseSpan(spanCode, data);
c << indexName << " i;";
c << spanCode;
c << "T test(T input)";
{
cppgen::StatementBlock sb(c);
c << "i" << getLoopRangeCode(normalisedStart, normalisedEnd);
c << "i = input;";
c << "return data[i];";
}
test.logMessage("Testing loop range " + indexName + getLoopRangeCode(normalisedStart, normalisedEnd));
c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](Type testValue)
{
IndexType i;
auto lr = getLoopRange(normalisedStart, normalisedEnd);
i.setLoopRange(lr.getStart(), lr.getEnd());
i = testValue;
auto expected = data[i];
auto actual = obj["test"].template call<Type>(testValue);
String message = indexName;
message << " with value " << String(testValue);
test.expectWithinAbsoluteError(actual, expected, Type(0.0001), message);
};
// Test List =======================================================
testWithValue(0.5);
#if SNEX_WRAP_ALL_NEGATIVE_INDEXES
testWithValue(-1.5);
#endif
testWithValue(20.0);
testWithValue(-1);
testWithValue(Limit * 0.99);
testWithValue(Limit * 1.2);
testWithValue(Limit * 141.2);
testWithValue(Limit * 8141.92);
testWithValue(0.3);
testWithValue(8.0);
testWithValue(Limit / 3);
}
}
void testInterpolators()
{
if constexpr (!IndexType::canReturnReference() && IndexType::LogicType::hasBoundCheck())
{
// Test Code ===================================================
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
span<Type, Limit> data;
String spanCode;
initialiseSpan(spanCode, data);
c << indexName + " i;";
c << spanCode;
c << "T test(T input)";
{
cppgen::StatementBlock sb(c);
c << "i = input;";
c << "i.setLoopRange(0, 0);";
c << "return data[i];";
}
test.logMessage("Testing interpolator " + indexName);
c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](Type testValue)
{
IndexType i;
i = testValue;
auto expected = data[i];
auto actual = obj["test"].template call<Type>(testValue);
String message = indexName;
message << " with value " << String(testValue);
test.expectWithinAbsoluteError(actual, expected, Type(0.0001), message);
};
// Test List =======================================================
testWithValue(0.5);
#if SNEX_WRAP_ALL_NEGATIVE_INDEXES
testWithValue(-1.5);
#endif
testWithValue(20.0);
testWithValue(Limit * 0.99);
testWithValue(Limit * 1.2);
testWithValue(0.3);
testWithValue(8.0);
testWithValue(Limit / 3);
}
}
void testSpanAccess()
{
if constexpr (Limit != 0 && !isInterpolator())
{
// Test Code ===================================================
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
span<int, Limit> data;
String spanCode;
initialiseSpan(spanCode, data);
c << spanCode;
c << indexName + " i;";
c << "int test(T input)";
{
cppgen::StatementBlock sb(c);
c.addWithSemicolon("i = input;");
c.addWithSemicolon("return data[i];");
}
c << "int test2(T input)";
{
cppgen::StatementBlock sb(c);
c << "i = input;";
c << "data[i] = (T)50;";
c << "return data[i];";
}
test.logMessage("Testing " + indexName + " span[]");
c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](Type testValue)
{
if (IndexType::LogicType::hasBoundCheck())
{
IndexType i;
i = testValue;
auto expectedValue = data[i];
auto actualValue = obj["test"].template call<int>(testValue);
String m = indexName;
m << "::operator[]";
m << " with value " << String(testValue);
test.expectEquals(actualValue, expectedValue, m);
data[i] = Type(50);
auto e2 = data[i];
auto a2 = obj["test2"].template call<int>(testValue);
m << "(write access)";
test.expectEquals(e2, a2, m);
}
else
{
test.logMessage("skip [] access for unsafe index");
}
};
// Test List =======================================================
if (std::is_floating_point<Type>())
{
testWithValue(0.5);
testWithValue(Limit + 0.5);
testWithValue(Limit / 3.f);
testWithValue(-0.5 * Limit);
}
else
{
testWithValue(80);
testWithValue(Limit);
testWithValue(Limit - 1);
testWithValue(-1);
testWithValue(0);
testWithValue(1);
testWithValue(Limit + 1);
testWithValue(-Limit + 1);
}
}
}
void testDynAccess()
{
if constexpr (!isInterpolator())
{
// Test Code ===================================================
heap<int> data;
data.setSize(ArraySize);
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
String spanCode;
initialiseSpan(spanCode, data);
dyn<int> d;
d.referTo(data);
c << spanCode;
c << "dyn<int> d;";
c << indexName + " i;";
c << "int test(XXX input)";
{
cppgen::StatementBlock sb(c);
c << "d.referTo(data);";
c << "i = input;";
c << "return d[i];";
}
test.logMessage("Testing " + indexName + " dyn[]");
c.replaceWildcard("XXX", Types::Helpers::getTypeNameFromTypeId<Type>());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](Type testValue)
{
if (IndexType::LogicType::hasBoundCheck())
{
IndexType i;
i = testValue;
auto expectedValue = d[i];
auto actualValue = obj["test"].template call<int>(testValue);
String m = indexName;
m << "::operator[]";
m << "(dyn) with value " << String(testValue);
test.expectEquals(actualValue, expectedValue, m);
}
else
{
test.logMessage("skip [] access for unsafe index");
}
};
// Test List =======================================================
if (std::is_floating_point<Type>())
{
testWithValue(0.5);
testWithValue(Limit + 0.5);
testWithValue(Limit / 3.f);
#if SNEX_WRAP_ALL_NEGATIVE_INDEXES
testWithValue(-12.215 * Limit);
#endif
}
else
{
testWithValue(80);
testWithValue(Limit);
testWithValue(Limit - 1);
testWithValue(-1);
testWithValue(0);
testWithValue(1);
testWithValue(Limit + 1);
testWithValue(-Limit + 1);
}
}
}
template <typename Container> void initialiseSpan(String& asCode, Container& data)
{
auto elementType = Types::Helpers::getTypeFromTypeId<typename Container::DataType>();
asCode << "span<" << Types::Helpers::getTypeName(elementType) << ", " << ArraySize << "> data = { ";
for (int i = 0; i < ArraySize; i++)
{
asCode << Types::Helpers::getCppValueString(var(i), elementType) << ", ";
data[i] = (typename Container::DataType)i;
}
asCode = asCode.upToLastOccurrenceOf(", ", false, false);
asCode << " };";
}
static constexpr bool isInterpolator()
{
return !IndexType::canReturnReference();
}
static constexpr bool hasDynamicBounds()
{
return IndexType::LogicType::hasDynamicBounds();
}
void testFloatAlphaAndIndex()
{
if constexpr (std::is_floating_point<Type>() && !isInterpolator())
{
if constexpr (hasDynamicBounds())
{
// Test Code ===================================================
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
c << indexName + " i;";
c << "T testAlpha(T input, int limit)";
{
cppgen::StatementBlock sb(c);
c.addWithSemicolon("i = input;");
c.addWithSemicolon("return i.getAlpha(limit);");
}
c << "int testIndex(T input, int delta, int limit)";
{
cppgen::StatementBlock sb(c);
c.addWithSemicolon("i = input;");
c.addWithSemicolon("return i.getIndex(limit, delta);");
}
test.logMessage("Testing " + indexName + "::getAlpha");
c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](Type testValue, int deltaValue, int limit)
{
IndexType i;
i = testValue;
auto expectedAlpha = i.getAlpha(limit);
auto actualAlpha = obj["testAlpha"].template call<Type>(testValue, limit);
String am = indexName;
am << "::getAlpha()";
am << " with value " << String(testValue);
test.expectWithinAbsoluteError(actualAlpha, expectedAlpha, Type(0.00001), am);
auto expectedIndex = i.getIndex(limit, deltaValue);
auto actualIndex = obj["testIndex"].template call<int>(testValue, deltaValue, limit);
String im = indexName;
im << "::getIndex()";
im << " with value " << String(testValue) << " and delta " << String(deltaValue);
test.expectEquals(actualIndex, expectedIndex, im);
};
// Test List =======================================================
testWithValue(0.51, 0, 48);
testWithValue(12.3, 0, 64);
testWithValue(-0.52, -1, 91);
testWithValue(Limit - 0.44, 2, 10);
testWithValue(Limit + 25.2, 1, 16);
testWithValue(Limit / 0.325 - 1, 9, 1);
testWithValue(Limit * 9.029, 4, 2);
testWithValue(Limit * -0.42, Limit + 2, 32);
testWithValue(324.42, -Limit + 2, 57);
}
else
{
// Test Code ===================================================
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
c << indexName + " i;";
c << "T testAlpha(T input)";
{
cppgen::StatementBlock sb(c);
c.addWithSemicolon("i = input;");
c.addWithSemicolon("return i.getAlpha(0);");
}
c << "int testIndex(T input, int delta)";
{
cppgen::StatementBlock sb(c);
c.addWithSemicolon("i = input;");
c.addWithSemicolon("return i.getIndex(0, delta);");
}
test.logMessage("Testing " + indexName + "::getAlpha");
c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](Type testValue, int deltaValue)
{
IndexType i;
i = testValue;
auto expectedAlpha = i.getAlpha(0);
auto actualAlpha = obj["testAlpha"].template call<Type>(testValue);
String am = indexName;
am << "::getAlpha()";
am << " with value " << String(testValue);
test.expectWithinAbsoluteError(actualAlpha, expectedAlpha, Type(0.00001), am);
auto expectedIndex = i.getIndex(0, deltaValue);
auto actualIndex = obj["testIndex"].template call<int>(testValue, deltaValue);
String im = indexName;
im << "::getIndex()";
im << " with value " << String(testValue) << " and delta " << String(deltaValue);
test.expectEquals(actualIndex, expectedIndex, im);
};
// Test List =======================================================
testWithValue(0.51, 0);
testWithValue(12.3, 0);
testWithValue(-0.52, -1);
testWithValue(Limit - 0.44, 2);
testWithValue(Limit + 25.2, 1);
testWithValue(Limit / 0.325 - 1, 9);
testWithValue(Limit * 9.029, 4);
testWithValue(Limit * 0.42, Limit + 2);
testWithValue(324.42, -Limit + 2);
}
}
}
void testIncrementors(FunctionClass::SpecialSymbols incType)
{
if constexpr (std::is_integral<Type>() && !IndexType::LogicType::hasDynamicBounds())
{
// Test Code ===================================================
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
c << indexName + " i;";
c << "int test(int input)";
String op;
{
cppgen::StatementBlock sb(c);
c.addWithSemicolon("i = input");
switch (incType)
{
case FunctionClass::IncOverload: op = "++i;"; break;
case FunctionClass::PostIncOverload: op = "i++;"; break;
case FunctionClass::DecOverload: op = "--i;"; break;
case FunctionClass::PostDecOverload: op = "i--;"; break;
default: op = ""; break;
}
c.addWithSemicolon("return (int)" + op);
}
test.logMessage("Testing " + indexName + "::" + FunctionClass::getSpecialSymbol({}, incType).toString());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](int testValue)
{
IndexType i;
i = testValue;
int expected;
switch (incType)
{
case FunctionClass::IncOverload: expected = (int)++i; break;
case FunctionClass::PostIncOverload: expected = (int)i++; break;
case FunctionClass::DecOverload: expected = (int)--i; break;
case FunctionClass::PostDecOverload: expected = (int)i--; break;
default: expected = 0; break;
}
auto actual = obj["test"].template call<int>(testValue);
String message = indexName;
message << ": " << op;
message << " with value " << String(testValue);
test.expectEquals(actual, expected, message);
};
// Test List =======================================================
testWithValue(0);
testWithValue(-1);
testWithValue(Limit - 1);
testWithValue(Limit + 1);
testWithValue(Limit);
testWithValue(Limit * 2);
testWithValue(-Limit);
testWithValue(Limit / 3);
}
}
void testAssignAndCast()
{
if constexpr (Limit != 0)
{
test.logMessage("Testing assignment and type cast ");
// Test Code ===================================================
cppgen::Base c(cppgen::Base::OutputType::AddTabs);
c << indexName + " i;";
c << "T test(T input)";
{
cppgen::StatementBlock sb(c);
c.addWithSemicolon("i = input");
c.addWithSemicolon("return (T)i");
}
c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>());
auto obj = compile(c.toString());
// Test Routine ==============================================
auto testWithValue = [&](Type testValue)
{
IndexType i;
i = testValue;
auto expected = (Type)i;
auto actual = obj["test"].template call<Type>(testValue);
String message = indexName;
message << " with value " << String(testValue);
test.expectWithinAbsoluteError(actual, expected, Type(0.00001), message);
};
// Test List =======================================================
if constexpr (std::is_floating_point<Type>())
{
testWithValue(Type(Limit - 0.4));
testWithValue(Type(Limit + 0.1));
testWithValue(Type(Limit + 2.4));
testWithValue(Type(-0.2));
testWithValue(Type(-80.2));
}
else
{
testWithValue(Type(0));
testWithValue(Type(Limit - 1));
testWithValue(Type(Limit));
testWithValue(Type(Limit + 1));
testWithValue(Type(-1));
testWithValue(Type(-Limit - 2));
testWithValue(Type(Limit * 32 + 9));
}
}
}
JitObject compile(const String& code)
{
for (auto& o : optimisations)
s.addOptimization(o);
Compiler compiler(s);
SnexObjectDatabase::registerObjects(compiler, 2);
auto obj = compiler.compileJitObject(code);
test.expect(compiler.getCompileResult().wasOk(), compiler.getCompileResult().getErrorMessage());
return obj;
}
GlobalScope s;
UnitTest& test;
StringArray optimisations;
};
}
}
| 25.786704 | 108 | 0.58422 |
1afcabee2775407f5e2b23d38e2ba2e62705fa63 | 1,013 | hh | C++ | include/distro/semver.hh | mbits-libs/libdistro | 350f94ba004b21c30eb9a1a345a92b94eacf6ae6 | [
"MIT"
] | null | null | null | include/distro/semver.hh | mbits-libs/libdistro | 350f94ba004b21c30eb9a1a345a92b94eacf6ae6 | [
"MIT"
] | null | null | null | include/distro/semver.hh | mbits-libs/libdistro | 350f94ba004b21c30eb9a1a345a92b94eacf6ae6 | [
"MIT"
] | null | null | null | // Copyright 2021 midnightBITS
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
#pragma once
#include <optional>
#include <string>
#include <variant>
#include <vector>
namespace distro {
class semver {
public:
class comp {
std::variant<unsigned, std::string> value;
public:
comp() = default;
comp(unsigned val) : value{val} {}
comp(std::string const& val) : value{val} {}
comp(std::string&& val) : value{std::move(val)} {}
std::string to_string() const;
bool operator<(comp const& rhs) const;
bool operator==(comp const& rhs) const;
static comp from_string(std::string_view comp);
};
unsigned major;
unsigned minor;
unsigned patch;
std::vector<comp> prerelease;
std::vector<std::string> meta;
std::string to_string() const;
bool operator<(semver const& rhs) const;
bool operator==(semver const& rhs) const;
static std::optional<semver> from_string(std::string_view view);
};
} // namespace distro
| 24.707317 | 73 | 0.687068 |
21005c808f86b2ba6c676448877ab8632e8ebfd7 | 15,570 | cpp | C++ | SPY_Translator[CPP_COM]/FindControl_Sundar/FindControl_Sundar/ControlFinder.cpp | clicksuku/SundarkpCode | b4aabf3c99258d955c6449ce6f20edba6f3fe581 | [
"Apache-2.0"
] | null | null | null | SPY_Translator[CPP_COM]/FindControl_Sundar/FindControl_Sundar/ControlFinder.cpp | clicksuku/SundarkpCode | b4aabf3c99258d955c6449ce6f20edba6f3fe581 | [
"Apache-2.0"
] | 3 | 2020-05-21T00:20:43.000Z | 2022-02-11T04:32:43.000Z | SPY_Translator[CPP_COM]/FindControl_Sundar/FindControl_Sundar/ControlFinder.cpp | clicksuku/SundarkpCode | b4aabf3c99258d955c6449ce6f20edba6f3fe581 | [
"Apache-2.0"
] | null | null | null | // SampleWinApp.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "ControlFinder.h"
#include <atlstr.h>
#define MAX_LOADSTRING 100
#define BULLSEYE_CENTER_X_OFFSET 15
#define BULLSEYE_CENTER_Y_OFFSET 18
HINSTANCE g_hInst = NULL;
BOOL g_bStartSearchWindow = FALSE;
HCURSOR g_hCursorSearchWindow = NULL;
HCURSOR g_hCursorPrevious = NULL;
HBITMAP g_hBitmapFinderToolFilled;
HBITMAP g_hBitmapFinderToolEmpty;
HWND g_hwndFoundWindow = NULL;
HPEN g_hRectanglePen = NULL;
HPEN g_hPrevPen = NULL; // Handle of the existing pen in the DC of the found window.
HBRUSH g_hPrevBrush = NULL; // Handle of the existing brush in the DC of the found window.
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
MSG msg;
long lRet = 0;
g_hInst = hInstance;
BOOL bRet = InitialiseResources();
if (bRet == FALSE)
{
UninitialiseResources();
return lRet;
}
HWND hDialog = CreateDialog
(
(HINSTANCE)g_hInst, // handle to application instance
(LPCTSTR)MAKEINTRESOURCE(IDD_SEARCH_WINDOW), // identifies dialog box template
NULL, // handle to owner window
(DLGPROC)SearchWindowDialogProc // pointer to dialog box procedure
);
ShowWindow(hDialog, SW_SHOWNORMAL);
UpdateWindow(hDialog);
while (GetMessage(&msg, (HWND)NULL, 0, 0))
{
if (!TranslateAccelerator(hDialog, NULL, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
lRet = msg.wParam;
return lRet;
}
BOOL InitialiseResources()
{
BOOL bRet = FALSE;
g_hCursorSearchWindow = LoadCursor (g_hInst, MAKEINTRESOURCE(IDC_CURSOR_SEARCH_WINDOW));
g_hRectanglePen = CreatePen (PS_SOLID, 3, RGB(0, 0, 255));
//g_hRectanglePen = CreatePen (PS_SOLID, 3, RGB(256, 0, 0));
g_hBitmapFinderToolFilled = LoadBitmap (g_hInst, MAKEINTRESOURCE(IDB_BITMAP_FINDER_FILLED));
g_hBitmapFinderToolEmpty = LoadBitmap (g_hInst, MAKEINTRESOURCE(IDB_BITMAP_FINDER_EMPTY));
if ((g_hCursorSearchWindow == NULL) || (g_hRectanglePen == NULL) || (g_hBitmapFinderToolFilled == NULL) || (g_hBitmapFinderToolEmpty == NULL))
{
return FALSE;
}
return TRUE;
}
void UninitialiseResources()
{
if (g_hRectanglePen)
{
DeleteObject (g_hRectanglePen);
g_hRectanglePen = NULL;
}
if (g_hPrevPen)
{
DeleteObject (g_hPrevPen);
g_hPrevPen = NULL;
}
if (g_hBitmapFinderToolFilled)
{
DeleteObject (g_hBitmapFinderToolFilled);
g_hBitmapFinderToolFilled = NULL;
}
if (g_hBitmapFinderToolEmpty)
{
DeleteObject (g_hBitmapFinderToolEmpty);
g_hBitmapFinderToolEmpty = NULL;
}
}
BOOL CALLBACK SearchWindowDialogProc
(
HWND hwndDlg, // handle to dialog box
UINT uMsg, // message
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
)
{
BOOL bRet = FALSE; // Default return value.
switch (uMsg)
{
case WM_INITDIALOG :
bRet = TRUE;
break;
case WM_MOUSEMOVE :
{
bRet = TRUE;
if (g_bStartSearchWindow)
{
// Only when we have started the Window Searching operation will we
// track mouse movement.
DoMouseMove(hwndDlg, uMsg, wParam, lParam);
}
break;
}
case WM_LBUTTONUP :
{
bRet = TRUE;
if (g_bStartSearchWindow)
{
// Only when we have started the window searching operation will we
// be interested when the user lifts up the left mouse button.
DoMouseUp(hwndDlg, uMsg, wParam, lParam);
}
break;
}
case WM_COMMAND :
{
WORD wNotifyCode = HIWORD(wParam); // notification code
WORD wID = LOWORD(wParam); // item, control, or accelerator identifier
HWND hwndCtl = (HWND)lParam; // handle of control
if ((wID == IDOK) || (wID == IDCANCEL))
{
bRet = TRUE;
UninitialiseResources();
PostQuitMessage(0);
break;
}
if (wID == IDC_STATIC_ICON_FINDER_TOOL)
{
// Because the IDC_STATIC_ICON_FINDER_TOOL static control is set with the SS_NOTIFY
// flag, the Search Window's dialog box will be sent a WM_COMMAND message when this
// static control is clicked.
bRet = TRUE;
// We start the window search operation by calling the DoSearchWindow() function.
SearchWindow(hwndDlg);
break;
}
if (wID == IDTRANSLATE)
{
TranslateText(hwndDlg);
break;
}
break;
}
case WM_DESTROY:
{
UninitialiseResources();
PostQuitMessage(0);
return 1;
}
case WM_CLOSE:
{
UninitialiseResources();
PostQuitMessage(0);
return 1;
}
default :
{
DefWindowProc
(
(HWND)hwndDlg, // handle to main frame window
(UINT)uMsg, // message
(WPARAM)wParam, // first message parameter
(LPARAM)lParam // second message parameter
);
bRet = FALSE;
break;
}
}
return bRet;
}
// Synopsis :
// 1. This function checks a hwnd to see if it is actually the "Search Window" Dialog's or Main Window's
// own window or one of their children. If so a FALSE will be returned so that these windows will not
// be selected.
//
// 2. Also, this routine checks to see if the hwnd to be checked is already a currently found window.
// If so, a FALSE will also be returned to avoid repetitions.
BOOL CheckWindowValidity (HWND hwndDialog, HWND hwndToCheck)
{
HWND hwndTemp = NULL;
// The window must not be NULL.
// It must also be a valid window as far as the OS is concerned.
// Ensure that the window is not the current one which has already been found.
// It also must not be the "Search Window" dialog box itself.
if ((hwndToCheck == NULL) ||(IsWindow(hwndToCheck) == FALSE) ||
(hwndToCheck == g_hwndFoundWindow) || (hwndToCheck == hwndDialog))
{
return FALSE;
}
// It also must not be one of the dialog box's children...
hwndTemp = GetParent (hwndToCheck);
if ((hwndTemp == hwndDialog))
{
return FALSE;
}
return TRUE;
}
// Synopsis :
// 1. This is the handler for WM_MOUSEMOVE messages sent to the "Search Window" dialog proc.
//
// 2. Note that we do not handle every WM_MOUSEMOVE message sent. Instead, we check to see
// if "g_bStartSearchWindow" is TRUE. This BOOL will be set to TRUE when the Window
// Searching Operation is actually started. See the WM_COMMAND message handler in
// SearchWindowDialogProc() for more details.
//
// 3. Because the "Search Window" dialog immediately captures the mouse when the Search Operation
// is started, all mouse movement is monitored by the "Search Window" dialog box. This is
// regardless of whether the mouse is within or without the "Search Window" dialog.
//
// 4. One important note is that the horizontal and vertical positions of the mouse cannot be
// calculated from "lParam". These values can be inaccurate when the mouse is outside the
// dialog box. Instead, use the GetCursorPos() API to capture the position of the mouse.
long DoMouseMove
(
HWND hwndDialog,
UINT message,
WPARAM wParam,
LPARAM lParam
)
{
POINT screenpoint;
HWND hwndFoundWindow = NULL;
TCHAR szText[256];
long lRet = 0;
// Must use GetCursorPos() instead of calculating from "lParam".
GetCursorPos (&screenpoint);
// Display global positioning in the dialog box.
wsprintf (szText, L"%d", screenpoint.x);
SetDlgItemText (hwndDialog, IDC_STATIC_X_POS, szText);
wsprintf (szText, L"%d", screenpoint.y);
SetDlgItemText (hwndDialog, IDC_STATIC_Y_POS, szText);
// Determine the window that lies underneath the mouse cursor.
hwndFoundWindow = WindowFromPoint (screenpoint);
// Check first for validity.
if (CheckWindowValidity (hwndDialog, hwndFoundWindow))
{
// We have just found a new window.
// Display some information on this found window.
DisplayInfoOnFoundWindow (hwndDialog, hwndFoundWindow);
// If there was a previously found window, we must instruct it to refresh itself.
// This is done to remove any highlighting effects drawn by us.
if (g_hwndFoundWindow)
{
//DeselectWindow(g_hwndFoundWindow);
RefreshWindow (g_hwndFoundWindow);
}
// Indicate that this found window is now the current global found window.
g_hwndFoundWindow = hwndFoundWindow;
// We now highlight the found window.
//HighlightFoundWindow (hwndDialog, g_hwndFoundWindow);
}
return lRet;
}
// Synopsis :
// 1. Handler for WM_LBUTTONUP message sent to the "Search Window" dialog box.//
// 2. We restore the screen cursor to the previous one.//
// 3. We stop the window search operation and release the mouse capture.
long DoMouseUp
(
HWND hwndDialog,
UINT message,
WPARAM wParam,
LPARAM lParam
)
{
long lRet = 0;
// If we had a previous cursor, set the screen cursor to the previous one.
// The cursor is to stay exactly where it is currently located when the
// left mouse button is lifted.
if (g_hCursorPrevious)
{
SetCursor (g_hCursorPrevious);
}
// If there was a found window, refresh it so that its highlighting is erased.
if (g_hwndFoundWindow)
{
RefreshWindow (g_hwndFoundWindow);
}
// Set the bitmap on the Finder Tool icon to be the bitmap with the bullseye bitmap.
SetFinderToolImage (hwndDialog, TRUE);
// Very important : must release the mouse capture.
ReleaseCapture ();
// Set the global search window flag to FALSE.
g_bStartSearchWindow = FALSE;
return lRet;
}
// Synopsis :
// 1. This routine sets the Finder Tool icon to contain an appropriate bitmap.
//
// 2. If bSet is TRUE, we display the BullsEye bitmap. Otherwise the empty window
// bitmap is displayed.
BOOL SetFinderToolImage (HWND hwndDialog, BOOL bSet)
{
HBITMAP hBmpToSet = NULL;
BOOL bRet = TRUE;
if (bSet)
{
// Set a FILLED image.
hBmpToSet = g_hBitmapFinderToolFilled;
}
else
{
// Set an EMPTY image.
hBmpToSet = g_hBitmapFinderToolEmpty;
}
SendDlgItemMessage
(
(HWND)hwndDialog, // handle of dialog box
(int)IDC_STATIC_ICON_FINDER_TOOL, // identifier of control
(UINT)STM_SETIMAGE, // message to send
(WPARAM)IMAGE_BITMAP, // first message parameter
(LPARAM)hBmpToSet // second message parameter
);
return bRet;
}
// Synopsis :
// 1. This routine moves the mouse cursor hotspot to the exact
// centre position of the bullseye in the finder tool static control.
//
// 2. This function, when used together with DoSetFinderToolImage(),
// gives the illusion that the bullseye image has indeed been transformed
// into a cursor and can be moved away from the Finder Tool Static
// control.
BOOL MoveCursorPositionToBullsEye (HWND hwndDialog)
{
BOOL bRet = FALSE;
HWND hwndToolFinder = NULL;
RECT rect;
POINT screenpoint;
// Get the window handle of the Finder Tool static control.
hwndToolFinder = GetDlgItem (hwndDialog, IDC_STATIC_ICON_FINDER_TOOL);
if (hwndToolFinder)
{
// Get the screen coordinates of the static control,
// add the appropriate pixel offsets to the center of
// the bullseye and move the mouse cursor to this exact
// position.
GetWindowRect (hwndToolFinder, &rect);
screenpoint.x = rect.left + BULLSEYE_CENTER_X_OFFSET;
screenpoint.y = rect.top + BULLSEYE_CENTER_Y_OFFSET;
SetCursorPos (screenpoint.x, screenpoint.y);
}
return bRet;
}
// Synopsis :
// 1. This function starts the window searching operation.
//
// 2. A very important part of this function is to capture
// all mouse activities from now onwards and direct all mouse
// messages to the "Search Window" dialog box procedure.
long SearchWindow (HWND hwndDialog)
{
long lRet = 0;
// Set the global "g_bStartSearchWindow" flag to TRUE.
g_bStartSearchWindow = TRUE;
// Display the empty window bitmap image in the Finder Tool static control.
SetFinderToolImage (hwndDialog, FALSE);
MoveCursorPositionToBullsEye (hwndDialog);
// Set the screen cursor to the BullsEye cursor.
if (g_hCursorSearchWindow)
{
g_hCursorPrevious = SetCursor (g_hCursorSearchWindow);
}
else
{
g_hCursorPrevious = NULL;
}
// Very important : capture all mouse activities from now onwards and
// direct all mouse messages to the "Search Window" dialog box procedure.
SetCapture (hwndDialog);
return lRet;
}
long DisplayInfoOnFoundWindow (HWND hwndDialog, HWND hwndFoundWindow)
{
RECT rect; // Rectangle area of the found window.
const int bufferSize = 1024;
TCHAR szWindowText[bufferSize] = _T("");
long lRet = 0;
// Get the screen coordinates of the rectangle of the found window.
GetWindowRect (hwndFoundWindow, &rect);
//Get Text from Window
int textLen = (int)SendMessage(hwndFoundWindow, WM_GETTEXTLENGTH, 0, 0);
if(0 < textLen)
{
SendMessage(hwndFoundWindow, WM_GETTEXT, (WPARAM)bufferSize, (LPARAM)szWindowText);
}
// Display some information on the found window.
SetDlgItemText (hwndDialog, IDC_EDIT_SOURCE_TEXT, szWindowText);
memset(szWindowText,'\0',sizeof(szWindowText));
return lRet;
}
long RefreshWindow (HWND hwndWindowToBeRefreshed)
{
long lRet = 0;
RECT rect; // Rectangle area of the found window.
// Get the screen coordinates of the rectangle of the found window.
GetWindowRect (hwndWindowToBeRefreshed, &rect);
//InvalidateRect (hwndWindowToBeRefreshed, NULL, NULL);
//UpdateWindow (hwndWindowToBeRefreshed);
lRet = RedrawWindow (hwndWindowToBeRefreshed, &rect, NULL, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
return lRet;
}
// Performs a highlighting of a found window.
// Comments below will demonstrate how this is done.
long HighlightFoundWindow (HWND hwndDialog, HWND hwndFoundWindow)
{
HDC hWindowDC = NULL; // The DC of the found window.
RECT rect; // Rectangle area of the found window.
long lRet = 0;
// Get the screen coordinates of the rectangle of the found window.
GetWindowRect (hwndFoundWindow, &rect);
// Get the window DC of the found window.
hWindowDC = GetWindowDC (hwndFoundWindow);
if (hWindowDC)
{
// Select our created pen into the DC and backup the previous pen.
g_hPrevPen = (HPEN) SelectObject (hWindowDC, g_hRectanglePen);
// Select a transparent brush into the DC and backup the previous brush.
g_hPrevBrush = (HBRUSH) SelectObject (hWindowDC, GetStockObject(HOLLOW_BRUSH));
// Draw a rectangle in the DC covering the entire window area of the found window.
Rectangle (hWindowDC, 0, 0, rect.right - rect.left, rect.bottom - rect.top);
SelectObject (hWindowDC, g_hPrevPen);
SelectObject (hWindowDC, g_hPrevBrush);
// Finally release the DC.
ReleaseDC (hwndFoundWindow, hWindowDC);
}
return lRet;
}
//Calls C# COM component which calls the Bing translator API
//Translates input text to output
BOOL TranslateText(HWND hwndDlg)
{
CoInitialize(NULL);
BOOL bRet = TRUE;
TCHAR szText[2048];
SetDlgItemText (hwndDlg, IDC_EDIT_TRANSLATED_TEXT, _T("Translating Message.....") );
GetDlgItemText(hwndDlg, IDC_EDIT_SOURCE_TEXT, szText, 1024);
CString strToTranslate(szText);
strToTranslate.Replace(_T("&"), _T(""));
CComPtr<ITranslator> cpi = NULL;
TCHAR szTranslated[2048];
HRESULT hr = CoCreateInstance(CLSID_TranslatorServiceComp,
NULL, CLSCTX_INPROC_SERVER,
IID_ITranslator, reinterpret_cast<void**>(&cpi));
if (FAILED(hr))
{
printf("Couldn't create the instance!... 0x%x\n", hr);
}
_bstr_t strTranslatedText = cpi->Translate(_bstr_t(strToTranslate));
_stprintf(szTranslated, _T("%s"), (LPCTSTR)strTranslatedText);
MessageBox(NULL, szTranslated , L"Test", MB_OK);
SetDlgItemText (hwndDlg, IDC_EDIT_TRANSLATED_TEXT, szTranslated );
CoUninitialize();
return bRet;
} | 26.569966 | 145 | 0.711753 |
2101331a0292dcc4225c749946f0ebf7e07afd9b | 7,052 | cpp | C++ | cali-linker/modules/ipc_module.cpp | cali-library-isolation/Cali-library-isolation | 550893293f66b0428a7b66e1ab80d9f5b7a4bbf4 | [
"Apache-2.0"
] | 7 | 2021-03-26T06:52:31.000Z | 2022-03-11T09:42:57.000Z | cali-linker/modules/ipc_module.cpp | cali-library-isolation/Cali-library-isolation | 550893293f66b0428a7b66e1ab80d9f5b7a4bbf4 | [
"Apache-2.0"
] | null | null | null | cali-linker/modules/ipc_module.cpp | cali-library-isolation/Cali-library-isolation | 550893293f66b0428a7b66e1ab80d9f5b7a4bbf4 | [
"Apache-2.0"
] | 1 | 2022-02-25T06:57:17.000Z | 2022-02-25T06:57:17.000Z | #include <memory>
#include <stdexcept>
#include <memory>
#include <iostream>
#include <llvm/IR/Module.h>
#include <llvm/Linker/Linker.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/IR/Verifier.h>
#include "ipc_module.h"
#include "llvm_module.h"
#include "../stdlib-is-shit.h"
#include "../cali_linker/archive-wrapper.h"
#include "../cali_linker/debug.h"
#include "../cali_linker/linker_replacement.h"
#include "../cali_linker/randomness.h"
namespace ipcrewriter {
std::shared_ptr<IpcModule>
IpcModule::newIpcModuleFromFile(const std::string &filename, bool isMainModule, YamlConfig *config, const ContextConfig *contextConfig) {
if (endsWith(filename, ".bc") || endsWith(filename, ".ll") || endsWith(filename, ".o")) {
return std::shared_ptr<IpcModule>(new LlvmIpcModule(filename, isMainModule, config, contextConfig));
}
if (endsWith(filename, ".so") || endsWith(filename, ".a")) {
return std::shared_ptr<IpcModule>(new BinaryIpcModule(filename, isMainModule, config, contextConfig));
}
throw std::invalid_argument("No supported extension");
}
const std::set<std::string> &IpcModule::getImports() const {
return imports;
}
const std::set<std::string> &IpcModule::getExports() const {
return exports;
}
const std::string &IpcModule::getSource() const {
return source;
}
const std::vector<std::string> &IpcModule::getLogEntries() {
return logEntries;
}
static int linked_things = 0;
std::shared_ptr<IpcModule>
CompositeIpcModule::newIpcModulesFromFiles(std::vector<std::string> &files, bool isMainModule, YamlConfig *config, const ContextConfig *contextConfig,
const std::string &output_filename) {
std::vector<std::shared_ptr<IpcModule>> binary_modules;
std::set<std::string> seen_files;
std::set<std::string> ignored;
// Prepare LLVM linker
LlvmIpcModule::context.enableDebugTypeODRUniquing();
// Load initial llvm bitcode file, containing some libc stubs
filesystem::path stubsFilename = applicationPath;
stubsFilename.append("libc-stubs.bc");
llvm::SMDiagnostic error;
auto composite_module = parseIRFile(stubsFilename.string(), error, LlvmIpcModule::context);
composite_module->setModuleIdentifier("llvm-linked-things_" + output_filename + "_" + std::to_string(linked_things++) + '-' + getRandomString() + ".bc");
// Prepare linker
llvm::Linker L(*composite_module);
int linked_modules = 0;
auto linkerflags = config->linkerOverride ? llvm::Linker::Flags::OverrideFromSrc : llvm::Linker::Flags::None;
// Helper function - link an additional LLVM file to the unique LLVM module
auto addLlvmModule = [&linked_modules, &L, linkerflags](std::unique_ptr<llvm::Module> module) {
if (L.linkInModule(std::move(module), linkerflags))
throw std::runtime_error("Could not link module");
linked_modules++;
};
for (const auto &filename: files) {
// file missing?
if (!exists(filename)) {
std::cerr << "Warning: file not found (" << filename << ")" << std::endl;
continue;
}
// Check if file has already been loaded
if (!seen_files.insert(absolute(filename)).second) {
std::cerr << "Already seen: " << filename << std::endl;
continue;
}
// Shared libraries
if (endsWith(filename, ".so")) {
binary_modules.push_back(std::shared_ptr<IpcModule>(new BinaryIpcModule(filename, isMainModule, config, contextConfig)));
continue;
}
// LLVM files
if (endsWith(filename, ".bc") || endsWith(filename, ".ll")) {
auto m = llvm::parseIRFile(filename, error, LlvmIpcModule::context);
if (filename.find("libstdc++") != std::string::npos)
for (auto &g: m->functions())
if (g.hasName()) ignored.insert(g.getName());
addLlvmModule(std::move(m));
}
// object files
if (endsWith(filename, ".o")) {
auto header = read_file_limit(filename, 4);
if (header == "BC\xc0\xde") {
addLlvmModule(llvm::parseIRFile(filename, error, LlvmIpcModule::context));
} else if (header == "\x7f""ELF") {
binary_modules.push_back(std::shared_ptr<IpcModule>(new BinaryIpcModule(filename, isMainModule, config, contextConfig)));
} else {
std::cerr << "Can\'t determine type of file " + filename << std::endl;
}
}
// static libraries
if (endsWith(filename, ".a")) {
bool binary_added = false;
dbg_cout << "Open archive " << filename << std::endl;
libarchive::Archive archive(filename);
int i = 0;
for (auto it: archive) {
//if (it.name() != "magick_libMagickCore_6_Q16_la-ps.o" && it.name() != "magick_libMagickCore_6_Q16_la-string.o")
// continue; //TODO hack
// if (i++ == 3)
// break; //TODO hack
if (endsWith(it.name(), ".o") || endsWith(it.name(), ".bc") || endsWith(it.name(), ".lo")) {
dbg_cout << "- Archive entry: " << it.name() << std::endl;
std::string buffer = it.read();
if (buffer.substr(0, 4) == "BC\xc0\xde") {
auto buffer2 = llvm::MemoryBuffer::getMemBufferCopy(buffer);
auto m = llvm::parseIR(buffer2->getMemBufferRef(), error, LlvmIpcModule::context);
if (!m)
error.print(it.name().c_str(), llvm::errs());
if (filename.find("libstdc++") != std::string::npos)
for (auto &g: m->functions())
if (g.hasName()) ignored.insert(g.getName());
addLlvmModule(std::move(m));
} else if (buffer.substr(0, 4) == "\x7f""ELF") {
if (!binary_added) {
binary_modules.push_back(std::shared_ptr<IpcModule>(new BinaryIpcModule(filename, isMainModule, config, contextConfig, true)));
binary_added = true;
}
} else {
std::cerr << "Can\'t determine type of file " + it.name() << " in archive " << filename << std::endl;
}
}
}
}
}
if (llvm::verifyModule(*composite_module, &llvm::errs())) {
throw std::runtime_error("linked module is broken!");
}
// build composite
if (linked_modules == 0 && binary_modules.size() == 1)
return binary_modules[0];
if (linked_modules == 1 && binary_modules.empty())
return std::shared_ptr<IpcModule>(new LlvmIpcModule(std::move(composite_module), isMainModule, config, contextConfig));
auto m = std::make_shared<CompositeIpcModule>(isMainModule, config, contextConfig);
if (linked_modules > 0) {
auto llvmModule = std::shared_ptr<IpcModule>(new LlvmIpcModule(std::move(composite_module), isMainModule, config, contextConfig));
dbg_cout << ignored.size() << " ignored symbols" << std::endl;
llvmModule->ignored = std::move(ignored);
m->add(llvmModule);
}
for (const auto &bm: binary_modules)
m->add(bm);
return m;
}
CompositeIpcModule::CompositeIpcModule(bool isMainModule, YamlConfig *config, const ContextConfig *contextConfig)
: IpcModule("", isMainModule, config, contextConfig) {}
const std::vector<std::string> &CompositeIpcModule::getLogEntries() {
logEntries.clear();
for (auto &m: modules) {
for (auto &s: m->getLogEntries())
logEntries.push_back(s);
}
return logEntries;
}
} | 36.729167 | 155 | 0.671583 |
21041a67704d748cb24c61d6086c7bb68d188097 | 2,329 | hpp | C++ | includes/matrix.hpp | TheLandfill/tsp | ae2b90c8a44f4521373259a587d4c91c5bc318a3 | [
"MIT"
] | null | null | null | includes/matrix.hpp | TheLandfill/tsp | ae2b90c8a44f4521373259a587d4c91c5bc318a3 | [
"MIT"
] | null | null | null | includes/matrix.hpp | TheLandfill/tsp | ae2b90c8a44f4521373259a587d4c91c5bc318a3 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <stdexcept>
template<typename T>
class Matrix {
public:
Matrix();
Matrix(const std::filesystem::path& path);
template<typename Func>
Matrix(size_t num_rows, size_t num_cols, Func rng);
void write_to_file(const std::filesystem::path& path) const;
T at(size_t row, size_t col) const;
T& at(size_t row, size_t col);
size_t get_num_rows() const;
size_t get_num_cols() const;
private:
size_t num_rows, num_cols;
std::vector<T> data;
};
template<typename T>
Matrix<T>::Matrix() : num_rows(0), num_cols(0), data() {}
template<typename T>
Matrix<T>::Matrix(const std::filesystem::path& path) {
std::ifstream reader{path};
if (!reader.is_open()) {
std::string error_message;
error_message.reserve(1024);
error_message += "File `";
error_message += path;
error_message += "` not found!";
throw std::runtime_error(error_message);
}
reader >> num_rows >> num_cols;
data.resize(num_rows * num_cols);
for (size_t row = 0; row < num_rows; row++) {
for (size_t col = 0; col < num_cols; col++) {
if(!(reader >> at(row, col))) {
std::cerr << "Could not read element at (" << row << ", " << col << ")!\n";
throw std::runtime_error("Error Reading Element!");
}
}
}
}
template<typename T>
template<typename Func>
Matrix<T>::Matrix(size_t nr, size_t nc, Func rng) :
num_rows(nr),
num_cols(nc)
{
data.reserve(nr * nc);
for (size_t row = 0; row < num_rows; row++) {
for (size_t col = 0; col < num_cols; col++) {
data.emplace_back(rng());
}
}
}
template<typename T>
void Matrix<T>::write_to_file(const std::filesystem::path& path) const {
std::ofstream writer{path};
writer << num_rows << " " << num_cols << "\n";
for (size_t row = 0; row < num_rows; row++) {
for (size_t col = 0; col < num_cols - 1; col++) {
writer << at(row, col) << " ";
}
writer << at(row, num_cols - 1) << "\n";
}
}
template<typename T>
T Matrix<T>::at(size_t row, size_t col) const {
return data.at(row * num_cols + col);
}
template<typename T>
T& Matrix<T>::at(size_t row, size_t col) {
return data.at(row * num_cols + col);
}
template<typename T>
size_t Matrix<T>::get_num_rows() const {
return num_rows;
}
template<typename T>
size_t Matrix<T>::get_num_cols() const {
return num_cols;
}
| 23.29 | 79 | 0.656934 |
21062d454eb17252c77fefab529e1c42ce286dca | 1,577 | hpp | C++ | partners_api/ads/ads_utils.hpp | vicpopov/omim | 664b458998fb0f2405f68ae830c2798e027b2dcc | [
"Apache-2.0"
] | 4,879 | 2015-09-30T10:56:36.000Z | 2022-03-31T18:43:03.000Z | partners_api/ads/ads_utils.hpp | mbrukman/omim | d22fe2b6e0beee697f096e931df97a64f9db9dc1 | [
"Apache-2.0"
] | 7,549 | 2015-09-30T10:52:53.000Z | 2022-03-31T22:04:22.000Z | partners_api/ads/ads_utils.hpp | mbrukman/omim | d22fe2b6e0beee697f096e931df97a64f9db9dc1 | [
"Apache-2.0"
] | 1,493 | 2015-09-30T10:43:06.000Z | 2022-03-21T09:16:49.000Z | #pragma once
#include "storage/storage_defines.hpp"
#include <cstdint>
#include <initializer_list>
#include <string>
#include <unordered_set>
namespace ads
{
class WithSupportedLanguages
{
public:
virtual ~WithSupportedLanguages() = default;
void AppendSupportedUserLanguages(std::initializer_list<std::string> const & languages);
bool IsLanguageSupported(std::string const & lang) const;
private:
std::unordered_set<int8_t> m_supportedUserLanguages;
};
class WithSupportedCountries
{
public:
virtual ~WithSupportedCountries() = default;
void AppendSupportedCountries(std::initializer_list<storage::CountryId> const & countries);
void AppendExcludedCountries(std::initializer_list<storage::CountryId> const & countries);
bool IsCountrySupported(storage::CountryId const & countryId) const;
bool IsCountryExcluded(storage::CountryId const & countryId) const;
private:
// All countries are supported when empty.
std::unordered_set<storage::CountryId> m_supportedCountries;
std::unordered_set<storage::CountryId> m_excludedCountries;
};
class WithSupportedUserPos
{
public:
virtual ~WithSupportedUserPos() = default;
void AppendSupportedUserPosCountries(std::initializer_list<storage::CountryId> const & countries);
void AppendExcludedUserPosCountries(std::initializer_list<storage::CountryId> const & countries);
bool IsUserPosCountrySupported(storage::CountryId const & countryId) const;
bool IsUserPosCountryExcluded(storage::CountryId const & countryId) const;
private:
WithSupportedCountries m_countries;
};
} // namespace ads
| 29.203704 | 100 | 0.795815 |
2108dd29216970cc4c099439b99610cdb7f6a839 | 10,392 | cpp | C++ | JsonHandler.cpp | brrrtm/lab3 | cc364c85ff80faab79d4e0ab4880b92ab5570ca5 | [
"MIT"
] | null | null | null | JsonHandler.cpp | brrrtm/lab3 | cc364c85ff80faab79d4e0ab4880b92ab5570ca5 | [
"MIT"
] | null | null | null | JsonHandler.cpp | brrrtm/lab3 | cc364c85ff80faab79d4e0ab4880b92ab5570ca5 | [
"MIT"
] | null | null | null | #include "JsonHandler.h"
#include <random>
#include <ctime>
#include <Windows.h>
JsonKey::JsonKey() {
}
JsonKey::JsonKey(string path) {
Json::Value arg;
ifstream file(path);
file >> arg;
file.close();
type = arg["type"].asString();
}
string JsonKey::get_type()
{
return this->type;
}
void JsonKey::get_text(string path) {
ifstream file(path);
while (!file.eof()) {
getline(file, decrypted);
decrypted += '\n';
}
decrypted.pop_back();
file.close();
}
void JsonKey::load_en_text(string path) {
Json::Value arg;
ifstream file(path);
file >> arg;
file.close();
type = arg["type"].asString();
encrypted = arg["text"].asString();
}
string JsonKey::get_dec_text() {
return decrypted;
}
string JsonKey::get_en_text() {
return encrypted;
}
void JsonKey::set_dec_text(string text) {
decrypted = text;
}
void JsonKey::set_en_text(string text) {
encrypted = text;
}
void JsonKey::set_type(string t) {
type = t;
}
void JsonKey::get_dec_text_from_file(string txt) {
ifstream file(txt);
string text;
while (!file.eof()) {
getline(file, text);
text += '\n';
}
file.close();
text.pop_back();
decrypted = text;
}
JsonKey::~JsonKey() {};
// change
JsonChangeKey::JsonChangeKey() {
this->set_type("change");
};
JsonChangeKey::JsonChangeKey(string path) {
Json::Value arg;
ifstream file(path);
file >> arg;
file.close();
this->get_type() = arg["type"].asString();
int idx = 0;
for (Json::Value::iterator it = arg["key"].begin(); it != arg["key"].end(); it++) {
int s1 = arg["key"][idx][0].asInt(), s2 = arg["key"][idx++][1].asInt();
key.push_back(make_pair((char)s1, (char)s2));
}
}
Json::Value JsonChangeKey::get_key_arguments() {
Json::Value arg;
arg["type"] = this->get_type();
for (int i = 0; i < key.size(); i++) {
arg["key"][i][0] = key[i].first;
arg["key"][i][1] = key[i].second;
}
return arg;
}
void JsonChangeKey::generate_key() {
srand(time(NULL));
vector<char> temp_alph = alphabet;
vector<char> alr;
string en = get_dec_text();
for (int i = 0; i < en.size(); i++) {
for (int j = i + 1; j < en.size(); j++) {
if (en[i] == en[j]) {
en.erase(en.begin() + j);
j--;
}
}
}
for (int i = 0; i < en.size(); i++) {
int id = rand() % temp_alph.size();
while (!check_alr(alr, temp_alph[id])) {
id = rand() % temp_alph.size();
}
alr.push_back(temp_alph[id]);
key.push_back(make_pair(en[i], temp_alph[id]));
}
save_key();
}
void JsonChangeKey::code() {
string text = get_dec_text();
for (int i = 0; i < text.size(); i++) {
for (int j = 0; j < key.size(); j++) {
if (text[i] == key[j].first) {
text[i] = key[j].second;
break;
}
}
}
set_en_text(text);
save_encrypt();
}
void JsonChangeKey::decode() {
string text = get_en_text();
vector<pair<char, char>> k = this->key;
for (int i = 0; i < text.size(); i++) {
for (int j = 0; j < k.size(); j++) {
if (text[i] == k[j].second) {
text[i] = k[j].first;
break;
}
}
}
set_dec_text(text);
save_decrypt();
}
bool JsonChangeKey::is_keys_generated() {
return !key.empty();
}
bool JsonChangeKey::check_alr(vector<char> v, char c) {
for (int i = 0; i < v.size(); i++) {
if (v[i] == c) return false;
}
return true;
}
void JsonChangeKey::save_key() {
string name = "ChangeKey.key";
Json::Value arg = this->get_key_arguments();
ofstream file(name);
file << arg;
file.close();
}
void JsonChangeKey::save_encrypt() {
Json::Value arg;
arg["type"] = this->get_type();
arg["text"] = this->get_en_text();
ofstream file("text.encrypt");
file << arg;
file.close();
}
void JsonChangeKey::save_decrypt() {
ofstream file("decrypted_change.txt");
file << this->get_dec_text();
file.close();
}
JsonChangeKey::~JsonChangeKey() {};
// transposition
JsonTransposKey::JsonTransposKey() {
this->set_type("transposition");
}
JsonTransposKey::JsonTransposKey(string path) {
Json::Value arg;
ifstream file(path);
file >> arg;
file.close();
this->set_type(arg["type"].asString());
int idx = 0;
for (Json::Value::iterator it = arg["key"].begin(); it != arg["key"].end(); it++) {
int s1 = arg["key"][idx][0].asInt(), s2 = arg["key"][idx++][1].asInt();
key.push_back(make_pair(s1, s2));
}
}
Json::Value JsonTransposKey::get_key_arguments()
{
Json::Value arg;
arg["type"] = this->get_type();
for (int i = 0; i < key.size(); i++) {
arg["key"][i][0] = key[i].first;
arg["key"][i][1] = key[i].second;
}
return arg;
}
void JsonTransposKey::generate_key() {
srand(time(NULL));
vector<int> ks, already;
for (int i = 0; i < get_dec_text().size(); i++) {
ks.push_back(i);
}
for (int i = 0; i < get_dec_text().size() / 2; i++) {
int id1 = rand() % ks.size();
while (!check_alr(already, id1))
id1 = rand() % ks.size();
already.push_back(id1);
int id2 = rand() % ks.size();
while (!check_alr(already, id2))
id2 = rand() % ks.size();
already.push_back(id2);
key.push_back(make_pair(id1, id2));
}
save_key();
}
void JsonTransposKey::code(){
string text = get_dec_text();
for (int i = 0; i < key.size(); i++) {
swap(text[key[i].first], text[key[i].second]);
}
set_en_text(text);
save_encrypt();
}
void JsonTransposKey::decode(){
string text = get_en_text();
for (int i = 0; i < key.size(); i++) {
swap(text[key[i].second], text[key[i].first]);
}
set_dec_text(text);
save_decrypt();
}
bool JsonTransposKey::is_keys_generated() {
return !key.empty();
}
bool JsonTransposKey::check_alr(vector<int> v, int c) {
for (int i = 0; i < v.size(); i++) {
if (v[i] == c) return false;
}
return true;
}
JsonTransposKey::~JsonTransposKey(){
}
void JsonTransposKey::save_key(){
ofstream file("TransposKey.key");
Json::Value arg = this->get_key_arguments();
file << arg;
file.close();
}
void JsonTransposKey::save_encrypt(){
Json::Value arg;
arg["type"] = this->get_type();
arg["text"] = this->get_en_text();
ofstream file("text.encrypt");
file << arg;
file.close();
}
void JsonTransposKey::save_decrypt() {
ofstream file("dectypted_transposition.txt");
file << this->get_dec_text();
file.close();
}
// gamma
Gamma::Gamma() {
this->set_type("gamma");
}
Gamma::Gamma(string path) {
Json::Value arg;
ifstream file(path);
file >> arg;
file.close();
this->set_type(arg["type"].asString());
string k;
int idx = 0;
for (Json::Value::iterator it = arg["key"].begin(); it != arg["key"].end(); it++) {
k += (char)(arg["key"][idx++].asInt());
}
this->key = k;
}
Json::Value Gamma::get_key_arguments() {
Json::Value arg;
arg["type"] = this->get_type();
for (int i = 0; i < key.size(); i++) {
arg["key"][i] = (int)key[i];
}
return arg;
}
void Gamma::generate_key() {
srand(time(NULL));
int size = rand() % 10;
for (int i = 0; i < size; i++) {
char ch = alphabet_g[(rand() % (alphabet_g.size() - 1)) + 1];
key += ch;
}
if (key.size() == this->get_dec_text().size()) {
save_key();
}
while (key.size() > this->get_dec_text().size()) {
if (key.size() == this->get_dec_text().size()) {
break;
}
key.pop_back();
}
if (key.size() < this->get_dec_text().size()) {
int im = 0;
int end = key.size();
for (int i = 0; i < this->get_dec_text().size(); i++) {
if (key.size() == this->get_dec_text().size()) {
break;
}
key += key[im++];
if (im == end)im = 0;
}
}
save_key();
}
void Gamma::code() {
vector<int> text_i;
vector<int> gamma_i;
string text = this->get_dec_text();
for (int i = 0; i < text.size(); i++) {
for (int j = 0; j < alphabet_g.size(); j++) {
if (text[i] == alphabet_g[j]) text_i.push_back(j);
if (key[i] == alphabet_g[j]) gamma_i.push_back(j);
}
}
for (int i = 0; i < text.size(); i++) {
int idx = (text_i[i] + gamma_i[i]) % alphabet_g.size();
text[i] = alphabet_g[idx];
}
this->set_en_text(text);
save_encrypt();
}
void Gamma::decode() {
vector<int> text_i;
vector<int> gamma_i;
string text = this->get_en_text();
for (int i = 0; i < text.size(); i++) {
for (int j = 0; j < alphabet_g.size(); j++) {
if (text[i] == alphabet_g[j]) text_i.push_back(j);
if (key[i] == alphabet_g[j]) gamma_i.push_back(j);
}
}
for (int i = 0; i < text.size(); i++) {
if (text_i[i] == 0) text_i[i] = alphabet_g.size() - 1;
int idx = (text_i[i] - gamma_i[i] + alphabet_g.size()) % alphabet_g.size();
text[i] = alphabet_g[idx];
}
set_dec_text(text);
save_decrypt();
}
bool Gamma::is_keys_generated() {
return !key.empty();
}
Gamma::~Gamma() {}
void Gamma::save_key() {
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
Json::Value arg = this->get_key_arguments();
ofstream file("GammaKey.key");
file << arg;
file.close();
}
void Gamma::save_encrypt() {
Json::Value arg;
arg["type"] = this->get_type();
arg["text"] = this->get_en_text();
ofstream file("text.encrypt");
file << arg;
file.close();
}
void Gamma::save_decrypt() {
ofstream file("decrypted_gamma.txt");
file << this->get_dec_text();
file.close();
}
| 26.176322 | 88 | 0.518187 |
210a6edaf9fae2e3b58701a703c2479ecb6ce056 | 31,405 | cxx | C++ | ds/adsi/nw312/cschema.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/adsi/nw312/cschema.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/adsi/nw312/cschema.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 1996
//
// File: cschema.cxx
//
// Contents: Windows NT 3.51
//
//
// History: 01-09-96 yihsins Created.
//
//----------------------------------------------------------------------------
#include "nwcompat.hxx"
#pragma hdrstop
/******************************************************************/
/* Class CNWCOMPATSchema
/******************************************************************/
DEFINE_IDispatch_Implementation(CNWCOMPATSchema)
DEFINE_IADs_Implementation(CNWCOMPATSchema)
CNWCOMPATSchema::CNWCOMPATSchema()
{
VariantInit( &_vFilter );
ENLIST_TRACKING(CNWCOMPATSchema);
}
CNWCOMPATSchema::~CNWCOMPATSchema()
{
VariantClear( &_vFilter );
delete _pDispMgr;
}
HRESULT
CNWCOMPATSchema::CreateSchema(
BSTR bstrParent,
BSTR bstrName,
DWORD dwObjectState,
REFIID riid,
void **ppvObj
)
{
CNWCOMPATSchema FAR *pSchema = NULL;
HRESULT hr = S_OK;
hr = AllocateSchemaObject( &pSchema );
BAIL_ON_FAILURE(hr);
hr = pSchema->InitializeCoreObject(
bstrParent,
bstrName,
SCHEMA_CLASS_NAME,
NO_SCHEMA,
CLSID_NWCOMPATSchema,
dwObjectState );
BAIL_ON_FAILURE(hr);
hr = pSchema->QueryInterface( riid, ppvObj );
BAIL_ON_FAILURE(hr);
pSchema->Release();
RRETURN(hr);
error:
delete pSchema;
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATSchema::QueryInterface(REFIID iid, LPVOID FAR* ppv)
{
if (ppv == NULL) {
RRETURN(E_POINTER);
}
if (IsEqualIID(iid, IID_IUnknown))
{
*ppv = (IADs FAR *) this;
}
else if (IsEqualIID(iid, IID_IDispatch))
{
*ppv = (IADs FAR *)this;
}
else if (IsEqualIID(iid, IID_ISupportErrorInfo))
{
*ppv = (ISupportErrorInfo FAR *) this;
}
else if (IsEqualIID(iid, IID_IADsContainer))
{
*ppv = (IADsContainer FAR *)this;
}
else if (IsEqualIID(iid, IID_IADs))
{
*ppv = (IADs FAR *) this;
}
else
{
*ppv = NULL;
return E_NOINTERFACE;
}
AddRef();
return NOERROR;
}
/* ISupportErrorInfo method */
STDMETHODIMP
CNWCOMPATSchema::InterfaceSupportsErrorInfo(
THIS_ REFIID riid
)
{
if (IsEqualIID(riid, IID_IADs) ||
IsEqualIID(riid, IID_IADsContainer)) {
RRETURN(S_OK);
} else {
RRETURN(S_FALSE);
}
}
/* IADs methods */
STDMETHODIMP
CNWCOMPATSchema::SetInfo(THIS)
{
RRETURN_EXP_IF_ERR(E_NOTIMPL);
}
STDMETHODIMP
CNWCOMPATSchema::GetInfo(THIS)
{
RRETURN(S_OK);
}
/* IADsContainer methods */
STDMETHODIMP
CNWCOMPATSchema::get_Count(long FAR* retval)
{
HRESULT hr;
if ( !retval )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
*retval = g_cNWCOMPATClasses + g_cNWCOMPATSyntax;
RRETURN(S_OK);
}
STDMETHODIMP
CNWCOMPATSchema::get_Filter(THIS_ VARIANT FAR* pVar)
{
HRESULT hr;
if ( !pVar )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
VariantInit( pVar );
hr = VariantCopy( pVar, &_vFilter );
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATSchema::put_Filter(THIS_ VARIANT Var)
{
HRESULT hr;
hr = VariantCopy( &_vFilter, &Var );
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATSchema::put_Hints(THIS_ VARIANT Var)
{
RRETURN_EXP_IF_ERR( E_NOTIMPL);
}
STDMETHODIMP
CNWCOMPATSchema::get_Hints(THIS_ VARIANT FAR* pVar)
{
RRETURN_EXP_IF_ERR(E_NOTIMPL);
}
STDMETHODIMP
CNWCOMPATSchema::GetObject(
THIS_ BSTR ClassName,
BSTR RelativeName,
IDispatch * FAR* ppObject)
{
TCHAR szBuffer[MAX_PATH];
HRESULT hr = S_OK;
if (!RelativeName || !*RelativeName) {
RRETURN_EXP_IF_ERR(E_ADS_UNKNOWN_OBJECT);
}
memset(szBuffer, 0, sizeof(szBuffer));
wcscpy(szBuffer, _ADsPath);
wcscat(szBuffer, L"/");
wcscat(szBuffer, RelativeName);
if (ClassName && *ClassName) {
wcscat(szBuffer,L",");
wcscat(szBuffer, ClassName);
}
hr = ::GetObject(
szBuffer,
(LPVOID *)ppObject
);
BAIL_ON_FAILURE(hr);
error:
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATSchema::get__NewEnum(THIS_ IUnknown * FAR* retval)
{
HRESULT hr;
IEnumVARIANT *penum = NULL;
if ( !retval )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
*retval = NULL;
//
// Create new enumerator for items currently
// in collection and QI for IUnknown
//
hr = CNWCOMPATSchemaEnum::Create( (CNWCOMPATSchemaEnum **)&penum,
_ADsPath,
_Name,
_vFilter );
BAIL_ON_FAILURE(hr);
hr = penum->QueryInterface( IID_IUnknown, (VOID FAR* FAR*)retval );
BAIL_ON_FAILURE(hr);
if ( penum )
penum->Release();
RRETURN(hr);
error:
if ( penum )
delete penum;
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATSchema::Create(
THIS_ BSTR ClassName,
BSTR RelativeName,
IDispatch * FAR* ppObject)
{
RRETURN_EXP_IF_ERR(E_NOTIMPL);
}
STDMETHODIMP
CNWCOMPATSchema::Delete(THIS_ BSTR SourceName, BSTR Type)
{
RRETURN_EXP_IF_ERR(E_NOTIMPL);
}
STDMETHODIMP
CNWCOMPATSchema::CopyHere(
THIS_ BSTR SourceName,
BSTR NewName,
IDispatch * FAR* ppObject
)
{
RRETURN_EXP_IF_ERR(E_NOTIMPL);
}
STDMETHODIMP
CNWCOMPATSchema::MoveHere(
THIS_ BSTR SourceName,
BSTR NewName,
IDispatch * FAR* ppObject
)
{
RRETURN_EXP_IF_ERR(E_NOTIMPL);
}
HRESULT
CNWCOMPATSchema::AllocateSchemaObject(CNWCOMPATSchema FAR * FAR * ppSchema)
{
CNWCOMPATSchema FAR *pSchema = NULL;
CAggregatorDispMgr FAR *pDispMgr = NULL;
HRESULT hr = S_OK;
pSchema = new CNWCOMPATSchema();
if ( pSchema == NULL )
hr = E_OUTOFMEMORY;
BAIL_ON_FAILURE(hr);
pDispMgr = new CAggregatorDispMgr;
if ( pDispMgr == NULL )
hr = E_OUTOFMEMORY;
BAIL_ON_FAILURE(hr);
hr = LoadTypeInfoEntry( pDispMgr,
LIBID_ADs,
IID_IADs,
(IADs *) pSchema,
DISPID_REGULAR );
BAIL_ON_FAILURE(hr);
hr = LoadTypeInfoEntry( pDispMgr,
LIBID_ADs,
IID_IADsContainer,
(IADsContainer *) pSchema,
DISPID_NEWENUM );
BAIL_ON_FAILURE(hr);
pSchema->_pDispMgr = pDispMgr;
*ppSchema = pSchema;
RRETURN(hr);
error:
delete pDispMgr;
delete pSchema;
RRETURN(hr);
}
/******************************************************************/
/* Class CNWCOMPATClass
/******************************************************************/
DEFINE_IDispatch_Implementation(CNWCOMPATClass)
DEFINE_IADs_Implementation(CNWCOMPATClass)
CNWCOMPATClass::CNWCOMPATClass()
: _pDispMgr( NULL ),
_aPropertyInfo( NULL ),
_cPropertyInfo( 0 ),
_bstrCLSID( NULL ),
_bstrOID( NULL ),
_bstrPrimaryInterface( NULL ),
_fAbstract( FALSE ),
_fContainer( FALSE ),
_bstrHelpFileName( NULL ),
_lHelpFileContext( 0 )
{
VariantInit( &_vMandatoryProperties );
VariantInit( &_vOptionalProperties );
VariantInit( &_vPossSuperiors );
VariantInit( &_vContainment );
VariantInit( &_vFilter );
ENLIST_TRACKING(CNWCOMPATClass);
}
CNWCOMPATClass::~CNWCOMPATClass()
{
if ( _bstrCLSID ) {
ADsFreeString( _bstrCLSID );
}
if ( _bstrOID ) {
ADsFreeString( _bstrOID );
}
if ( _bstrPrimaryInterface ) {
ADsFreeString( _bstrPrimaryInterface );
}
if ( _bstrHelpFileName ) {
ADsFreeString( _bstrHelpFileName );
}
VariantClear( &_vMandatoryProperties );
VariantClear( &_vOptionalProperties );
VariantClear( &_vPossSuperiors );
VariantClear( &_vContainment );
VariantClear( &_vFilter );
delete _pDispMgr;
}
HRESULT
CNWCOMPATClass::CreateClass(
BSTR bstrParent,
CLASSINFO *pClassInfo,
DWORD dwObjectState,
REFIID riid,
void **ppvObj
)
{
CNWCOMPATClass FAR *pClass = NULL;
HRESULT hr = S_OK;
BSTR bstrTmp = NULL;
hr = AllocateClassObject( &pClass );
BAIL_ON_FAILURE(hr);
pClass->_aPropertyInfo = pClassInfo->aPropertyInfo;
pClass->_cPropertyInfo = pClassInfo->cPropertyInfo;
pClass->_lHelpFileContext = pClassInfo->lHelpFileContext;
pClass->_fContainer = (VARIANT_BOOL) pClassInfo->fContainer;
pClass->_fAbstract = (VARIANT_BOOL) pClassInfo->fAbstract;
hr = StringFromCLSID( (REFCLSID) *(pClassInfo->pPrimaryInterfaceGUID),
&bstrTmp );
BAIL_ON_FAILURE(hr);
hr = ADsAllocString( bstrTmp,
&pClass->_bstrPrimaryInterface );
BAIL_ON_FAILURE(hr);
CoTaskMemFree( bstrTmp );
bstrTmp = NULL;
hr = StringFromCLSID( (REFCLSID) *(pClassInfo->pCLSID),
&bstrTmp );
BAIL_ON_FAILURE(hr);
hr = ADsAllocString( bstrTmp,
&pClass->_bstrCLSID );
BAIL_ON_FAILURE(hr);
CoTaskMemFree( bstrTmp );
bstrTmp = NULL;
hr = ADsAllocString( pClassInfo->bstrOID, &pClass->_bstrOID);
BAIL_ON_FAILURE(hr);
hr = MakeVariantFromStringList( pClassInfo->bstrMandatoryProperties,
&(pClass->_vMandatoryProperties));
BAIL_ON_FAILURE(hr);
hr = MakeVariantFromStringList( pClassInfo->bstrOptionalProperties,
&(pClass->_vOptionalProperties));
BAIL_ON_FAILURE(hr);
hr = MakeVariantFromStringList( pClassInfo->bstrPossSuperiors,
&(pClass->_vPossSuperiors));
BAIL_ON_FAILURE(hr);
hr = MakeVariantFromStringList( pClassInfo->bstrContainment,
&(pClass->_vContainment));
BAIL_ON_FAILURE(hr);
hr = ADsAllocString( pClassInfo->bstrHelpFileName,
&pClass->_bstrHelpFileName);
BAIL_ON_FAILURE(hr);
hr = pClass->InitializeCoreObject(
bstrParent,
pClassInfo->bstrName,
CLASS_CLASS_NAME,
NO_SCHEMA,
CLSID_NWCOMPATClass,
dwObjectState );
BAIL_ON_FAILURE(hr);
hr = pClass->QueryInterface( riid, ppvObj );
BAIL_ON_FAILURE(hr);
pClass->Release();
RRETURN(hr);
error:
if ( bstrTmp != NULL )
CoTaskMemFree( bstrTmp );
delete pClass;
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATClass::QueryInterface(REFIID iid, LPVOID FAR* ppv)
{
if (ppv == NULL) {
RRETURN(E_POINTER);
}
if (IsEqualIID(iid, IID_IUnknown))
{
*ppv = (IADsClass FAR * ) this;
}
else if (IsEqualIID(iid, IID_IDispatch))
{
*ppv = (IADs FAR *) this;
}
else if (IsEqualIID(iid, IID_ISupportErrorInfo))
{
*ppv = (ISupportErrorInfo FAR *) this;
}
else if (IsEqualIID(iid, IID_IADs))
{
*ppv = (IADs FAR *) this;
}
else if (IsEqualIID(iid, IID_IADsClass))
{
*ppv = (IADsClass FAR *) this;
}
else
{
*ppv = NULL;
return E_NOINTERFACE;
}
AddRef();
return NOERROR;
}
/* ISupportErrorInfo method */
STDMETHODIMP
CNWCOMPATClass::InterfaceSupportsErrorInfo(
THIS_ REFIID riid
)
{
if (IsEqualIID(riid, IID_IADs) ||
IsEqualIID(riid, IID_IADsClass)) {
RRETURN(S_OK);
} else {
RRETURN(S_FALSE);
}
}
/* IADs methods */
STDMETHODIMP
CNWCOMPATClass::SetInfo(THIS)
{
RRETURN_EXP_IF_ERR(E_NOTIMPL);
}
STDMETHODIMP
CNWCOMPATClass::GetInfo(THIS)
{
RRETURN(S_OK);
}
/* IADsClass methods */
STDMETHODIMP
CNWCOMPATClass::get_PrimaryInterface( THIS_ BSTR FAR *pbstrGUID )
{
HRESULT hr;
if ( !pbstrGUID )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
hr = ADsAllocString( _bstrPrimaryInterface, pbstrGUID );
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATClass::get_CLSID( THIS_ BSTR FAR *pbstrCLSID )
{
HRESULT hr;
if ( !pbstrCLSID )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
hr = ADsAllocString( _bstrCLSID, pbstrCLSID );
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATClass::put_CLSID( THIS_ BSTR bstrCLSID )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATClass::get_OID( THIS_ BSTR FAR *pbstrOID )
{
HRESULT hr;
if ( !pbstrOID )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
hr = ADsAllocString( _bstrOID, pbstrOID );
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATClass::put_OID( THIS_ BSTR bstrOID )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATClass::get_Abstract( THIS_ VARIANT_BOOL FAR *pfAbstract )
{
if ( !pfAbstract )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
*pfAbstract = _fAbstract? VARIANT_TRUE : VARIANT_FALSE;
RRETURN(S_OK);
}
STDMETHODIMP
CNWCOMPATClass::put_Abstract( THIS_ VARIANT_BOOL fAbstract )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATClass::get_Auxiliary( THIS_ VARIANT_BOOL FAR *pfAuxiliary )
{
if ( !pfAuxiliary )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
*pfAuxiliary = VARIANT_FALSE;
RRETURN(S_OK);
}
STDMETHODIMP
CNWCOMPATClass::put_Auxiliary( THIS_ VARIANT_BOOL fAuxiliary )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATClass::get_MandatoryProperties( THIS_ VARIANT FAR *pvMandatoryProperties )
{
HRESULT hr;
VariantInit( pvMandatoryProperties );
hr = VariantCopy( pvMandatoryProperties, &_vMandatoryProperties );
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATClass::put_MandatoryProperties( THIS_ VARIANT vMandatoryProperties )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATClass::get_DerivedFrom( THIS_ VARIANT FAR *pvDerivedFrom )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATClass::put_DerivedFrom( THIS_ VARIANT vDerivedFrom )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATClass::get_AuxDerivedFrom( THIS_ VARIANT FAR *pvAuxDerivedFrom )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATClass::put_AuxDerivedFrom( THIS_ VARIANT vAuxDerivedFrom )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATClass::get_PossibleSuperiors( THIS_ VARIANT FAR *pvPossSuperiors )
{
HRESULT hr;
VariantInit( pvPossSuperiors );
hr = VariantCopy( pvPossSuperiors, &_vPossSuperiors );
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATClass::put_PossibleSuperiors( THIS_ VARIANT vPossSuperiors )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATClass::get_Containment( THIS_ VARIANT FAR *pvContainment )
{
HRESULT hr;
VariantInit( pvContainment );
hr = VariantCopy( pvContainment, &_vContainment );
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATClass::put_Containment( THIS_ VARIANT vContainment )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATClass::get_Container( THIS_ VARIANT_BOOL FAR *pfContainer )
{
if ( !pfContainer )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
*pfContainer = _fContainer? VARIANT_TRUE : VARIANT_FALSE;
RRETURN(S_OK);
}
STDMETHODIMP
CNWCOMPATClass::put_Container( THIS_ VARIANT_BOOL fContainer )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATClass::get_HelpFileName( THIS_ BSTR FAR *pbstrHelpFileName )
{
HRESULT hr;
if ( !pbstrHelpFileName )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
hr = ADsAllocString( _bstrHelpFileName, pbstrHelpFileName );
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATClass::put_HelpFileName( THIS_ BSTR bstrHelpFile )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATClass::get_HelpFileContext( THIS_ long FAR *plHelpContext )
{
if ( !plHelpContext )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
*plHelpContext = _lHelpFileContext;
RRETURN(S_OK);
}
STDMETHODIMP
CNWCOMPATClass::put_HelpFileContext( THIS_ long lHelpContext )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATClass::Qualifiers(THIS_ IADsCollection FAR* FAR* ppQualifiers)
{
RRETURN_EXP_IF_ERR(E_NOTIMPL);
}
HRESULT
CNWCOMPATClass::AllocateClassObject(CNWCOMPATClass FAR * FAR * ppClass)
{
CNWCOMPATClass FAR *pClass = NULL;
CAggregatorDispMgr FAR *pDispMgr = NULL;
HRESULT hr = S_OK;
pClass = new CNWCOMPATClass();
if ( pClass == NULL )
hr = E_OUTOFMEMORY;
BAIL_ON_FAILURE(hr);
pDispMgr = new CAggregatorDispMgr;
if ( pDispMgr == NULL )
hr = E_OUTOFMEMORY;
BAIL_ON_FAILURE(hr);
hr = LoadTypeInfoEntry( pDispMgr,
LIBID_ADs,
IID_IADs,
(IADs *) pClass,
DISPID_REGULAR );
BAIL_ON_FAILURE(hr);
hr = LoadTypeInfoEntry( pDispMgr,
LIBID_ADs,
IID_IADsClass,
(IADsClass *) pClass,
DISPID_REGULAR );
BAIL_ON_FAILURE(hr);
pClass->_pDispMgr = pDispMgr;
*ppClass = pClass;
RRETURN(hr);
error:
delete pDispMgr;
delete pClass;
RRETURN(hr);
}
/******************************************************************/
/* Class CNWCOMPATProperty
/******************************************************************/
DEFINE_IDispatch_Implementation(CNWCOMPATProperty)
DEFINE_IADs_Implementation(CNWCOMPATProperty)
CNWCOMPATProperty::CNWCOMPATProperty()
: _pDispMgr( NULL ),
_bstrOID( NULL ),
_bstrSyntax( NULL ),
_lMaxRange( 0 ),
_lMinRange( 0 ),
_fMultiValued( FALSE )
{
ENLIST_TRACKING(CNWCOMPATProperty);
}
CNWCOMPATProperty::~CNWCOMPATProperty()
{
if ( _bstrOID ) {
ADsFreeString( _bstrOID );
}
if ( _bstrSyntax ) {
ADsFreeString( _bstrSyntax );
}
delete _pDispMgr;
}
HRESULT
CNWCOMPATProperty::CreateProperty(
BSTR bstrParent,
PROPERTYINFO *pPropertyInfo,
DWORD dwObjectState,
REFIID riid,
void **ppvObj
)
{
CNWCOMPATProperty FAR * pProperty = NULL;
HRESULT hr = S_OK;
hr = AllocatePropertyObject( &pProperty );
BAIL_ON_FAILURE(hr);
hr = ADsAllocString( pPropertyInfo->bstrOID, &pProperty->_bstrOID);
BAIL_ON_FAILURE(hr);
hr = ADsAllocString( pPropertyInfo->bstrSyntax, &pProperty->_bstrSyntax);
BAIL_ON_FAILURE(hr);
pProperty->_lMaxRange = pPropertyInfo->lMaxRange;
pProperty->_lMinRange = pPropertyInfo->lMinRange;
pProperty->_fMultiValued = (VARIANT_BOOL) pPropertyInfo->fMultiValued;
hr = pProperty->InitializeCoreObject(
bstrParent,
pPropertyInfo->szPropertyName,
PROPERTY_CLASS_NAME,
NO_SCHEMA,
CLSID_NWCOMPATProperty,
dwObjectState );
BAIL_ON_FAILURE(hr);
hr = pProperty->QueryInterface( riid, ppvObj );
BAIL_ON_FAILURE(hr);
pProperty->Release();
RRETURN(hr);
error:
delete pProperty;
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATProperty::QueryInterface(REFIID iid, LPVOID FAR* ppv)
{
if (ppv == NULL) {
RRETURN(E_POINTER);
}
if (IsEqualIID(iid, IID_IUnknown))
{
*ppv = (IADsProperty FAR *) this;
}
else if (IsEqualIID(iid, IID_IDispatch))
{
*ppv = (IADs FAR *) this;
}
else if (IsEqualIID(iid, IID_ISupportErrorInfo))
{
*ppv = (ISupportErrorInfo FAR *) this;
}
else if (IsEqualIID(iid, IID_IADs))
{
*ppv = (IADs FAR *) this;
}
else if (IsEqualIID(iid, IID_IADsProperty))
{
*ppv = (IADsProperty FAR *) this;
}
else
{
*ppv = NULL;
return E_NOINTERFACE;
}
AddRef();
return NOERROR;
}
/* ISupportErrorInfo method */
STDMETHODIMP
CNWCOMPATProperty::InterfaceSupportsErrorInfo(
THIS_ REFIID riid
)
{
if (IsEqualIID(riid, IID_IADs) ||
IsEqualIID(riid, IID_IADsProperty)) {
RRETURN(S_OK);
} else {
RRETURN(S_FALSE);
}
}
/* IADs methods */
STDMETHODIMP
CNWCOMPATProperty::SetInfo(THIS)
{
RRETURN_EXP_IF_ERR(E_NOTIMPL);
}
STDMETHODIMP
CNWCOMPATProperty::GetInfo(THIS)
{
RRETURN(S_OK);
}
/* IADsProperty methods */
STDMETHODIMP
CNWCOMPATProperty::get_OID( THIS_ BSTR FAR *pbstrOID )
{
HRESULT hr;
if ( !pbstrOID )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
hr = ADsAllocString( _bstrOID, pbstrOID );
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATProperty::put_OID( THIS_ BSTR bstrOID )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATProperty::get_Syntax( THIS_ BSTR FAR *pbstrSyntax )
{
HRESULT hr;
if ( !pbstrSyntax )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
hr = ADsAllocString( _bstrSyntax, pbstrSyntax );
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATProperty::put_Syntax( THIS_ BSTR bstrSyntax )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATProperty::get_MaxRange( THIS_ long FAR *plMaxRange )
{
if ( !plMaxRange )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
*plMaxRange = _lMaxRange;
RRETURN(S_OK);
}
STDMETHODIMP
CNWCOMPATProperty::put_MaxRange( THIS_ long lMaxRange )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATProperty::get_MinRange( THIS_ long FAR *plMinRange )
{
if ( !plMinRange )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
*plMinRange = _lMinRange;
RRETURN(S_OK);
}
STDMETHODIMP
CNWCOMPATProperty::put_MinRange( THIS_ long lMinRange )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATProperty::get_MultiValued( THIS_ VARIANT_BOOL FAR *pfMultiValued )
{
if ( !pfMultiValued )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
*pfMultiValued = _fMultiValued? VARIANT_TRUE: VARIANT_FALSE;
RRETURN(S_OK);
}
STDMETHODIMP
CNWCOMPATProperty::put_MultiValued( THIS_ VARIANT_BOOL fMultiValued )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CNWCOMPATProperty::Qualifiers(THIS_ IADsCollection FAR* FAR* ppQualifiers)
{
RRETURN_EXP_IF_ERR(E_NOTIMPL);
}
HRESULT
CNWCOMPATProperty::AllocatePropertyObject(CNWCOMPATProperty FAR * FAR * ppProperty)
{
CNWCOMPATProperty FAR *pProperty = NULL;
CAggregatorDispMgr FAR *pDispMgr = NULL;
HRESULT hr = S_OK;
pProperty = new CNWCOMPATProperty();
if ( pProperty == NULL )
hr = E_OUTOFMEMORY;
BAIL_ON_FAILURE(hr);
pDispMgr = new CAggregatorDispMgr;
if ( pDispMgr == NULL )
hr = E_OUTOFMEMORY;
BAIL_ON_FAILURE(hr);
hr = LoadTypeInfoEntry( pDispMgr,
LIBID_ADs,
IID_IADs,
(IADs *) pProperty,
DISPID_REGULAR );
BAIL_ON_FAILURE(hr);
hr = LoadTypeInfoEntry( pDispMgr,
LIBID_ADs,
IID_IADsProperty,
(IADsProperty *) pProperty,
DISPID_REGULAR );
BAIL_ON_FAILURE(hr);
pProperty->_pDispMgr = pDispMgr;
*ppProperty = pProperty;
RRETURN(hr);
error:
delete pDispMgr;
delete pProperty;
RRETURN(hr);
}
/******************************************************************/
/* Class CNWCOMPATSyntax
/******************************************************************/
DEFINE_IDispatch_Implementation(CNWCOMPATSyntax)
DEFINE_IADs_Implementation(CNWCOMPATSyntax)
CNWCOMPATSyntax::CNWCOMPATSyntax()
{
ENLIST_TRACKING(CNWCOMPATSyntax);
}
CNWCOMPATSyntax::~CNWCOMPATSyntax()
{
delete _pDispMgr;
}
HRESULT
CNWCOMPATSyntax::CreateSyntax(
BSTR bstrParent,
SYNTAXINFO *pSyntaxInfo,
DWORD dwObjectState,
REFIID riid,
void **ppvObj
)
{
CNWCOMPATSyntax FAR *pSyntax = NULL;
HRESULT hr = S_OK;
hr = AllocateSyntaxObject( &pSyntax );
BAIL_ON_FAILURE(hr);
hr = pSyntax->InitializeCoreObject(
bstrParent,
pSyntaxInfo->bstrName,
SYNTAX_CLASS_NAME,
NO_SCHEMA,
CLSID_NWCOMPATSyntax,
dwObjectState );
BAIL_ON_FAILURE(hr);
pSyntax->_lOleAutoDataType = pSyntaxInfo->lOleAutoDataType;
hr = pSyntax->QueryInterface( riid, ppvObj );
BAIL_ON_FAILURE(hr);
pSyntax->Release();
RRETURN(hr);
error:
delete pSyntax;
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATSyntax::QueryInterface(REFIID iid, LPVOID FAR* ppv)
{
if (ppv == NULL) {
RRETURN(E_POINTER);
}
if (IsEqualIID(iid, IID_IUnknown))
{
*ppv = (IADs FAR *) this;
}
else if (IsEqualIID(iid, IID_IDispatch))
{
*ppv = (IADs FAR *) this;
}
else if (IsEqualIID(iid, IID_ISupportErrorInfo))
{
*ppv = (ISupportErrorInfo FAR *) this;
}
else if (IsEqualIID(iid, IID_IADs))
{
*ppv = (IADs FAR *) this;
}
else if (IsEqualIID(iid, IID_IADsSyntax))
{
*ppv = (IADsSyntax FAR *) this;
}
else
{
*ppv = NULL;
return E_NOINTERFACE;
}
AddRef();
return NOERROR;
}
/* ISupportErrorInfo method */
STDMETHODIMP
CNWCOMPATSyntax::InterfaceSupportsErrorInfo(
THIS_ REFIID riid
)
{
if (IsEqualIID(riid, IID_IADs) ||
IsEqualIID(riid, IID_IADsSyntax)) {
RRETURN(S_OK);
} else {
RRETURN(S_FALSE);
}
}
/* IADs methods */
STDMETHODIMP
CNWCOMPATSyntax::SetInfo(THIS)
{
RRETURN_EXP_IF_ERR(E_NOTIMPL);
}
STDMETHODIMP
CNWCOMPATSyntax::GetInfo(THIS)
{
RRETURN(S_OK);
}
HRESULT
CNWCOMPATSyntax::AllocateSyntaxObject(CNWCOMPATSyntax FAR * FAR * ppSyntax)
{
CNWCOMPATSyntax FAR *pSyntax = NULL;
CAggregatorDispMgr FAR *pDispMgr = NULL;
HRESULT hr = S_OK;
pSyntax = new CNWCOMPATSyntax();
if ( pSyntax == NULL )
hr = E_OUTOFMEMORY;
BAIL_ON_FAILURE(hr);
pDispMgr = new CAggregatorDispMgr;
if ( pDispMgr == NULL )
hr = E_OUTOFMEMORY;
BAIL_ON_FAILURE(hr);
hr = LoadTypeInfoEntry( pDispMgr,
LIBID_ADs,
IID_IADsSyntax,
(IADsSyntax *) pSyntax,
DISPID_REGULAR );
BAIL_ON_FAILURE(hr);
pSyntax->_pDispMgr = pDispMgr;
*ppSyntax = pSyntax;
RRETURN(hr);
error:
delete pDispMgr;
delete pSyntax;
RRETURN(hr);
}
STDMETHODIMP
CNWCOMPATSyntax::get_OleAutoDataType( THIS_ long FAR *plOleAutoDataType )
{
if ( !plOleAutoDataType )
RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER);
*plOleAutoDataType = _lOleAutoDataType;
RRETURN(S_OK);
}
STDMETHODIMP
CNWCOMPATSyntax::put_OleAutoDataType( THIS_ long lOleAutoDataType )
{
RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED);
}
/******************************************************************/
/* Misc Helpers
/******************************************************************/
HRESULT
MakeVariantFromStringList(
BSTR bstrList,
VARIANT *pvVariant
)
{
HRESULT hr = S_OK;
SAFEARRAY *aList = NULL;
SAFEARRAYBOUND aBound;
BSTR pszTempList = NULL;
if ( bstrList != NULL )
{
long i = 0;
long nCount = 1;
TCHAR c;
BSTR pszSrc;
hr = ADsAllocString( bstrList, &pszTempList );
BAIL_ON_FAILURE(hr);
while ( c = pszTempList[i] )
{
if ( c == TEXT(','))
{
pszTempList[i] = 0;
nCount++;
}
i++;
}
aBound.lLbound = 0;
aBound.cElements = nCount;
aList = SafeArrayCreate( VT_VARIANT, 1, &aBound );
if ( aList == NULL )
{
hr = E_OUTOFMEMORY;
BAIL_ON_FAILURE(hr);
}
pszSrc = pszTempList;
for ( i = 0; i < nCount; i++ )
{
VARIANT v;
VariantInit(&v);
V_VT(&v) = VT_BSTR;
hr = ADsAllocString( pszSrc, &(V_BSTR(&v)));
BAIL_ON_FAILURE(hr);
hr = SafeArrayPutElement( aList,
&i,
&v );
VariantClear(&v);
BAIL_ON_FAILURE(hr);
pszSrc += _tcslen( pszSrc ) + 1;
}
VariantInit( pvVariant );
V_VT(pvVariant) = VT_ARRAY | VT_VARIANT;
V_ARRAY(pvVariant) = aList;
ADsFreeString( pszTempList );
pszTempList = NULL;
}
else
{
aBound.lLbound = 0;
aBound.cElements = 0;
aList = SafeArrayCreate( VT_VARIANT, 1, &aBound );
if ( aList == NULL )
{
hr = E_OUTOFMEMORY;
BAIL_ON_FAILURE(hr);
}
VariantInit( pvVariant );
V_VT(pvVariant) = VT_ARRAY | VT_VARIANT;
V_ARRAY(pvVariant) = aList;
}
RRETURN(S_OK);
error:
if ( pszTempList )
ADsFreeString( pszTempList );
if ( aList )
SafeArrayDestroy( aList );
return hr;
}
STDMETHODIMP
CNWCOMPATClass::get_OptionalProperties( THIS_ VARIANT FAR *retval )
{
HRESULT hr;
VariantInit( retval);
hr = VariantCopy( retval, &_vOptionalProperties );
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATClass::put_OptionalProperties( THIS_ VARIANT vOptionalProperties )
{
HRESULT hr = E_NOTIMPL;
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CNWCOMPATClass::get_NamingProperties( THIS_ VARIANT FAR *retval )
{
RRETURN_EXP_IF_ERR(E_NOTIMPL);
}
STDMETHODIMP
CNWCOMPATClass::put_NamingProperties( THIS_ VARIANT vNamingProperties )
{
RRETURN_EXP_IF_ERR(E_NOTIMPL);
}
| 22.416131 | 84 | 0.595128 |
21132bbe7dbd51afb2918827974fcddfdb3c2dcb | 269 | cpp | C++ | Linked List Exercises/Ex1/Ex1 - SingleLinkedList/CNode.cpp | ferp132/math | 96f765b93554a2ad3a279575d6c60b1107b0bf35 | [
"MIT"
] | null | null | null | Linked List Exercises/Ex1/Ex1 - SingleLinkedList/CNode.cpp | ferp132/math | 96f765b93554a2ad3a279575d6c60b1107b0bf35 | [
"MIT"
] | null | null | null | Linked List Exercises/Ex1/Ex1 - SingleLinkedList/CNode.cpp | ferp132/math | 96f765b93554a2ad3a279575d6c60b1107b0bf35 | [
"MIT"
] | null | null | null | #include "CNode.h"
CNode::CNode()
{
}
void CNode::SetData(int iData)
{
data = iData;
}
int CNode::GetData() const
{
return data;
}
void CNode::SetNextNode(CNode *newnextNode)
{
nextNode = newnextNode;
}
CNode * CNode::GetNextNode() const
{
return nextNode;
}
| 9.962963 | 43 | 0.672862 |
2115560a3bd1e622ef0aad2f7fa0b18a961e5632 | 4,829 | cpp | C++ | src/brdf/LitSphereWindow.cpp | davidlee80/GI | 820ccba1323daaff3453e61f679ee04ed36a91b9 | [
"MS-PL"
] | 1 | 2022-03-16T01:41:13.000Z | 2022-03-16T01:41:13.000Z | src/brdf/LitSphereWindow.cpp | davidlee80/GI | 820ccba1323daaff3453e61f679ee04ed36a91b9 | [
"MS-PL"
] | null | null | null | src/brdf/LitSphereWindow.cpp | davidlee80/GI | 820ccba1323daaff3453e61f679ee04ed36a91b9 | [
"MS-PL"
] | null | null | null | /*
Copyright Disney Enterprises, Inc. All rights reserved.
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have
the same meaning here as under U.S. copyright law. A "contribution" is the original
software, or any additions or changes to the software. A "contributor" is any person
that distributes its contribution under this license. "Licensed patents" are a
contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license
conditions and limitations in section 3, each contributor grants you a non-exclusive,
worldwide, royalty-free copyright license to reproduce its contribution, prepare
derivative works of its contribution, and distribute its contribution or any derivative
works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license
conditions and limitations in section 3, each contributor grants you a non-exclusive,
worldwide, royalty-free license under its licensed patents to make, have made,
use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the
software or derivative works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any
contributors' name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim
are infringed by the software, your patent license from such contributor to the
software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright,
patent, trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do
so only under this license by including a complete copy of this license with your
distribution. If you distribute any portion of the software in compiled or object code
form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors
give no express warranties, guarantees or conditions. You may have additional
consumer rights under your local laws which this license cannot change.
To the extent permitted under your local laws, the contributors exclude the
implied warranties of merchantability, fitness for a particular purpose and non-
infringement.
*/
#include <QtGui>
#include <QCheckBox>
#include "LitSphereWindow.h"
#include "LitSphereWidget.h"
#include "ParameterWindow.h"
#include "FloatVarWidget.h"
LitSphereWindow::LitSphereWindow( ParameterWindow* paramWindow )
{
glWidget = new LitSphereWidget( this, paramWindow->getBRDFList() );
// so we can tell the parameter window when the incident vector changes (from dragging on the sphere)
connect( glWidget, SIGNAL(incidentVectorChanged( float, float )), paramWindow, SLOT(incidentVectorChanged( float, float )) );
connect( paramWindow, SIGNAL(incidentDirectionChanged(float,float)), glWidget, SLOT(incidentDirectionChanged(float,float)) );
connect( paramWindow, SIGNAL(brdfListChanged(std::vector<brdfPackage>)), glWidget, SLOT(brdfListChanged(std::vector<brdfPackage>)) );
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(glWidget);
QHBoxLayout *buttonLayout = new QHBoxLayout;
mainLayout->addLayout(buttonLayout);
doubleTheta = new QCheckBox( "Double theta" );
doubleTheta->setChecked( true );
connect( doubleTheta, SIGNAL(stateChanged(int)), glWidget, SLOT(doubleThetaChanged(int)) );
buttonLayout->addWidget(doubleTheta);
useNDotL = new QCheckBox( "Multiply by N . L" );
useNDotL->setChecked( true );
connect( useNDotL, SIGNAL(stateChanged(int)), glWidget, SLOT(useNDotLChanged(int)) );
buttonLayout->addWidget(useNDotL);
FloatVarWidget* fv;
#if 0
fv = new FloatVarWidget("Brightness", 0, 100.0, 1.0);
connect(fv, SIGNAL(valueChanged(float)), glWidget, SLOT(brightnessChanged(float)));
mainLayout->addWidget(fv);
#endif
fv = new FloatVarWidget("Gamma", 1.0, 5.0, 2.2);
connect(fv, SIGNAL(valueChanged(float)), glWidget, SLOT(gammaChanged(float)));
mainLayout->addWidget(fv);
fv = new FloatVarWidget("Exposure", -6.0, 6.0, 0.0);
connect(fv, SIGNAL(valueChanged(float)), glWidget, SLOT(exposureChanged(float)));
mainLayout->addWidget(fv);
setLayout(mainLayout);
setWindowTitle( "Lit Sphere" );
}
void LitSphereWindow::setShowing( bool s )
{
if( glWidget )
glWidget->setShowing( s );
}
| 44.302752 | 137 | 0.75937 |
2115d2997d7bdca32560608377c3a692242d4c9c | 1,404 | cpp | C++ | shader.cpp | a12n/rematrix | e539a5573a99665ba7b21e1c2114508060dcd163 | [
"MIT"
] | 2 | 2022-01-15T16:27:05.000Z | 2022-01-15T16:48:03.000Z | shader.cpp | a12n/rematrix | e539a5573a99665ba7b21e1c2114508060dcd163 | [
"MIT"
] | null | null | null | shader.cpp | a12n/rematrix | e539a5573a99665ba7b21e1c2114508060dcd163 | [
"MIT"
] | null | null | null | #include "shader.hpp"
namespace rematrix {
shader::shader(GLenum type) :
id{glCreateShader(type)}
{
if (id == 0) {
throw runtime_error("couldn't create shader");
}
}
shader::shader(shader&& other) noexcept :
id{other.id}
{
const_cast<GLuint&>(other.id) = 0;
}
shader::~shader()
{
glDeleteShader(id);
}
shader&
shader::operator=(shader&& other) noexcept
{
const_cast<GLuint&>(id) = other.id;
const_cast<GLuint&>(other.id) = 0;
return *this;
}
void
shader::compile(const char* src)
{
glShaderSource(id, 1, &src, nullptr);
glCompileShader(id);
GLint ok;
glGetShaderiv(id, GL_COMPILE_STATUS, &ok);
if (! ok) {
GLint length;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
string log(length, '\0');
glGetShaderInfoLog(id, length, nullptr, log.data());
throw runtime_error(log);
}
}
//----------------------------------------------------------------------------
vertex_shader::vertex_shader() :
shader{GL_VERTEX_SHADER}
{
}
vertex_shader::vertex_shader(const char* src) :
vertex_shader()
{
compile(src);
}
//----------------------------------------------------------------------------
fragment_shader::fragment_shader() :
shader{GL_FRAGMENT_SHADER}
{
}
fragment_shader::fragment_shader(const char* src) :
fragment_shader()
{
compile(src);
}
} // namespace rematrix
| 18.72 | 78 | 0.569088 |
21183747e45a590a7bcb6551ed6718d017a80d99 | 181,084 | cxx | C++ | inetcore/winhttp/v5.1/ihttprequest/httprequest.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetcore/winhttp/v5.1/ihttprequest/httprequest.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetcore/winhttp/v5.1/ihttprequest/httprequest.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*
* HttpRequest.cxx
*
* WinHttp.WinHttpRequest COM component
*
* Copyright (C) 2000 Microsoft Corporation. All rights reserved. *
*
* Much of this code was stolen from our Xml-Http friends over in
* inetcore\xml\http\xmlhttp.cxx. Thanks very much!
*
*/
#include <wininetp.h>
#include "httprequest.hxx"
#include <olectl.h>
#include "EnumConns.hxx" //IEnumConnections implementator
#include "EnumCP.hxx" //IEnumConnectionPoints implementator
#include "multilang.hxx"
/////////////////////////////////////////////////////////////////////////////
// private function prototypes
static void PreWideCharToUtf8(WCHAR * buffer, UINT cch, UINT * cb, bool * bSimpleConversion);
static void WideCharToUtf8(WCHAR * buffer, UINT cch, BYTE * bytebuffer, bool bSimpleConversion);
static HRESULT BSTRToUTF8(char ** psz, DWORD * pcbUTF8, BSTR bstr, bool * pbSetUtf8Charset);
static HRESULT AsciiToBSTR(BSTR * pbstr, char * sz, int cch);
static HRESULT GetBSTRFromVariant(VARIANT varVariant, BSTR * pBstr);
static BOOL GetBoolFromVariant(VARIANT varVariant, BOOL fDefault);
static DWORD GetDwordFromVariant(VARIANT varVariant, DWORD dwDefault);
static long GetLongFromVariant(VARIANT varVariant, long lDefault);
static HRESULT CreateVector(VARIANT * pVar, const BYTE * pData, DWORD cElems);
static HRESULT ReadFromStream(char ** ppData, ULONG * pcbData, IStream * pStm);
static void MessageLoop();
static DWORD UpdateTimeout(DWORD dwTimeout, DWORD dwStartTime);
static HRESULT FillExcepInfo(HRESULT hr, EXCEPINFO * pExcepInfo);
static BOOL IsValidVariant(VARIANT v);
static HRESULT ParseSelectedCert(BSTR bstrSelection,
LPBOOL pfLocalMachine,
BSTR *pbstrStore,
BSTR *pbstrSubject);
static BOOL GetContentLengthIfResponseNotChunked(HINTERNET hHttpRequest,
DWORD * pdwContentLength);
static HRESULT SecureFailureFromStatus(DWORD dwFlags);
static BOOL s_fWndClassRegistered;
// Change the name of the window class for each new version of WinHTTP
static const char * s_szWinHttpEventMarshallerWndClass = "_WinHttpEventMarshaller51";
static CMimeInfoCache* g_pMimeInfoCache = NULL;
BOOL IsValidHeaderName(LPCWSTR lpszHeaderName);
#define SafeRelease(p) \
{ \
if (p) \
(p)->Release();\
(p) = NULL;\
}
#ifndef HWND_MESSAGE
#define HWND_MESSAGE ((HWND)-3)
#endif
#define SIZEOF_BUFFER (8192)
inline BOOL IsValidBstr(BSTR bstr)
{
return (bstr == NULL) || (!IsBadStringPtrW(bstr, (UINT_PTR)-1));
}
#ifndef WINHTTP_STATIC_LIBRARY
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, void ** ppv)
{
if (rclsid != CLSID_WinHttpRequest)
return CLASS_E_CLASSNOTAVAILABLE;
if (!WinHttpCheckPlatform())
return CLASS_E_CLASSNOTAVAILABLE;
if (riid != IID_IClassFactory || ppv == NULL)
return E_INVALIDARG;
CClassFactory * pCF = New CClassFactory();
if (pCF)
{
*ppv = static_cast<IClassFactory *>(pCF);
pCF->AddRef();
return NOERROR;
}
else
{
*ppv = NULL;
return E_OUTOFMEMORY;
}
}
CClassFactory::CClassFactory()
{
_cRefs = 0;
InterlockedIncrement(&g_cSessionCount);
}
STDMETHODIMP CClassFactory::QueryInterface(REFIID riid, void ** ppvObject)
{
if (ppvObject == NULL)
return E_INVALIDARG;
if (riid == IID_IClassFactory || riid == IID_IUnknown)
{
*ppvObject = static_cast<IClassFactory *>(this);
AddRef();
return NOERROR;
}
else
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE CClassFactory::AddRef()
{
return ++_cRefs;
}
ULONG STDMETHODCALLTYPE CClassFactory::Release()
{
if (--_cRefs == 0)
{
delete this;
InterlockedDecrement(&g_cSessionCount);
return 0;
}
return _cRefs;
}
STDMETHODIMP
CClassFactory::CreateInstance(IUnknown * pUnkOuter, REFIID riid, void ** ppvObject)
{
if (pUnkOuter != NULL)
return CLASS_E_NOAGGREGATION;
if (ppvObject == NULL)
return E_INVALIDARG;
if( !DelayLoad(&g_moduleOle32)
|| !DelayLoad(&g_moduleOleAut32))
{
return E_UNEXPECTED;
}
return CreateHttpRequest(riid, ppvObject);
}
STDMETHODIMP
CClassFactory::LockServer(BOOL fLock)
{
if (fLock)
InterlockedIncrement(&g_cSessionCount);
else
InterlockedDecrement(&g_cSessionCount);
return NOERROR;
}
STDAPI DllCanUnloadNow()
{
return ((g_cSessionCount == 0) && (g_pAsyncCount == NULL || g_pAsyncCount->GetRef() == 0)) ? S_OK : S_FALSE;
}
#else
STDAPI WinHttpCreateHttpRequestComponent(REFIID riid, void ** ppvObject)
{
return CreateHttpRequest(riid, ppvObject);
}
#endif //WINHTTP_STATIC_LIBRARY
STDMETHODIMP
CreateHttpRequest(REFIID riid, void ** ppvObject)
{
CHttpRequest * pHttpRequest = New CHttpRequest();
HRESULT hr;
if (pHttpRequest)
{
hr = pHttpRequest->QueryInterface(riid, ppvObject);
if (FAILED(hr))
{
delete pHttpRequest;
}
}
else
hr = E_OUTOFMEMORY;
return hr;
}
/*
* CHttpRequest::CHttpRequest constructor
*
*/
CHttpRequest::CHttpRequest()
{
InterlockedIncrement(&g_cSessionCount);
Initialize();
}
/*
* CHttpRequest::~CHttpRequest destructor
*
*/
CHttpRequest::~CHttpRequest()
{
ReleaseResources();
InterlockedDecrement(&g_cSessionCount);
}
#define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \
const type name = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
MIDL_DEFINE_GUID(IID, IID_IWinHttpRequest_TechBeta,0x06f29373,0x5c5a,0x4b54,0xb0,0x25,0x6e,0xf1,0xbf,0x8a,0xbf,0x0e);
MIDL_DEFINE_GUID(IID, IID_IWinHttpRequestEvents_TechBeta,0xcff7bd4c,0x6689,0x4bbe,0x91,0xc2,0x0f,0x55,0x9e,0x8b,0x88,0xa7);
HRESULT STDMETHODCALLTYPE
CHttpRequest::QueryInterface(REFIID riid, void ** ppv)
{
HRESULT hr = NOERROR;
if (ppv == NULL)
{
hr = E_INVALIDARG;
}
else if (riid == IID_IWinHttpRequest ||
riid == IID_IDispatch ||
riid == IID_IWinHttpRequest_TechBeta ||
riid == IID_IUnknown)
{
*ppv = static_cast<IWinHttpRequest *>(this);
AddRef();
}
else if (riid == IID_IConnectionPointContainer)
{
*ppv = static_cast<IConnectionPointContainer *>(this);
AddRef();
}
else if (riid == IID_ISupportErrorInfo)
{
*ppv = static_cast<ISupportErrorInfo *>(this);
AddRef();
}
else if (riid == IID_IProvideClassInfo)
{
*ppv = static_cast<IProvideClassInfo *>(static_cast<IProvideClassInfo2 *>(this));
AddRef();
}
else if (riid == IID_IProvideClassInfo2)
{
*ppv = static_cast<IProvideClassInfo2 *>(this);
AddRef();
}
else
hr = E_NOINTERFACE;
return hr;
}
ULONG STDMETHODCALLTYPE
CHttpRequest::AddRef()
{
if (GetCurrentThreadId() == _dwMainThreadId)
++_cRefsOnMainThread;
return InterlockedIncrement(&_cRefs);
}
ULONG STDMETHODCALLTYPE
CHttpRequest::Release()
{
if (GetCurrentThreadId() == _dwMainThreadId)
{
if ((--_cRefsOnMainThread == 0) && _fAsync)
{
// Clean up the Event Marshaller. This must be done
// on the main thread.
_CP.ShutdownEventSinksMarshaller();
// If the worker thread is still running, abort it
// and wait for it to run down.
Abort();
}
}
DWORD cRefs = InterlockedDecrement(&_cRefs);
if (cRefs == 0)
{
delete this;
return 0;
}
else
return cRefs;
}
HRESULT
CHttpRequest::GetHttpRequestTypeInfo(REFGUID guid, ITypeInfo ** ppTypeInfo)
{
HRESULT hr = NOERROR;
ITypeLib * pTypeLib;
char szPath[MAX_PATH+1];
OLECHAR wszPath[MAX_PATH+1];
GetModuleFileName(GlobalDllHandle, szPath, sizeof(szPath)-1); // leave room for null char
szPath[sizeof(szPath)-1] = '\0'; // guarantee null-termination
MultiByteToWideChar(CP_ACP, 0, szPath, -1, wszPath, MAX_PATH);
hr = DL(LoadTypeLib)(wszPath, &pTypeLib);
if (SUCCEEDED(hr))
{
hr = pTypeLib->GetTypeInfoOfGuid(guid, ppTypeInfo);
pTypeLib->Release();
}
return hr;
}
STDMETHODIMP
CHttpRequest::GetTypeInfoCount(UINT * pctinfo)
{
if (!pctinfo)
return E_INVALIDARG;
*pctinfo = 1;
return NOERROR;
}
STDMETHODIMP
CHttpRequest::GetTypeInfo(UINT iTInfo, LCID, ITypeInfo ** ppTInfo)
{
if (!ppTInfo)
return E_INVALIDARG;
*ppTInfo = NULL;
if (iTInfo != 0)
return DISP_E_BADINDEX;
if (!_pTypeInfo)
{
HRESULT hr = GetHttpRequestTypeInfo(IID_IWinHttpRequest, &_pTypeInfo);
if (FAILED(hr))
return hr;
}
*ppTInfo = _pTypeInfo;
_pTypeInfo->AddRef();
return NOERROR;
}
struct IDMAPPING
{
const OLECHAR * wszMemberName;
DISPID dispId;
};
static const IDMAPPING IdMapping[] =
{
{ L"Open", DISPID_HTTPREQUEST_OPEN },
{ L"SetRequestHeader", DISPID_HTTPREQUEST_SETREQUESTHEADER },
{ L"Send", DISPID_HTTPREQUEST_SEND },
{ L"Status", DISPID_HTTPREQUEST_STATUS },
{ L"WaitForResponse", DISPID_HTTPREQUEST_WAITFORRESPONSE },
{ L"GetResponseHeader", DISPID_HTTPREQUEST_GETRESPONSEHEADER },
{ L"ResponseBody", DISPID_HTTPREQUEST_RESPONSEBODY },
{ L"ResponseText", DISPID_HTTPREQUEST_RESPONSETEXT },
{ L"ResponseStream", DISPID_HTTPREQUEST_RESPONSESTREAM },
{ L"StatusText", DISPID_HTTPREQUEST_STATUSTEXT },
{ L"SetAutoLogonPolicy", DISPID_HTTPREQUEST_SETAUTOLOGONPOLICY },
{ L"SetClientCertificate", DISPID_HTTPREQUEST_SETCLIENTCERTIFICATE },
{ L"SetCredentials", DISPID_HTTPREQUEST_SETCREDENTIALS },
{ L"SetProxy", DISPID_HTTPREQUEST_SETPROXY },
{ L"GetAllResponseHeaders", DISPID_HTTPREQUEST_GETALLRESPONSEHEADERS },
{ L"Abort", DISPID_HTTPREQUEST_ABORT },
{ L"SetTimeouts", DISPID_HTTPREQUEST_SETTIMEOUTS },
{ L"Option", DISPID_HTTPREQUEST_OPTION }
};
STDMETHODIMP
CHttpRequest::GetIDsOfNames(REFIID riid, LPOLESTR * rgszNames,
UINT cNames,
LCID ,
DISPID * rgDispId)
{
if (riid != IID_NULL)
return E_INVALIDARG;
HRESULT hr = NOERROR;
if (cNames > 0)
{
hr = DISP_E_UNKNOWNNAME;
for (int i = 0; i < (sizeof(IdMapping)/sizeof(IdMapping[0])); i++)
{
if (StrCmpIW(rgszNames[0], IdMapping[i].wszMemberName) == 0)
{
hr = NOERROR;
rgDispId[0] = IdMapping[i].dispId;
break;
}
}
}
return hr;
}
// _DispGetParamSafe
//
// A wrapper around the OLE Automation DispGetParam API that protects
// the call with a __try/__except block. Needed for casting to BSTR,
// as bogus BSTR pointers can cause an AV in VariantChangeType (which
// DispGetParam calls).
//
static HRESULT _DispGetParamSafe
(
DISPPARAMS * pDispParams,
DISPID dispid,
VARTYPE vt,
VARIANT * pvarResult,
unsigned int * puArgErr
)
{
HRESULT hr;
__try
{
hr = DL(DispGetParam)(pDispParams, dispid, vt, pvarResult, puArgErr);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
return hr;
}
// _DispGetOptionalParam
//
// Helper routine to fetch optional parameters. If DL(DispGetParam) returns
// DISP_E_PARAMNOTFOUND, the error is converted to NOERROR.
//
static inline HRESULT _DispGetOptionalParam
(
DISPPARAMS * pDispParams,
DISPID dispid,
VARTYPE vt,
VARIANT * pvarResult,
unsigned int * puArgErr
)
{
HRESULT hr = _DispGetParamSafe(pDispParams, dispid, vt, pvarResult, puArgErr);
return (hr == DISP_E_PARAMNOTFOUND) ? NOERROR : hr;
}
STDMETHODIMP
CHttpRequest::Invoke(DISPID dispIdMember, REFIID riid,
LCID,
WORD wFlags,
DISPPARAMS * pDispParams,
VARIANT * pVarResult,
EXCEPINFO * pExcepInfo,
UINT * puArgErr)
{
HRESULT hr = NOERROR;
unsigned int uArgErr;
if (wFlags & ~(DISPATCH_METHOD | DISPATCH_PROPERTYGET | DISPATCH_PROPERTYPUT))
return E_INVALIDARG;
if (riid != IID_NULL)
return DISP_E_UNKNOWNINTERFACE;
if (IsBadReadPtr(pDispParams, sizeof(DISPPARAMS)))
return E_INVALIDARG;
if (!puArgErr)
{
puArgErr = &uArgErr;
}
else if (IsBadWritePtr(puArgErr, sizeof(UINT)))
{
return E_INVALIDARG;
}
if (pVarResult)
{
if (IsBadWritePtr(pVarResult, sizeof(VARIANT)))
return E_INVALIDARG;
DL(VariantInit)(pVarResult);
}
switch (dispIdMember)
{
case DISPID_HTTPREQUEST_ABORT:
{
hr = Abort();
break;
}
case DISPID_HTTPREQUEST_SETPROXY:
{
VARIANT varProxySetting;
VARIANT varProxyServer;
VARIANT varBypassList;
DL(VariantInit)(&varProxySetting);
DL(VariantInit)(&varProxyServer);
DL(VariantInit)(&varBypassList);
hr = DL(DispGetParam)(pDispParams, 0, VT_I4, &varProxySetting, puArgErr);
if (SUCCEEDED(hr))
{
hr = _DispGetOptionalParam(pDispParams, 1, VT_BSTR, &varProxyServer, puArgErr);
}
if (SUCCEEDED(hr))
{
hr = _DispGetOptionalParam(pDispParams, 2, VT_BSTR, &varBypassList, puArgErr);
}
if (SUCCEEDED(hr))
{
hr = SetProxy(V_I4(&varProxySetting), varProxyServer, varBypassList);
}
DL(VariantClear)(&varProxySetting);
DL(VariantClear)(&varProxyServer);
DL(VariantClear)(&varBypassList);
break;
}
case DISPID_HTTPREQUEST_SETCREDENTIALS:
{
VARIANT varUserName;
VARIANT varPassword;
VARIANT varAuthTarget;
DL(VariantInit)(&varUserName);
DL(VariantInit)(&varPassword);
DL(VariantInit)(&varAuthTarget);
hr = _DispGetParamSafe(pDispParams, 0, VT_BSTR, &varUserName, puArgErr);
if (SUCCEEDED(hr))
{
hr = _DispGetParamSafe(pDispParams, 1, VT_BSTR, &varPassword, puArgErr);
}
if (SUCCEEDED(hr))
{
hr = DL(DispGetParam)(pDispParams, 2, VT_I4, &varAuthTarget, puArgErr);
}
if (SUCCEEDED(hr))
{
hr = SetCredentials(V_BSTR(&varUserName), V_BSTR(&varPassword),
V_I4(&varAuthTarget));
}
DL(VariantClear)(&varUserName);
DL(VariantClear)(&varPassword);
DL(VariantClear)(&varAuthTarget);
break;
}
case DISPID_HTTPREQUEST_OPEN:
{
VARIANT varMethod;
VARIANT varUrl;
VARIANT varAsync;
DL(VariantInit)(&varMethod);
DL(VariantInit)(&varUrl);
DL(VariantInit)(&varAsync);
hr = _DispGetParamSafe(pDispParams, 0, VT_BSTR, &varMethod, puArgErr);
if (SUCCEEDED(hr))
{
hr = _DispGetParamSafe(pDispParams, 1, VT_BSTR, &varUrl, puArgErr);
}
if (SUCCEEDED(hr))
{
hr = _DispGetOptionalParam(pDispParams, 2, VT_BOOL, &varAsync, puArgErr);
}
if (SUCCEEDED(hr))
{
hr = Open(V_BSTR(&varMethod), V_BSTR(&varUrl), varAsync);
}
DL(VariantClear)(&varMethod);
DL(VariantClear)(&varUrl);
DL(VariantClear)(&varAsync);
break;
}
case DISPID_HTTPREQUEST_SETREQUESTHEADER:
{
VARIANT varHeader;
VARIANT varValue;
DL(VariantInit)(&varHeader);
DL(VariantInit)(&varValue);
hr = _DispGetParamSafe(pDispParams, 0, VT_BSTR, &varHeader, puArgErr);
if (SUCCEEDED(hr))
{
hr = _DispGetParamSafe(pDispParams, 1, VT_BSTR, &varValue, puArgErr);
}
if (SUCCEEDED(hr))
{
hr = SetRequestHeader(V_BSTR(&varHeader), V_BSTR(&varValue));
}
DL(VariantClear)(&varHeader);
DL(VariantClear)(&varValue);
break;
}
case DISPID_HTTPREQUEST_GETRESPONSEHEADER:
{
VARIANT varHeader;
DL(VariantInit)(&varHeader);
hr = _DispGetParamSafe(pDispParams, 0, VT_BSTR, &varHeader, puArgErr);
if (SUCCEEDED(hr))
{
BSTR bstrValue = NULL;
hr = GetResponseHeader(V_BSTR(&varHeader), &bstrValue);
if (SUCCEEDED(hr) && pVarResult)
{
V_VT(pVarResult) = VT_BSTR;
V_BSTR(pVarResult) = bstrValue;
}
else
DL(SysFreeString)(bstrValue);
}
DL(VariantClear)(&varHeader);
break;
}
case DISPID_HTTPREQUEST_GETALLRESPONSEHEADERS:
{
BSTR bstrResponseHeaders = NULL;
hr = GetAllResponseHeaders(&bstrResponseHeaders);
if (SUCCEEDED(hr) && pVarResult)
{
V_VT(pVarResult) = VT_BSTR;
V_BSTR(pVarResult) = bstrResponseHeaders;
}
else
DL(SysFreeString)(bstrResponseHeaders);
break;
}
case DISPID_HTTPREQUEST_SEND:
{
if (pDispParams->cArgs <= 1)
{
VARIANT varEmptyBody;
DL(VariantInit)(&varEmptyBody);
hr = Send((pDispParams->cArgs == 0) ? varEmptyBody : pDispParams->rgvarg[0]);
}
else
{
hr = DISP_E_BADPARAMCOUNT;
}
break;
}
case DISPID_HTTPREQUEST_STATUS:
{
long Status;
hr = get_Status(&Status);
if (SUCCEEDED(hr) && pVarResult)
{
V_VT(pVarResult) = VT_I4;
V_I4(pVarResult) = Status;
}
break;
}
case DISPID_HTTPREQUEST_STATUSTEXT:
{
BSTR bstrStatus = NULL;
hr = get_StatusText(&bstrStatus);
if (SUCCEEDED(hr) && pVarResult)
{
V_VT(pVarResult) = VT_BSTR;
V_BSTR(pVarResult) = bstrStatus;
}
else
DL(SysFreeString)(bstrStatus);
break;
}
case DISPID_HTTPREQUEST_RESPONSETEXT:
{
BSTR bstrResponse = NULL;
hr = get_ResponseText(&bstrResponse);
if (SUCCEEDED(hr) && pVarResult)
{
V_VT(pVarResult) = VT_BSTR;
V_BSTR(pVarResult) = bstrResponse;
}
else
DL(SysFreeString)(bstrResponse);
break;
}
case DISPID_HTTPREQUEST_RESPONSEBODY:
{
if (pVarResult)
{
hr = get_ResponseBody(pVarResult);
}
break;
}
case DISPID_HTTPREQUEST_RESPONSESTREAM:
{
if (pVarResult)
{
hr = get_ResponseStream(pVarResult);
}
break;
}
case DISPID_HTTPREQUEST_OPTION:
{
VARIANT varOption;
WinHttpRequestOption Option;
DL(VariantInit)(&varOption);
hr = DL(DispGetParam)(pDispParams, 0, VT_I4, &varOption, puArgErr);
if (FAILED(hr))
break;
Option = static_cast<WinHttpRequestOption>(V_I4(&varOption));
if (wFlags & (DISPATCH_METHOD | DISPATCH_PROPERTYGET))
{
if (pVarResult)
{
hr = get_Option(Option, pVarResult);
}
}
else if (wFlags & DISPATCH_PROPERTYPUT)
{
hr = put_Option(Option, pDispParams->rgvarg[0]);
}
DL(VariantClear)(&varOption);
break;
}
case DISPID_HTTPREQUEST_WAITFORRESPONSE:
{
VARIANT varTimeout;
VARIANT_BOOL boolSucceeded = FALSE;
DL(VariantInit)(&varTimeout);
hr = _DispGetOptionalParam(pDispParams, 0, VT_I4, &varTimeout, puArgErr);
if (SUCCEEDED(hr))
{
hr = WaitForResponse(varTimeout, &boolSucceeded);
}
if (pVarResult)
{
V_VT(pVarResult) = VT_BOOL;
V_BOOL(pVarResult) = boolSucceeded;
}
DL(VariantClear)(&varTimeout);
break;
}
case DISPID_HTTPREQUEST_SETTIMEOUTS:
{
VARIANT varResolveTimeout;
VARIANT varConnectTimeout;
VARIANT varSendTimeout;
VARIANT varReceiveTimeout;
DL(VariantInit)(&varResolveTimeout);
DL(VariantInit)(&varConnectTimeout);
DL(VariantInit)(&varSendTimeout);
DL(VariantInit)(&varReceiveTimeout);
hr = DL(DispGetParam)(pDispParams, 0, VT_I4, &varResolveTimeout, puArgErr);
if (SUCCEEDED(hr))
{
hr = DL(DispGetParam)(pDispParams, 1, VT_I4, &varConnectTimeout, puArgErr);
}
if (SUCCEEDED(hr))
{
hr = DL(DispGetParam)(pDispParams, 2, VT_I4, &varSendTimeout, puArgErr);
}
if (SUCCEEDED(hr))
{
hr = DL(DispGetParam)(pDispParams, 3, VT_I4, &varReceiveTimeout, puArgErr);
}
if (SUCCEEDED(hr))
{
hr = SetTimeouts(V_I4(&varResolveTimeout), V_I4(&varConnectTimeout),
V_I4(&varSendTimeout),
V_I4(&varReceiveTimeout));
}
DL(VariantClear)(&varResolveTimeout);
DL(VariantClear)(&varConnectTimeout);
DL(VariantClear)(&varSendTimeout);
DL(VariantClear)(&varReceiveTimeout);
break;
}
case DISPID_HTTPREQUEST_SETCLIENTCERTIFICATE:
{
VARIANT varClientCertificate;
DL(VariantInit)(&varClientCertificate);
hr = _DispGetParamSafe(pDispParams, 0, VT_BSTR, &varClientCertificate, puArgErr);
if (SUCCEEDED(hr))
{
hr = SetClientCertificate(V_BSTR(&varClientCertificate));
}
DL(VariantClear)(&varClientCertificate);
break;
}
case DISPID_HTTPREQUEST_SETAUTOLOGONPOLICY:
{
VARIANT varAutoLogonPolicy;
DL(VariantInit)(&varAutoLogonPolicy);
hr = DL(DispGetParam)(pDispParams, 0, VT_I4, &varAutoLogonPolicy, puArgErr);
if (SUCCEEDED(hr))
{
WinHttpRequestAutoLogonPolicy AutoLogonPolicy;
AutoLogonPolicy = static_cast<WinHttpRequestAutoLogonPolicy>(V_I4(&varAutoLogonPolicy));
hr = SetAutoLogonPolicy(AutoLogonPolicy);
}
DL(VariantClear)(&varAutoLogonPolicy);
break;
}
default:
hr = DISP_E_MEMBERNOTFOUND;
break;
}
if (FAILED(hr) && (pExcepInfo != NULL))
{
hr = FillExcepInfo(hr, pExcepInfo);
}
return hr;
}
static
HRESULT
FillExcepInfo(HRESULT hr, EXCEPINFO * pExcepInfo)
{
// Don't create excepinfo for these errors to mimic oleaut behavior.
if( hr == DISP_E_BADPARAMCOUNT ||
hr == DISP_E_NONAMEDARGS ||
hr == DISP_E_MEMBERNOTFOUND ||
hr == E_INVALIDARG)
{
return hr;
}
// clear out exception info
IErrorInfo * pei = NULL;
pExcepInfo->wCode = 0;
pExcepInfo->scode = hr;
// if error info exists, use it
DL(GetErrorInfo)(0, &pei);
if (pei)
{
// give back to OLE
DL(SetErrorInfo)(0, pei);
pei->GetHelpContext(&pExcepInfo->dwHelpContext);
pei->GetSource(&pExcepInfo->bstrSource);
pei->GetDescription(&pExcepInfo->bstrDescription);
pei->GetHelpFile(&pExcepInfo->bstrHelpFile);
// give complete ownership to OLEAUT
pei->Release();
hr = DISP_E_EXCEPTION;
}
return hr;
}
STDMETHODIMP
CHttpRequest::InterfaceSupportsErrorInfo(REFIID riid)
{
return (riid == IID_IWinHttpRequest) ? S_OK : S_FALSE;
}
STDMETHODIMP
CHttpRequest::GetClassInfo(ITypeInfo ** ppTI)
{
if (!ppTI)
return E_POINTER;
*ppTI = NULL;
return GetHttpRequestTypeInfo(CLSID_WinHttpRequest, ppTI);
}
STDMETHODIMP
CHttpRequest::GetGUID(DWORD dwGuidKind, GUID * pGUID)
{
if (!pGUID)
return E_POINTER;
if (dwGuidKind == GUIDKIND_DEFAULT_SOURCE_DISP_IID)
{
*pGUID = IID_IWinHttpRequestEvents;
}
else
return E_INVALIDARG;
return NOERROR;
}
STDMETHODIMP
CHttpRequest::EnumConnectionPoints(IEnumConnectionPoints ** ppEnum)
{
if (!ppEnum)
return E_POINTER;
*ppEnum = static_cast<IEnumConnectionPoints*>(
new CEnumConnectionPoints(static_cast<IConnectionPoint*>(&_CP))
);
return (*ppEnum) ? S_OK : E_OUTOFMEMORY;
}
STDMETHODIMP
CHttpRequest::FindConnectionPoint(REFIID riid, IConnectionPoint ** ppCP)
{
if (!ppCP)
return E_POINTER;
if (riid == IID_IWinHttpRequestEvents)
{
return _CP.QueryInterface(IID_IConnectionPoint, (void **)ppCP);
}
else if (riid == IID_IWinHttpRequestEvents_TechBeta)
{
_CP.DisableOnError();
return _CP.QueryInterface(IID_IConnectionPoint, (void **)ppCP);
}
else
return CONNECT_E_NOCONNECTION;
}
STDMETHODIMP
CHttpRequest::CHttpRequestEventsCP::QueryInterface(REFIID riid, void ** ppvObject)
{
if (!ppvObject)
return E_INVALIDARG;
if (riid == IID_IUnknown || riid == IID_IConnectionPoint)
{
*ppvObject = static_cast<IUnknown *>(static_cast<IConnectionPoint *>(this));
AddRef();
return NOERROR;
}
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE
CHttpRequest::CHttpRequestEventsCP::AddRef()
{
return Px()->AddRef();
}
ULONG STDMETHODCALLTYPE
CHttpRequest::CHttpRequestEventsCP::Release()
{
return Px()->Release();
}
STDMETHODIMP
CHttpRequest::CHttpRequestEventsCP::GetConnectionInterface(IID * pIID)
{
if (!pIID)
return E_POINTER;
*pIID = IID_IWinHttpRequestEvents;
return NOERROR;
}
STDMETHODIMP
CHttpRequest::CHttpRequestEventsCP::GetConnectionPointContainer
(
IConnectionPointContainer ** ppCPC
)
{
if (!ppCPC)
return E_POINTER;
return Px()->QueryInterface(IID_IConnectionPointContainer, (void **)ppCPC);
}
STDMETHODIMP
CHttpRequest::CHttpRequestEventsCP::Advise(IUnknown * pUnk, DWORD * pdwCookie)
{
if (!pUnk || !pdwCookie)
{
return E_POINTER;
}
IWinHttpRequestEvents * pIWinHttpRequestEvents;
HRESULT hr;
hr = pUnk->QueryInterface(IID_IWinHttpRequestEvents, (void **)&pIWinHttpRequestEvents);
// RENO 39279: if the QI for IWinHttpRequestEvents fails, try the older
// IID from the Tech Beta.
if (FAILED(hr))
{
hr = pUnk->QueryInterface(IID_IWinHttpRequestEvents_TechBeta, (void **)&pIWinHttpRequestEvents);
if (SUCCEEDED(hr))
{
// The OnError event should have already been disabled in
// CHttpRequest::FindConnectionPoint(), but it doesn't
// hurt to be paranoid.
DisableOnError();
}
}
if (SUCCEEDED(hr))
{
*pdwCookie = _SinkArray.Add(static_cast<IUnknown *>(pIWinHttpRequestEvents));
if (*pdwCookie)
{
_cConnections++;
hr = NOERROR;
}
else
{
hr = E_OUTOFMEMORY;
}
}
else
hr = CONNECT_E_CANNOTCONNECT;
return hr;
}
STDMETHODIMP
CHttpRequest::CHttpRequestEventsCP::Unadvise(DWORD dwCookie)
{
IUnknown * pSink = _SinkArray.GetUnknown(dwCookie);
if (pSink)
{
_SinkArray.Remove(dwCookie);
pSink->Release();
--_cConnections;
}
return NOERROR;
}
STDMETHODIMP
CHttpRequest::CHttpRequestEventsCP::EnumConnections(IEnumConnections ** ppEnum)
{
if (!ppEnum)
return E_POINTER;
*ppEnum = NULL;
DWORD_PTR size = _SinkArray.end() - _SinkArray.begin();
CONNECTDATA* pCD = NULL;
if (size != 0)
{
//allocate data on stack, we usually expect just 1 or few connections,
//so it's ok to allocate such ammount of data on stack
__try
{
pCD = (CONNECTDATA*)_alloca(size * sizeof(CONNECTDATA[1]));
}
__except (GetExceptionCode() == STATUS_STACK_OVERFLOW ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{
return E_OUTOFMEMORY;
}
}
IUnknown** ppUnk = _SinkArray.begin();
for (DWORD i = 0; i < size; ++i)
{
pCD[i].pUnk = ppUnk[i];
pCD[i].dwCookie = i + 1;
}
CEnumConnections* pE = new CEnumConnections();
if (pE)
{
HRESULT hr = pE->Init(pCD, (DWORD)size);
if ( SUCCEEDED(hr) )
*ppEnum = static_cast<IEnumConnections*>(pE);
else
delete pE;
return hr;
}
else
return E_OUTOFMEMORY;
}
void
CHttpRequest::CHttpRequestEventsCP::FireOnResponseStart(long Status, BSTR ContentType)
{
if (_cConnections > 0 && !Px()->_bAborted)
{
GetSink()->OnResponseStart(Status, ContentType);
}
}
void
CHttpRequest::CHttpRequestEventsCP::FireOnResponseDataAvailable
(
const BYTE * rgbData,
DWORD cbData
)
{
if (_cConnections > 0 && !Px()->_bAborted)
{
VARIANT varData;
HRESULT hr;
DL(VariantInit)(&varData);
hr = CreateVector(&varData, rgbData, cbData);
if (SUCCEEDED(hr))
{
GetSink()->OnResponseDataAvailable(&V_ARRAY(&varData));
}
DL(VariantClear)(&varData);
}
}
void
CHttpRequest::CHttpRequestEventsCP::FireOnResponseFinished()
{
if (_cConnections > 0 && !Px()->_bAborted)
{
GetSink()->OnResponseFinished();
}
}
void
CHttpRequest::CHttpRequestEventsCP::FireOnError(HRESULT hr)
{
if ((_cConnections > 0) && (!Px()->_bAborted) && (!_bOnErrorDisabled))
{
IErrorInfo * pErrorInfo = CreateErrorObject(hr);
BSTR bstrErrorDescription = NULL;
if (pErrorInfo)
{
pErrorInfo->GetDescription(&bstrErrorDescription);
pErrorInfo->Release();
}
GetSink()->OnError((long) hr, bstrErrorDescription);
DL(SysFreeString)(bstrErrorDescription);
}
}
HRESULT
CHttpRequest::CHttpRequestEventsCP::CreateEventSinksMarshaller()
{
HRESULT hr = NOERROR;
if (_cConnections > 0)
{
SafeRelease(_pSinkMarshaller);
hr = CWinHttpRequestEventsMarshaller::Create(&_SinkArray, &_pSinkMarshaller);
}
return hr;
}
void
CHttpRequest::CHttpRequestEventsCP::ShutdownEventSinksMarshaller()
{
if (_pSinkMarshaller)
_pSinkMarshaller->Shutdown();
}
void
CHttpRequest::CHttpRequestEventsCP::ReleaseEventSinksMarshaller()
{
SafeRelease(_pSinkMarshaller);
}
void
CHttpRequest::CHttpRequestEventsCP::FreezeEvents()
{
if (_pSinkMarshaller)
_pSinkMarshaller->FreezeEvents();
}
void
CHttpRequest::CHttpRequestEventsCP::UnfreezeEvents()
{
if (_pSinkMarshaller)
_pSinkMarshaller->UnfreezeEvents();
}
CHttpRequest::CHttpRequestEventsCP::~CHttpRequestEventsCP()
{
// If any connections are still alive, unadvise them.
if (_cConnections > 0)
{
_SinkArray.ReleaseAll();
_cConnections = 0;
}
}
/*
* CHttpRequest::Initialize
*
* Purpose:
* Zero all data members
*
*/
void
CHttpRequest::Initialize()
{
_cRefs = 0;
_pTypeInfo = NULL;
_bstrUserAgent = NULL;
_dwProxySetting = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
_bstrProxyServer = NULL;
_bstrBypassList = NULL;
_eState = CHttpRequest::CREATED;
_fAsync = FALSE;
#if !defined(TRUE_ASYNC)
_hWorkerThread = NULL;
#endif//!TRUE_ASYNC
_cRefsOnMainThread = 0;
_dwMainThreadId = GetCurrentThreadId();
_hrAsyncResult = NOERROR;
_bAborted = false;
_bSetTimeouts = false;
_bSetUtf8Charset = false;
_hInet = NULL;
_hConnection = NULL;
_hHTTP = NULL;
_ResolveTimeout = 0;
_ConnectTimeout = 0;
_SendTimeout = 0;
_ReceiveTimeout = 0;
_cbRequestBody = 0;
_szRequestBuffer = NULL;
_dwCodePage = CP_UTF8;
_dwEscapeFlag = WINHTTP_FLAG_ESCAPE_DISABLE_QUERY;
_cbResponseBody = 0;
_pResponseStream = NULL;
_hAbortedConnectObject = NULL;
_hAbortedRequestObject = NULL;
_bstrCertSubject = NULL;
_bstrCertStore = NULL;
_fCertLocalMachine = FALSE;
_fCheckForRevocation = FALSE;
_dwSslIgnoreFlags = 0;
_dwSecureProtocols = DEFAULT_SECURE_PROTOCOLS;
_hrSecureFailure = HRESULT_FROM_WIN32(ERROR_WINHTTP_SECURE_FAILURE);
_bEnableSslImpersonation = FALSE;
_bMethodGET = FALSE;
_bHttp1_1Mode = TRUE;
#ifdef TRUE_ASYNC
_hCompleteEvent = NULL;
_bRetriedWithCert = FALSE;
_Buffer = NULL;
#endif
_dwAutoLogonPolicy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_DEFAULT;
_dwRedirectPolicy = WINHTTP_OPTION_REDIRECT_POLICY_DEFAULT;
_lMaxAutomaticRedirects = GlobalMaxHttpRedirects;
_lMaxResponseHeaderSize = GlobalMaxHeaderSize;
_lMaxResponseDrainSize = GlobalMaxDrainSize;
_dwPassportConfig = (WINHTTP_DISABLE_PASSPORT_AUTH | WINHTTP_DISABLE_PASSPORT_KEYRING);
}
/*
* CHttpRequest::ReleaseResources
*
* Purpose:
* Release all handles, events, and buffers
*
*/
void
CHttpRequest::ReleaseResources()
{
SafeRelease(_pTypeInfo);
#if !defined(TRUE_ASYNC)
if (_hWorkerThread)
{
CloseHandle(_hWorkerThread);
_hWorkerThread = NULL;
}
#endif//!TRUE_ASYNC
_CP.ReleaseEventSinksMarshaller();
//
// Derefence aborted handle objects (if any).
//
if (_hAbortedRequestObject != NULL)
{
DereferenceObject(_hAbortedRequestObject);
_hAbortedRequestObject = NULL;
}
if (_hAbortedConnectObject != NULL)
{
DereferenceObject(_hAbortedConnectObject);
_hAbortedConnectObject = NULL;
}
if (_hHTTP)
{
HINTERNET temp = _hHTTP;
_hHTTP = NULL;
WinHttpCloseHandle(temp);
}
if (_hConnection)
{
HINTERNET temp = _hConnection;
_hConnection = NULL;
WinHttpCloseHandle(temp);
}
if (_hInet)
{
HINTERNET temp = _hInet;
_hInet = NULL;
WinHttpCloseHandle(temp);
}
if (_szRequestBuffer)
{
delete [] _szRequestBuffer;
_szRequestBuffer = NULL;
}
SafeRelease(_pResponseStream);
if (_bstrUserAgent)
{
DL(SysFreeString)(_bstrUserAgent);
_bstrUserAgent = NULL;
}
if (_bstrProxyServer)
{
DL(SysFreeString)(_bstrProxyServer);
_bstrProxyServer = NULL;
}
if (_bstrBypassList)
{
DL(SysFreeString)(_bstrBypassList);
_bstrBypassList = NULL;
}
if (_bstrCertSubject)
{
DL(SysFreeString)(_bstrCertSubject);
_bstrCertSubject = NULL;
}
if (_bstrCertStore)
{
DL(SysFreeString)(_bstrCertStore);
_bstrCertStore = NULL;
}
#ifdef TRUE_ASYNC
if (_hCompleteEvent != NULL)
{
CloseHandle(_hCompleteEvent);
_hCompleteEvent = NULL;
}
if (_Buffer != NULL)
{
delete [] _Buffer;
}
#endif
}
/*
* CHttpRequest::Reset
*
* Purpose:
* Release all resources and initialize data members
*
*/
void
CHttpRequest::Reset()
{
ReleaseResources();
Initialize();
}
/*
* CHttpRequest::Recycle
*
* Purpose:
* Recycle object
*
*/
void
CHttpRequest::Recycle()
{
DEBUG_ENTER((DBG_HTTP,
None,
"IWinHttpRequest::Recycle",
NULL));
//
// Wait for the worker thread to shut down. This shouldn't take long
// since the Abort will close the Request and Connection handles.
//
if (
#ifdef TRUE_ASYNC
_hCompleteEvent
#else
_hWorkerThread
#endif//TRUE_ASYNC
)
{
DWORD dwWaitResult;
for (;;)
{
dwWaitResult = MsgWaitForMultipleObjects(1,
#ifdef TRUE_ASYNC
&_hCompleteEvent
#else
&_hWorkerThread
#endif//TRUE_ASYNC
,
FALSE,
INFINITE,
QS_ALLINPUT);
if (dwWaitResult == (WAIT_OBJECT_0 + 1))
{
// Message waiting in the message queue.
// Run message pump to clear queue.
MessageLoop();
}
else
{
break;
}
}
#ifdef TRUE_ASYNC
CloseHandle(_hCompleteEvent);
_hCompleteEvent = NULL;
#else
CloseHandle(_hWorkerThread);
_hWorkerThread = NULL;
#endif//TRUE_ASYNC
}
_hConnection = NULL;
_hHTTP = NULL;
//
// Derefence aborted handle objects (if any).
//
if (_hAbortedRequestObject != NULL)
{
DereferenceObject(_hAbortedRequestObject);
_hAbortedRequestObject = NULL;
}
if (_hAbortedConnectObject != NULL)
{
DereferenceObject(_hAbortedConnectObject);
_hAbortedConnectObject = NULL;
}
//sergekh: we shouldn't reset _fAsync to know the state of _hInet
//_fAsync = FALSE;
_hrAsyncResult = NOERROR;
_bAborted = false;
// don't reset timeouts, keep any that were set.
_cbRequestBody = 0;
_cbResponseBody = 0;
if (_szRequestBuffer)
{
delete [] _szRequestBuffer;
_szRequestBuffer = NULL;
}
SafeRelease(_pResponseStream);
_CP.ShutdownEventSinksMarshaller();
_CP.ReleaseEventSinksMarshaller();
// Allow events to fire; Abort() would have frozen them from firing.
_CP.UnfreezeEvents();
SetState(CHttpRequest::CREATED);
DEBUG_LEAVE(0);
}
static BOOL GetContentLengthIfResponseNotChunked(
HINTERNET hHttpRequest,
DWORD * pdwContentLength
)
{
char szTransferEncoding[16]; // big enough for "chunked" or "identity"
DWORD cb;
BOOL fRetCode;
cb = sizeof(szTransferEncoding) - 1;
fRetCode = HttpQueryInfoA(
hHttpRequest,
WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING,
WINHTTP_HEADER_NAME_BY_INDEX,
szTransferEncoding,
&cb,
0);
if (!fRetCode || lstrcmpi(szTransferEncoding, "identity") == 0)
{
// Determine the content length
cb = sizeof(DWORD);
fRetCode = HttpQueryInfoA(
hHttpRequest,
WINHTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX,
pdwContentLength,
&cb,
0);
}
else
{
fRetCode = FALSE;
}
return fRetCode;
}
/*
* CHttpRequest::ReadResponse
*
* Purpose:
* Read the response bits
*
* Parameters:
* None
*
* Errors:
* E_FAIL
* E_OUTOFMEMORY
*/
HRESULT
CHttpRequest::ReadResponse()
{
HRESULT hr = NOERROR;
BOOL fRetCode;
long lStatus;
BSTR bstrContentType = NULL;
DWORD dwContentLength = 0;
BYTE * Buffer = NULL;
SetState(CHttpRequest::RECEIVING);
hr = get_Status(&lStatus);
if (FAILED(hr))
goto Error;
hr = _GetResponseHeader(L"Content-Type", &bstrContentType);
if (FAILED(hr))
{
bstrContentType = DL(SysAllocString)(L"");
if (bstrContentType == NULL)
goto ErrorOutOfMemory;
hr = NOERROR;
}
INET_ASSERT((_pResponseStream == NULL) && (_cbResponseBody == 0));
hr = DL(CreateStreamOnHGlobal)(NULL, TRUE, &_pResponseStream);
if (SUCCEEDED(hr))
{
// Determine the content length
fRetCode = GetContentLengthIfResponseNotChunked(_hHTTP, &dwContentLength);
// pre-set response stream size if we have a Content-Length
if (fRetCode)
{
ULARGE_INTEGER size;
size.LowPart = dwContentLength;
size.HighPart = 0;
_pResponseStream->SetSize(size);
}
else
{
// Content-Length was not specified in the response, but this
// does not mean Content-Length==0. We will keep reading until
// either no more data is available. Set dwContentLength to 4GB
// to trick our read loop into reading until eof is reached.
dwContentLength = (DWORD)(-1L);
ULARGE_INTEGER size;
// Set initial size of the response stream to 8K.
size.LowPart = SIZEOF_BUFFER;
size.HighPart = 0;
_pResponseStream->SetSize(size);
}
}
else
goto ErrorOutOfMemory;
//
// Allocate an 8K buffer to read the response data in chunks.
//
Buffer = New BYTE[SIZEOF_BUFFER];
if (!Buffer)
{
goto ErrorOutOfMemory;
}
//
// Fire the initial OnResponseStart event
//
_CP.FireOnResponseStart(lStatus, bstrContentType);
// Skip read loop if Content-Length==0.
if (dwContentLength == 0)
{
goto Finished;
}
//
// Read data until there is no more - we need to buffer the data
//
while (!_bAborted)
{
DWORD cbAvail = 0;
DWORD cbRead = 0;
fRetCode = WinHttpQueryDataAvailable(_hHTTP, &cbAvail);
if (!fRetCode)
{
goto ErrorFail;
}
// Read up to 8K (sizeof Buffer) of data.
cbAvail = min(cbAvail, SIZEOF_BUFFER);
fRetCode = WinHttpReadData(_hHTTP, Buffer, cbAvail, &cbRead);
if (!fRetCode)
{
goto ErrorFail;
}
if (cbRead != 0)
{
hr = _pResponseStream->Write(Buffer, cbRead, NULL);
if (FAILED(hr))
{
goto ErrorOutOfMemory;
}
_CP.FireOnResponseDataAvailable((const BYTE *)Buffer, cbRead);
_cbResponseBody += cbRead;
}
// If WinHttpReadData indicates there is no more data to read,
// or we've read as much data as the Content-Length header tells
// us to expect, then we're finished reading the response.
if ((cbRead == 0) || (_cbResponseBody >= dwContentLength))
{
ULARGE_INTEGER size;
// set final size on stream
size.LowPart = _cbResponseBody;
size.HighPart = 0;
_pResponseStream->SetSize(size);
break;
}
}
Finished:
SetState(CHttpRequest::RESPONSE);
_CP.FireOnResponseFinished();
hr = NOERROR;
Cleanup:
if (bstrContentType)
DL(SysFreeString)(bstrContentType);
if (Buffer)
delete [] Buffer;
return hr;
ErrorOutOfMemory:
hr = E_OUTOFMEMORY;
goto Error;
ErrorFail:
hr = HRESULT_FROM_WIN32(::GetLastError());
_CP.FireOnError(hr);
goto Error;
Error:
SafeRelease(_pResponseStream);
_cbResponseBody = NULL;
goto Cleanup;
}
STDMETHODIMP
CHttpRequest::SetProxy(HTTPREQUEST_PROXY_SETTING ProxySetting,
VARIANT varProxyServer,
VARIANT varBypassList)
{
HRESULT hr = NOERROR;
if (!IsValidVariant(varProxyServer) || !IsValidVariant(varBypassList))
return E_INVALIDARG;
DEBUG_ENTER_API((DBG_HTTP,
Dword,
"IWinHttpRequest::SetProxy",
"HTTPREQUEST_PROXY_SETTING: %d, VARIANT, VARIANT",
ProxySetting
));
if (_bstrProxyServer)
{
DL(SysFreeString)(_bstrProxyServer);
_bstrProxyServer = NULL;
}
if (_bstrBypassList)
{
DL(SysFreeString)(_bstrBypassList);
_bstrBypassList = NULL;
}
switch (ProxySetting)
{
case HTTPREQUEST_PROXYSETTING_PRECONFIG:
_dwProxySetting = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
break;
case HTTPREQUEST_PROXYSETTING_DIRECT:
_dwProxySetting = WINHTTP_ACCESS_TYPE_NO_PROXY;
break;
case HTTPREQUEST_PROXYSETTING_PROXY:
_dwProxySetting = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
hr = GetBSTRFromVariant(varProxyServer, &_bstrProxyServer);
if (SUCCEEDED(hr))
{
hr = GetBSTRFromVariant(varBypassList, &_bstrBypassList);
}
if (FAILED(hr))
{
hr = E_INVALIDARG;
}
break;
default:
hr = E_INVALIDARG;
break;
}
if (SUCCEEDED(hr))
{
if (_hHTTP)
{
WINHTTP_PROXY_INFOW ProxyInfo;
memset(&ProxyInfo, 0, sizeof(ProxyInfo));
ProxyInfo.dwAccessType = _dwProxySetting;
ProxyInfo.lpszProxy = _bstrProxyServer;
ProxyInfo.lpszProxyBypass = _bstrBypassList;
if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_PROXY,
&ProxyInfo,
sizeof(ProxyInfo)))
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
if (SUCCEEDED(hr) &&
!WinHttpSetOption(_hInet, WINHTTP_OPTION_PROXY,
&ProxyInfo,
sizeof(ProxyInfo)))
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
}
}
SetErrorInfo(hr);
DEBUG_LEAVE_API(hr);
return hr;
}
STDMETHODIMP
CHttpRequest::SetCredentials(
BSTR bstrUserName,
BSTR bstrPassword,
HTTPREQUEST_SETCREDENTIALS_FLAGS Flags)
{
HRESULT hr;
DEBUG_ENTER_API((DBG_HTTP,
Dword,
"IWinHttpRequest::SetCredentials",
"BSTR %Q, BSTR *, Flags: %x",
_hHTTP? bstrUserName: L"",
Flags
));
// Must call Open method before SetCredentials.
if (! _hHTTP)
{
goto ErrorCannotCallBeforeOpen;
}
if (!IsValidBstr(bstrUserName) || !IsValidBstr(bstrPassword))
return E_INVALIDARG;
if (Flags == HTTPREQUEST_SETCREDENTIALS_FOR_SERVER)
{
// Set Username and Password.
if (!WinHttpSetOption(
_hHTTP,
WINHTTP_OPTION_USERNAME,
bstrUserName,
lstrlenW(bstrUserName)))
goto ErrorFail;
if (!WinHttpSetOption(
_hHTTP,
WINHTTP_OPTION_PASSWORD,
bstrPassword,
lstrlenW(bstrPassword)+1)) // 596411 allow empty/blank password
goto ErrorFail;
}
else if (Flags == HTTPREQUEST_SETCREDENTIALS_FOR_PROXY)
{
// Set Username and Password.
if (!WinHttpSetOption(
_hHTTP,
WINHTTP_OPTION_PROXY_USERNAME,
bstrUserName,
lstrlenW(bstrUserName)))
goto ErrorFail;
if (!WinHttpSetOption(
_hHTTP,
WINHTTP_OPTION_PROXY_PASSWORD,
bstrPassword,
lstrlenW(bstrPassword)+1)) // 596411 allow empty/blank password
goto ErrorFail;
}
else
{
DEBUG_LEAVE_API(E_INVALIDARG);
return E_INVALIDARG;
}
hr = NOERROR;
Cleanup:
SetErrorInfo(hr);
DEBUG_LEAVE_API(hr);
return hr;
ErrorCannotCallBeforeOpen:
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN);
goto Cleanup;
ErrorFail:
hr = HRESULT_FROM_WIN32(::GetLastError());
goto Cleanup;
}
/*
* CHttpRequest::Open
*
* Purpose:
* Open a logical HTTP connection
*
* Parameters:
* bstrMethod IN HTTP method (GET, PUT, ...)
* bstrUrl IN Target URL
*
* Errors:
* E_FAIL
* E_INVALIDARG
* E_OUTOFMEMORY
* E_ACCESSDENIED
* Errors from InternetOpenA and WinHttpCrackUrlA and InternetConnectA
* and HttpOpenRequestA
*/
STDMETHODIMP
CHttpRequest::Open(
BSTR bstrMethod,
BSTR bstrUrl,
VARIANT varAsync)
{
HRESULT hr = NOERROR;
BSTR bstrHostName = NULL;
BSTR bstrUrlPath = NULL;
DWORD dwHttpOpenFlags = 0;
DWORD dw;
URL_COMPONENTSW url;
// Validate that we are called from our apartment's thread.
if (GetCurrentThreadId() != _dwMainThreadId)
return RPC_E_WRONG_THREAD;
// Validate parameters
if (!bstrMethod || !bstrUrl ||
!IsValidBstr(bstrMethod) ||
!IsValidBstr(bstrUrl) ||
!lstrlenW(bstrMethod) || // cannot have empty method
!lstrlenW(bstrUrl) || // cannot have empty url
!IsValidVariant(varAsync))
return E_INVALIDARG;
BOOL newAsync = GetBoolFromVariant(varAsync, FALSE);
DEBUG_ENTER_API((DBG_HTTP,
Dword,
"IWinHttpRequest::Open",
"method: %Q, url: %Q, async: %d",
bstrMethod,
bstrUrl,
newAsync
));
// Check for reinitialization
if (_eState != CHttpRequest::CREATED)
{
//
// Abort any request in progress.
// This will also recycle the object.
//
Abort();
}
//
//check if session has the async state we need
//
if (_hInet)
{
if ((_fAsync && !newAsync) || (!_fAsync && newAsync)) //XOR
{
//state is not the same, close session
WinHttpCloseHandle(_hInet);
_hInet = NULL;
}
}
_fAsync = newAsync;
//
// Open an Internet Session if one does not already exist.
//
if (!_hInet)
{
_hInet = WinHttpOpen(
GetUserAgentString(),
_dwProxySetting,
_bstrProxyServer,
_bstrBypassList,
#ifdef TRUE_ASYNC
_fAsync ? WINHTTP_FLAG_ASYNC : 0
#else
0
#endif//TRUE_ASYNC
);
if (!_hInet)
goto ErrorFail;
DWORD dwEnableFlags = _bEnableSslImpersonation ? 0 : WINHTTP_ENABLE_SSL_REVERT_IMPERSONATION;
if (dwEnableFlags)
{
WinHttpSetOption(_hInet,
WINHTTP_OPTION_ENABLE_FEATURE,
(LPVOID)&dwEnableFlags,
sizeof(dwEnableFlags));
}
}
//
// If any timeouts were set previously, apply them.
//
if (_bSetTimeouts)
{
if (!WinHttpSetTimeouts(_hInet, (int)_ResolveTimeout,
(int)_ConnectTimeout,
(int)_SendTimeout,
(int)_ReceiveTimeout))
goto ErrorFail;
}
//
// Set the code page on the Session handle; the Connect
// handle will also inherit this value.
//
if (!WinHttpSetOption(_hInet, WINHTTP_OPTION_CODEPAGE,
&_dwCodePage,
sizeof(_dwCodePage)))
goto ErrorFail;
if (!WinHttpSetOption(_hInet,
WINHTTP_OPTION_SECURE_PROTOCOLS,
(LPVOID)&_dwSecureProtocols,
sizeof(_dwSecureProtocols)))
goto ErrorFail;
if (!WinHttpSetOption(_hInet,
WINHTTP_OPTION_REDIRECT_POLICY,
(LPVOID)&_dwRedirectPolicy,
sizeof(DWORD)))
goto ErrorFail;
if (!WinHttpSetOption(_hInet,
WINHTTP_OPTION_CONFIGURE_PASSPORT_AUTH,
(LPVOID)&_dwPassportConfig,
sizeof(DWORD)))
goto ErrorFail;
// Break the URL into the required components
ZeroMemory(&url, sizeof(URL_COMPONENTSW));
url.dwStructSize = sizeof(URL_COMPONENTSW);
url.dwHostNameLength = 1;
url.dwUrlPathLength = 1;
url.dwExtraInfoLength = 1;
if (!WinHttpCrackUrl(bstrUrl, 0, 0, &url))
goto ErrorFail;
// Check for non-http schemes
if (url.nScheme != INTERNET_SCHEME_HTTP && url.nScheme != INTERNET_SCHEME_HTTPS)
goto ErrorUnsupportedScheme;
// IE6/Reno Bug #6236: if the client does not specify a resource path,
// then add the "/".
if (url.dwUrlPathLength == 0)
{
INET_ASSERT(url.dwExtraInfoLength == 0);
url.lpszUrlPath = L"/";
url.dwUrlPathLength = 1;
}
bstrHostName = DL(SysAllocStringLen)(url.lpszHostName, url.dwHostNameLength);
bstrUrlPath = DL(SysAllocStringLen)(url.lpszUrlPath, lstrlenW(url.lpszUrlPath));
if (!bstrHostName || !bstrUrlPath)
goto ErrorOutOfMemory;
INET_ASSERT(_hConnection == NULL);
INET_ASSERT(_hHTTP == NULL);
_hConnection = WinHttpConnect(
_hInet,
bstrHostName,
url.nPort,
0);
if (!_hConnection)
goto ErrorFail;
if (url.nScheme == INTERNET_SCHEME_HTTPS)
{
dwHttpOpenFlags |= WINHTTP_FLAG_SECURE;
}
//
// Apply EscapePercentInURL option.
//
dwHttpOpenFlags |= _dwEscapeFlag;
_hHTTP = WinHttpOpenRequest(
_hConnection,
bstrMethod,
bstrUrlPath,
_bHttp1_1Mode ? L"HTTP/1.1" : L"HTTP/1.0",
NULL,
NULL,
dwHttpOpenFlags);
if (!_hHTTP)
goto ErrorFail;
if ((StrCmpIW(bstrMethod, L"GET") == 0) || (StrCmpIW(bstrMethod, L"HEAD") == 0))
{
_bMethodGET = TRUE;
}
if (_fCheckForRevocation)
{
DWORD dwOptions = WINHTTP_ENABLE_SSL_REVOCATION;
WinHttpSetOption(_hHTTP,
WINHTTP_OPTION_ENABLE_FEATURE,
(LPVOID)&dwOptions,
sizeof(dwOptions));
}
// Set the SSL ignore flags through an undocumented front door
if (_dwSslIgnoreFlags)
{
WinHttpSetOption(_hHTTP,
WINHTTP_OPTION_SECURITY_FLAGS,
(LPVOID)&_dwSslIgnoreFlags,
sizeof(_dwSslIgnoreFlags));
}
if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_AUTOLOGON_POLICY,
(void *) &_dwAutoLogonPolicy,
sizeof(_dwAutoLogonPolicy)))
goto ErrorFail;
dw = (DWORD)_lMaxAutomaticRedirects;
if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS,
(void *) &dw, sizeof(dw)))
goto ErrorFail;
dw = (DWORD)_lMaxResponseHeaderSize;
if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE,
(void *) &dw, sizeof(dw)))
goto ErrorFail;
dw = (DWORD)_lMaxResponseDrainSize;
if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE,
(void *) &dw, sizeof(dw)))
goto ErrorFail;
SetState(CHttpRequest::OPENED);
hr = NOERROR;
Cleanup:
if (bstrHostName)
DL(SysFreeString)(bstrHostName);;
if (bstrUrlPath)
DL(SysFreeString)(bstrUrlPath);
SetErrorInfo(hr);
DEBUG_LEAVE_API(hr);
return hr;
ErrorUnsupportedScheme:
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_UNRECOGNIZED_SCHEME);
goto Cleanup;
ErrorOutOfMemory:
hr = E_OUTOFMEMORY;
goto Error;
ErrorFail:
if (_hHTTP)
{
WinHttpCloseHandle(_hHTTP);
_hHTTP = NULL;
}
if (_hConnection)
{
WinHttpCloseHandle(_hConnection);
_hConnection = NULL;
}
hr = HRESULT_FROM_WIN32(GetLastError());
goto Cleanup;
Error:
goto Cleanup;
}
/*
* CHttpRequest::SetRequestHeader
*
* Purpose:
* Set a request header
*
* Parameters:
* bstrHeader IN HTTP request header
* bstrValue IN Header value
*
* Errors:
* E_FAIL
* E_INVALIDARG
* E_UNEXPECTED
*/
STDMETHODIMP
CHttpRequest::SetRequestHeader(BSTR bstrHeader, BSTR bstrValue)
{
WCHAR * wszHeaderValue = NULL;
DWORD cchHeaderValue;
DWORD dwModifiers = HTTP_ADDREQ_FLAG_ADD;
HRESULT hr = NOERROR;
// Validate header parameter (null or zero-length value is allowed)
if (!bstrHeader
|| !IsValidBstr(bstrHeader)
|| (lstrlenW(bstrHeader)==0)
|| !IsValidBstr(bstrValue)
|| !IsValidHeaderName(bstrHeader))
return E_INVALIDARG;
DEBUG_ENTER_API((DBG_HTTP,
Dword,
"IWinHttpRequest::SetRequestHeader",
"header: %Q, value: %Q",
bstrHeader,
bstrValue
));
// Validate state
if (_eState < CHttpRequest::OPENED)
goto ErrorCannotCallBeforeOpen;
else if (_eState >= CHttpRequest::SENDING)
goto ErrorCannotCallAfterSend;
// Ignore attempts to set the Content-Length header; the
// content length is computed and sent automatically.
if (StrCmpIW(bstrHeader, L"Content-Length") == 0)
goto Cleanup;
if (StrCmpIW(bstrHeader, L"Cookie") == 0)
dwModifiers |= HTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON;
cchHeaderValue = lstrlenW(bstrHeader) + lstrlenW(bstrValue)
+ 2 /* wcslen(L": ") */
+ 2 /* wcslen(L"\r\n") */;
wszHeaderValue = New WCHAR [cchHeaderValue + 1];
if (!wszHeaderValue)
goto ErrorOutOfMemory;
wcscpy(wszHeaderValue, bstrHeader);
wcscat(wszHeaderValue, L": ");
if (bstrValue)
wcscat(wszHeaderValue, bstrValue);
wcscat(wszHeaderValue, L"\r\n");
// For blank header values, erase the header by setting the
// REPLACE flag.
if (lstrlenW(bstrValue) == 0)
{
dwModifiers |= HTTP_ADDREQ_FLAG_REPLACE;
}
if (! WinHttpAddRequestHeaders(_hHTTP, wszHeaderValue,
(DWORD)-1L,
dwModifiers))
goto ErrorFail;
hr = NOERROR;
Cleanup:
if (wszHeaderValue)
delete [] wszHeaderValue;
SetErrorInfo(hr);
DEBUG_LEAVE_API(hr);
return hr;
ErrorOutOfMemory:
hr = E_OUTOFMEMORY;
goto Error;
ErrorCannotCallBeforeOpen:
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN);
goto Error;
ErrorCannotCallAfterSend:
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND);
goto Error;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
goto Error;
Error:
goto Cleanup;
}
/*
* CHttpRequest::SetRequiredRequestHeaders
*
* Purpose:
* Set implicit request headers
*
* Parameters:
* None
*
* Errors:
* E_FAIL
* E_UNEXPECTED
* E_OUTOFMEMORY
* Errors from WinHttpAddRequestHeaders and WinHttpSendRequest
*/
HRESULT
CHttpRequest::SetRequiredRequestHeaders()
{
HRESULT hr = NOERROR;
if (!(_bMethodGET && _cbRequestBody == 0))
{
char szContentLengthHeader[sizeof("Content-Length") +
sizeof(": ") +
15 + // content-length value
sizeof("\r\n") + 1];
lstrcpy(szContentLengthHeader, "Content-Length: ");
_ltoa(_cbRequestBody,
szContentLengthHeader + 16, /* "Content-Length: " */
10);
lstrcat(szContentLengthHeader, "\r\n");
if (! HttpAddRequestHeadersA(_hHTTP, szContentLengthHeader,
(DWORD)-1L,
HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE))
{
hr = E_FAIL;
}
}
// Add an Accept: */* header if no other Accept header
// has been set. Ignore any return code, since it is
// not fatal if this fails.
HttpAddRequestHeadersA(_hHTTP, "Accept: */*",
(DWORD)-1L,
HTTP_ADDREQ_FLAG_ADD_IF_NEW);
if (_bSetUtf8Charset)
{
CHAR szContentType[256];
BOOL fRetCode;
DWORD cb = sizeof(szContentType) - sizeof("Content-Type: ") - sizeof("; Charset=UTF-8");
LPSTR pszNewContentType = NULL;
lstrcpy(szContentType, "Content-Type: ");
fRetCode = HttpQueryInfoA(_hHTTP,
HTTP_QUERY_FLAG_REQUEST_HEADERS | HTTP_QUERY_CONTENT_TYPE,
WINHTTP_HEADER_NAME_BY_INDEX,
szContentType + sizeof("Content-Type: ") - 1,
&cb,
0);
if (fRetCode)
{
if (!StrStrIA(szContentType, "charset"))
{
lstrcat(szContentType, "; Charset=UTF-8");
pszNewContentType = szContentType;
}
}
else if (GetLastError() == ERROR_WINHTTP_HEADER_NOT_FOUND)
{
pszNewContentType = "Content-Type: text/plain; Charset=UTF-8";
}
if (pszNewContentType)
{
fRetCode = HttpAddRequestHeadersA(_hHTTP, pszNewContentType,
(DWORD)-1L,
HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE);
INET_ASSERT(fRetCode);
}
}
return hr;
}
#if !defined(TRUE_ASYNC)
DWORD WINAPI WinHttpRequestSendAsync(LPVOID lpParameter)
{
#ifdef WINHTTP_FOR_MSXML
//
// MSXML needs to initialize its thread local storage data.
// It does not do this during DLL_THREAD_ATTACH, so our
// worker thread must explicitly call into MSXML to initialize
// its TLS for this thread.
//
InitializeMsxmlTLS();
#endif
HRESULT hr;
DWORD dwExitCode;
CHttpRequest * pWinHttpRequest = reinterpret_cast<CHttpRequest *>(lpParameter);
INET_ASSERT(pWinHttpRequest != NULL);
dwExitCode = pWinHttpRequest->SendAsync();
pWinHttpRequest->Release();
// If this worker thread was impersonating, revert to the default
// process identity.
RevertToSelf();
return dwExitCode;
}
#endif//!TRUE_ASYNC
/*
* CHttpRequest::CreateAsyncWorkerThread
*
*/
#if !defined(TRUE_ASYNC)
HRESULT
CHttpRequest::CreateAsyncWorkerThread()
{
DWORD dwWorkerThreadId;
HANDLE hThreadToken = NULL;
HRESULT hr;
hr = _CP.CreateEventSinksMarshaller();
if (FAILED(hr))
return hr;
hr = NOERROR;
//
// If the current thread is impersonating, then grab its access token
// and revert the current thread (so it is nolonger impersonating).
// After creating the worker thread, we will make the main thread
// impersonate again. Apparently you should not call CreateThread
// while impersonating.
//
if (OpenThreadToken(GetCurrentThread(), (TOKEN_IMPERSONATE | TOKEN_READ),
FALSE,
&hThreadToken))
{
INET_ASSERT(hThreadToken != 0);
RevertToSelf();
}
// Create the worker thread suspended.
_hWorkerThread = CreateThread(NULL, 0, WinHttpRequestSendAsync,
(void *)static_cast<CHttpRequest *>(this),
CREATE_SUSPENDED,
&dwWorkerThreadId);
// If CreateThread fails, grab the error code now.
if (!_hWorkerThread)
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
//
// If the main thread was impersonating, then:
// (1) have the worker thread impersonate the same user, and
// (2) have the main thread resume impersonating the
// client too (since we called RevertToSelf above).
//
if (hThreadToken)
{
if (_hWorkerThread)
{
(void)SetThreadToken(&_hWorkerThread, hThreadToken);
}
(void)SetThreadToken(NULL, hThreadToken);
CloseHandle(hThreadToken);
}
// If the worker thread was created, start it running.
if (_hWorkerThread)
{
// The worker thread owns a ref count on the component.
// Don't call AddRef() as it will attribute the ref count
// to the main thread.
_cRefs++;
ResumeThread(_hWorkerThread);
}
else
{
_CP.ShutdownEventSinksMarshaller();
_CP.ReleaseEventSinksMarshaller();
}
return hr;
}
#endif//!TRUE_ASYNC
/*
* CHttpRequest::Send
*
* Purpose:
* Send the HTTP request
*
* Parameters:
* varBody IN Request body
*
* Errors:
* E_FAIL
* E_UNEXPECTED
* E_OUTOFMEMORY
* Errors from WinHttpAddRequestHeaders and WinHttpSendRequest
*/
STDMETHODIMP
CHttpRequest::Send(VARIANT varBody)
{
HRESULT hr = NOERROR;
BOOL fRetCode = FALSE;
BOOL fRetryWithClientAuth = TRUE;
// Validate that we are called from our apartment's thread.
if (GetCurrentThreadId() != _dwMainThreadId)
return RPC_E_WRONG_THREAD;
// Validate parameter
if (!IsValidVariant(varBody))
return E_INVALIDARG;
DEBUG_ENTER2_API((DBG_HTTP,
Dword,
"IWinHttpRequest::Send",
"VARIANT varBody"
));
TRACE_ENTER2_API((DBG_HTTP,
Dword,
"IWinHttpRequest::Send",
_hHTTP,
"VARIANT varBody"
));
// Validate state
if (_eState < CHttpRequest::OPENED)
goto ErrorCannotCallBeforeOpen;
if (_fAsync)
{
if ((_eState > CHttpRequest::OPENED) && (_eState < CHttpRequest::RESPONSE))
goto ErrorPending;
}
// Get the request body
hr = SetRequestBody(varBody);
if (FAILED(hr))
goto Error;
hr = SetRequiredRequestHeaders();
if (FAILED(hr))
goto Error;
try_again:
SetState(CHttpRequest::SENDING);
if (_fAsync)
{
#if !defined(TRUE_ASYNC)
hr = CreateAsyncWorkerThread();
#else
hr = StartAsyncSend();
#endif//!TRUE_ASYNC
if (FAILED(hr))
goto Error;
}
else
{
//register callback
if (WINHTTP_INVALID_STATUS_CALLBACK ==
WinHttpSetStatusCallback(_hHTTP,
SyncCallback,
WINHTTP_CALLBACK_STATUS_SECURE_FAILURE,
NULL))
goto ErrorFail;
// Send the HTTP request
fRetCode = WinHttpSendRequest(
_hHTTP,
NULL, 0, // No header info here
_szRequestBuffer,
_cbRequestBody,
_cbRequestBody,
reinterpret_cast<DWORD_PTR>(this));
if (!fRetCode)
{
goto ErrorFail;
}
SetState(CHttpRequest::SENT);
fRetCode = WinHttpReceiveResponse(_hHTTP, NULL);
if (!fRetCode)
{
goto ErrorFail;
}
// Read the response data
hr = ReadResponse();
if (FAILED(hr))
goto Error;
}
hr = NOERROR;
Cleanup:
SetErrorInfo(hr);
DEBUG_LEAVE_API(hr);
return hr;
ErrorCannotCallBeforeOpen:
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN);
goto Error;
ErrorPending:
hr = E_PENDING;
goto Error;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
if (!_fAsync &&
hr == HRESULT_FROM_WIN32(ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED) &&
fRetryWithClientAuth)
{
fRetryWithClientAuth = FALSE;
// Try to enumerate the first cert in the reverted user context,
// select the cert (per object sesssion, not global), and send
// the request again.
if (SelectCertificate())
goto try_again;
}
else if (hr == HRESULT_FROM_WIN32(ERROR_WINHTTP_SECURE_FAILURE))
{
INET_ASSERT(FAILED(_hrSecureFailure));
hr = _hrSecureFailure;
}
_CP.FireOnError(hr);
goto Cleanup;
Error:
goto Cleanup;
}
/*
* CHttpRequest::SendAsync
*
* Purpose:
* Send the HTTP request
*
* Parameters:
* varBody IN Request body
*
* Errors:
* E_FAIL
* E_UNEXPECTED
* E_OUTOFMEMORY
* Errors from WinHttpAddRequestHeaders and WinHttpSendRequest
*/
#if !defined(TRUE_ASYNC)
DWORD
CHttpRequest::SendAsync()
{
DWORD dwLastError = 0;
DWORD fRetCode;
HRESULT hr;
BOOL fRetryWithClientAuth = TRUE;
try_again:
if (_bAborted || !_hHTTP)
goto ErrorUnexpected;
// Send the HTTP request
fRetCode = WinHttpSendRequest(
_hHTTP,
NULL, 0, // No header info here
_szRequestBuffer,
_cbRequestBody,
_cbRequestBody,
0);
if (!fRetCode)
goto ErrorFail;
SetState(CHttpRequest::SENT);
fRetCode = WinHttpReceiveResponse(_hHTTP, NULL);
if (!fRetCode)
goto ErrorFail;
if (!_bAborted)
{
hr = ReadResponse();
if (FAILED(hr))
{
if (hr == E_OUTOFMEMORY)
goto ErrorOutOfMemory;
goto ErrorFail;
}
}
hr = NOERROR;
Cleanup:
_hrAsyncResult = hr;
return dwLastError;
ErrorUnexpected:
dwLastError = ERROR_WINHTTP_INTERNAL_ERROR;
hr = HRESULT_FROM_WIN32(dwLastError);
goto Cleanup;
ErrorFail:
dwLastError = GetLastError();
if (dwLastError == ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED &&
fRetryWithClientAuth)
{
fRetryWithClientAuth = FALSE;
// Try to enumerate the first cert in the reverted user context,
// select the cert (per object sesssion, not global), and send
// the request again.
if (SelectCertificate())
{
SetState(CHttpRequest::SENDING);
goto try_again;
}
}
hr = HRESULT_FROM_WIN32(dwLastError);
goto Cleanup;
ErrorOutOfMemory:
dwLastError = ERROR_NOT_ENOUGH_MEMORY;
hr = E_OUTOFMEMORY;
goto Cleanup;
}
#endif//!TRUE_ASYNC
STDMETHODIMP
CHttpRequest::WaitForResponse(VARIANT varTimeout, VARIANT_BOOL * pboolSucceeded)
{
HRESULT hr = NOERROR;
bool bSucceeded= true;
DWORD dwTimeout;
// Validate that we are called from our apartment's thread.
if (GetCurrentThreadId() != _dwMainThreadId)
return RPC_E_WRONG_THREAD;
// Validate parameters; null pboolSucceeded pointer is Ok.
if (!IsValidVariant(varTimeout) ||
(pboolSucceeded &&
IsBadWritePtr(pboolSucceeded, sizeof(VARIANT_BOOL))))
return E_INVALIDARG;
// Get the timeout value. Disallow numbers
// less than -1 (which means INFINITE).
if (GetLongFromVariant(varTimeout, INFINITE) < -1L)
return E_INVALIDARG;
dwTimeout = GetDwordFromVariant(varTimeout, INFINITE);
DEBUG_ENTER_API((DBG_HTTP,
Dword,
"IWinHttpRequest::WaitForResponse",
"Timeout: %d, VARIANT_BOOL* pboolSucceeded: %#x",
dwTimeout,
pboolSucceeded
));
// Validate state.
if (_eState < CHttpRequest::SENDING)
goto ErrorCannotCallBeforeSend;
//
// WaitForResponse is a no-op if we're not in async mode.
//
if (_fAsync &&
#ifdef TRUE_ASYNC
_hCompleteEvent
#else
_hWorkerThread
#endif
)
{
//
// Has the worker thread has already finished or event signaled?
//
if (WaitForSingleObject(
#ifdef TRUE_ASYNC
_hCompleteEvent
#else
_hWorkerThread
#endif
, 0) == WAIT_TIMEOUT)
{
//
// Convert Timeout from seconds to milliseconds. Any timeout
// value over 4 million seconds (~46 days) is "rounded up"
// to INFINITE. :)
//
if (dwTimeout > 4000000) // avoid overflow
{
dwTimeout = INFINITE;
}
else
{
// convert to milliseconds
dwTimeout *= 1000;
}
DWORD dwStartTime;
DWORD dwWaitResult;
bool bWaitAgain;
do
{
dwStartTime = GetTickCount();
dwWaitResult = MsgWaitForMultipleObjects(1,
#ifdef TRUE_ASYNC
&_hCompleteEvent
#else
&_hWorkerThread
#endif
,
FALSE,
dwTimeout,
QS_ALLINPUT);
bWaitAgain = false;
switch (dwWaitResult)
{
case WAIT_OBJECT_0:
// Thread exited.
MessageLoop();
hr = _hrAsyncResult;
bSucceeded = SUCCEEDED(hr);
break;
case WAIT_OBJECT_0 + 1:
// Message waiting in the message queue.
// Run message pump to clear queue.
MessageLoop();
//check if object was not aborted
if (_eState != CHttpRequest::CREATED)
bWaitAgain = true;
else
hr = _hrAsyncResult;
break;
case WAIT_TIMEOUT:
// Timeout.
bSucceeded = false;
break;
case (-1):
default:
// Error.
goto ErrorFail;
break;
}
// If we're going to continue waiting for the worker
// thread, decrease timeout appropriately.
if (bWaitAgain)
{
dwTimeout = UpdateTimeout(dwTimeout, dwStartTime);
}
} while (bWaitAgain);
}
else
{
// If the worker thread is already done, then pump messages
// to clear any events that it may have posted.
MessageLoop();
hr = _hrAsyncResult;
bSucceeded = SUCCEEDED(hr);
}
}
//check if object was aborted
if (_eState == CHttpRequest::CREATED)
bSucceeded = false;
Cleanup:
if (pboolSucceeded)
{
*pboolSucceeded = (bSucceeded ? VARIANT_TRUE : VARIANT_FALSE);
}
if (hr == HRESULT_FROM_WIN32(ERROR_WINHTTP_SECURE_FAILURE))
{
INET_ASSERT(FAILED(_hrSecureFailure));
hr = _hrSecureFailure;
}
SetErrorInfo(hr);
DEBUG_PRINT_API(ASYNC, INFO, (bSucceeded ? "Succeeded set to true\n" : "Succeeded set to false\n"))
DEBUG_LEAVE_API(hr);
return hr;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
goto Error;
ErrorCannotCallBeforeSend:
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND);
goto Error;
Error:
bSucceeded = false;
goto Cleanup;
}
STDMETHODIMP
CHttpRequest::Abort()
{
DEBUG_ENTER_API((DBG_HTTP,
Dword,
"IWinHttpRequest::Abort",
NULL
));
// Validate that we are called from our apartment's thread.
if (GetCurrentThreadId() != _dwMainThreadId)
return RPC_E_WRONG_THREAD;
//
// Abort if not already aborted and not in the CREATED state,
// (meaning at least the Open method has been called).
//
if ((_eState > CHttpRequest::CREATED) && !_bAborted)
{
DWORD error;
_bAborted = true;
// Tell our connection point manager to abort any
// events "in flight"--i.e., abort any events that
// may have already been posted by the worker thread.
_CP.FreezeEvents();
if (_hHTTP)
{
//
// Add a ref count on the HTTP Request handle.
//
INET_ASSERT(_hAbortedRequestObject == NULL);
error = MapHandleToAddress(_hHTTP, (LPVOID *)&_hAbortedRequestObject, FALSE);
INET_ASSERT(error == 0);
WinHttpCloseHandle(_hHTTP);
_hHTTP = NULL;
}
if (_hConnection)
{
//
// Add a ref count on the Connection handle.
//
INET_ASSERT(_hAbortedConnectObject == NULL);
error = MapHandleToAddress(_hConnection, (LPVOID *)&_hAbortedConnectObject, FALSE);
INET_ASSERT(error == 0);
WinHttpCloseHandle(_hConnection);
_hConnection = NULL;
}
// Recycle the object.
Recycle();
}
DEBUG_LEAVE_API(NOERROR);
return NOERROR;
}
STDMETHODIMP
CHttpRequest::SetTimeouts(long ResolveTimeout, long ConnectTimeout, long SendTimeout, long ReceiveTimeout)
{
if ((ResolveTimeout < -1L) || (ConnectTimeout < -1L) ||
(SendTimeout < -1L) || (ReceiveTimeout < -1L))
{
return E_INVALIDARG;
}
HRESULT hr = NOERROR;
_ResolveTimeout = (DWORD) ResolveTimeout;
_ConnectTimeout = (DWORD) ConnectTimeout;
_SendTimeout = (DWORD) SendTimeout;
_ReceiveTimeout = (DWORD) ReceiveTimeout;
_bSetTimeouts = true;
if (_hHTTP)
{
DWORD fRetCode;
fRetCode = WinHttpSetTimeouts(_hHTTP, (int)_ResolveTimeout,
(int)_ConnectTimeout,
(int)_SendTimeout,
(int)_ReceiveTimeout);
if (!fRetCode)
hr = E_INVALIDARG;
}
return hr;
}
STDMETHODIMP
CHttpRequest::SetClientCertificate(BSTR ClientCertificate)
{
BOOL fCertLocalMachine = FALSE;
BSTR bstrCertStore = NULL;
BSTR bstrCertSubject = NULL;
HRESULT hr;
if (!IsValidBstr(ClientCertificate))
goto ErrorInvalidArg;
hr = ParseSelectedCert(ClientCertificate,
&fCertLocalMachine,
&bstrCertStore,
&bstrCertSubject
);
// Only fill in new selection if parsed successfully.
if (hr == S_OK)
{
_fCertLocalMachine = fCertLocalMachine;
if (_bstrCertStore)
DL(SysFreeString)(_bstrCertStore);
_bstrCertStore = bstrCertStore;
if (_bstrCertSubject)
DL(SysFreeString)(_bstrCertSubject);
_bstrCertSubject = bstrCertSubject;
}
if (_hHTTP)
{
// We will try again later if this fails now, so
// don't worry about detecting an error.
SelectCertificate();
}
Exit:
SetErrorInfo(hr);
return hr;
ErrorInvalidArg:
hr = E_INVALIDARG;
goto Exit;
}
STDMETHODIMP
CHttpRequest::SetAutoLogonPolicy(WinHttpRequestAutoLogonPolicy AutoLogonPolicy)
{
HRESULT hr;
switch (AutoLogonPolicy)
{
case AutoLogonPolicy_Always:
_dwAutoLogonPolicy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;
break;
case AutoLogonPolicy_OnlyIfBypassProxy:
_dwAutoLogonPolicy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
break;
case AutoLogonPolicy_Never:
_dwAutoLogonPolicy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
break;
default:
goto ErrorInvalidArg;
}
if (_hHTTP)
{
if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_AUTOLOGON_POLICY,
(void *) &_dwAutoLogonPolicy,
sizeof(_dwAutoLogonPolicy)))
goto ErrorFail;
}
hr = NOERROR;
Exit:
SetErrorInfo(hr);
return hr;
ErrorInvalidArg:
hr = E_INVALIDARG;
goto Exit;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
goto Exit;
}
/*
* CHttpRequest::SetRequestBody
*
* Purpose:
* Set the request body
*
* Parameters:
* varBody IN Request body
*
* Errors:
* E_FAIL
* E_OUTOFMEMORY
* E_UNEXPECTED
*/
HRESULT
CHttpRequest::SetRequestBody(VARIANT varBody)
{
HRESULT hr = NOERROR;
VARIANT varTemp;
SAFEARRAY * psa = NULL;
VARIANT * pvarBody = NULL;
// varBody is validated by CHttpRequest::Send().
DL(VariantInit)(&varTemp);
// Free a previously set body and its response
if (_szRequestBuffer)
{
delete [] _szRequestBuffer;
_szRequestBuffer = NULL;
_cbRequestBody = 0;
}
_bSetUtf8Charset = false;
SafeRelease(_pResponseStream);
_cbResponseBody = 0;
if (V_ISBYREF(&varBody))
{
pvarBody = varBody.pvarVal;
}
else
{
pvarBody = &varBody;
}
// Check for an empty body
if (V_VT(pvarBody) == VT_EMPTY ||
V_VT(pvarBody) == VT_NULL ||
V_VT(pvarBody) == VT_ERROR)
goto Cleanup;
//
// Extract the body: BSTR or array of UI1
//
// We need to explicitly look for the byte array since it will be converted
// to a BSTR by DL(VariantChangeType).
if (V_ISARRAY(pvarBody) && (V_VT(pvarBody) & VT_UI1))
{
BYTE * pb = NULL;
long lUBound = 0;
long lLBound = 0;
psa = V_ARRAY(pvarBody);
// We only handle 1 dimensional arrays
if (DL(SafeArrayGetDim)(psa) != 1)
goto ErrorFail;
// Get access to the blob
hr = DL(SafeArrayAccessData)(psa, (void **)&pb);
if (FAILED(hr))
goto Error;
// Compute the data size from the upper and lower array bounds
hr = DL(SafeArrayGetLBound)(psa, 1, &lLBound);
if (FAILED(hr))
goto Error;
hr = DL(SafeArrayGetUBound)(psa, 1, &lUBound);
if (FAILED(hr))
goto Error;
_cbRequestBody = lUBound - lLBound + 1;
if (_cbRequestBody > 0)
{
// Copy the data into the request buffer
_szRequestBuffer = New char [_cbRequestBody];
if (!_szRequestBuffer)
{
_cbRequestBody = 0;
goto ErrorOutOfMemory;
}
::memcpy(_szRequestBuffer, pb, _cbRequestBody);
}
DL(SafeArrayUnaccessData)(psa);
psa = NULL;
}
else
{
BSTR bstrBody = NULL;
bool bFreeString = false;
//
// Try a BSTR; avoiding to call GetBSTRFromVariant (which makes
// a copy) if possible.
//
if (V_VT(pvarBody) == VT_BSTR)
{
bstrBody = V_BSTR(pvarBody); // direct BSTR string, do not free
bFreeString = false;
}
else
{
hr = GetBSTRFromVariant(*pvarBody, &bstrBody);
if (SUCCEEDED(hr))
{
bFreeString = true;
}
else if (hr == E_INVALIDARG)
{
// GetBSTRFromVariant will return E_INVALIDARG if the
// call to VariantChangeType AVs. The VARIANT may be
// valid, but may simply not contain a BSTR, so if
// some other error is returned (most likely
// DISP_E_MISMATCH), then continue and see if the
// VARIANT contains an IStream object.
goto Error;
}
}
if (bstrBody)
{
hr = BSTRToUTF8(&_szRequestBuffer, &_cbRequestBody, bstrBody, &_bSetUtf8Charset);
if (bFreeString)
DL(SysFreeString)(bstrBody);
if (FAILED(hr))
goto Error;
}
else
{
// Try a Stream
if (V_VT(pvarBody) == VT_UNKNOWN || V_VT(pvarBody) == VT_DISPATCH)
{
IStream * pStm = NULL;
__try
{
hr = pvarBody->punkVal->QueryInterface(
IID_IStream,
(void **)&pStm);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
if (FAILED(hr))
goto Error;
hr = ReadFromStream(
&_szRequestBuffer,
&_cbRequestBody,
pStm);
pStm->Release();
if (FAILED(hr))
goto Error;
}
}
}
hr = NOERROR;
Cleanup:
DL(VariantClear)(&varTemp);
if (psa)
DL(SafeArrayUnaccessData)(psa);
return hr;
ErrorOutOfMemory:
hr = E_OUTOFMEMORY;
goto Error;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
goto Error;
Error:
goto Cleanup;
}
/*
* CHttpRequest::GetResponseHeader
*
* Purpose:
* Get a response header
*
* Parameters:
* bstrHeader IN HTTP request header
* pbstrValue OUT Header value
*
* Errors:
* E_FAIL
* E_INVALIDARG
* E_OUTOFMEMORY
* E_UNEXPECTED
* Errors from WinHttpQueryHeaders
*/
STDMETHODIMP
CHttpRequest::GetResponseHeader(BSTR bstrHeader, BSTR * pbstrValue)
{
return _GetResponseHeader(bstrHeader, pbstrValue);
}
#ifdef TRUE_ASYNC
HRESULT
CHttpRequest::_GetResponseHeader(OLECHAR * wszHeader, BSTR * pbstrValue)
{
HRESULT hr;
// Validate state
if (_eState < CHttpRequest::SENDING)
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND);
else
hr = _GetResponseHeader2(wszHeader, pbstrValue, _hHTTP);
SetErrorInfo(hr);
return hr;
}
HRESULT
CHttpRequest::_GetResponseHeader2(OLECHAR * wszHeader, BSTR * pbstrValue, HINTERNET hInternet)
{
HRESULT hr = NOERROR;
WCHAR * wszHeaderValue = NULL;
DWORD cb;
BOOL fRetCode;
// Validate parameters
if (IsBadReadPtr(wszHeader, 2) ||
IsBadWritePtr(pbstrValue, sizeof(BSTR)) ||
!lstrlenW(wszHeader))
return E_INVALIDARG;
*pbstrValue = NULL;
cb = 64; // arbitrary size in which many header values will fit
wszHeaderValue = New WCHAR[cb];
if (!wszHeaderValue)
goto ErrorOutOfMemory;
RetryQuery:
// Determine length of requested header
fRetCode = WinHttpQueryHeaders(
hInternet,
HTTP_QUERY_CUSTOM,
wszHeader,
wszHeaderValue,
&cb,
0);
// Check for ERROR_INSUFFICIENT_BUFFER - reallocate the buffer and retry
if (!fRetCode)
{
switch (GetLastError())
{
case ERROR_INSUFFICIENT_BUFFER:
{
delete [] wszHeaderValue;
wszHeaderValue = New WCHAR[cb]; // should this be cb/2?
if (!wszHeaderValue)
goto ErrorOutOfMemory;
goto RetryQuery;
}
case ERROR_HTTP_HEADER_NOT_FOUND:
goto ErrorFail;
default:
goto ErrorFail;
}
}
*pbstrValue = DL(SysAllocString)(wszHeaderValue);
if (!*pbstrValue)
goto ErrorOutOfMemory;
hr = NOERROR;
Cleanup:
if (wszHeaderValue)
delete [] wszHeaderValue;
return hr;
ErrorOutOfMemory:
hr = E_OUTOFMEMORY;
goto Error;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
goto Error;
Error:
goto Cleanup;
}
#else//TRUE_ASYNC
HRESULT
CHttpRequest::_GetResponseHeader(OLECHAR * wszHeader, BSTR * pbstrValue)
{
HRESULT hr = NOERROR;
WCHAR * wszHeaderValue = NULL;
DWORD cb;
BOOL fRetCode;
// Validate parameters
if (IsBadReadPtr(wszHeader, 2) ||
IsBadWritePtr(pbstrValue, sizeof(BSTR)) ||
!lstrlenW(wszHeader))
return E_INVALIDARG;
// Validate state
if (_eState < CHttpRequest::SENDING)
goto ErrorCannotCallBeforeSend;
*pbstrValue = NULL;
cb = 64; // arbitrary size in which many header values will fit
wszHeaderValue = New WCHAR[cb];
if (!wszHeaderValue)
goto ErrorOutOfMemory;
RetryQuery:
// Determine length of requested header
fRetCode = WinHttpQueryHeaders(
_hHTTP,
HTTP_QUERY_CUSTOM,
wszHeader,
wszHeaderValue,
&cb,
0);
// Check for ERROR_INSUFFICIENT_BUFFER - reallocate the buffer and retry
if (!fRetCode)
{
switch (GetLastError())
{
case ERROR_INSUFFICIENT_BUFFER:
{
delete [] wszHeaderValue;
wszHeaderValue = New WCHAR[cb]; // should this be cb/2?
if (!wszHeaderValue)
goto ErrorOutOfMemory;
goto RetryQuery;
}
case ERROR_HTTP_HEADER_NOT_FOUND:
goto ErrorFail;
default:
goto ErrorFail;
}
}
*pbstrValue = DL(SysAllocString)(wszHeaderValue);
if (!*pbstrValue)
goto ErrorOutOfMemory;
hr = NOERROR;
Cleanup:
if (wszHeaderValue)
delete [] wszHeaderValue;
SetErrorInfo(hr);
return hr;
ErrorOutOfMemory:
hr = E_OUTOFMEMORY;
goto Error;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
goto Error;
ErrorCannotCallBeforeSend:
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND);
goto Error;
Error:
goto Cleanup;
}
#endif//TRUE_ASYNC
/*
* CHttpRequest::GetAllResponseHeaders
*
* Purpose:
* Return the response headers
*
* Parameters:
* pbstrHeaders IN/OUT CRLF delimited headers
*
* Errors:
* E_FAIL
* E_INVALIDARG
* E_OUTOFMEMORY
* E_UNEXPECTED
*/
STDMETHODIMP
CHttpRequest::GetAllResponseHeaders(BSTR * pbstrHeaders)
{
HRESULT hr = NOERROR;
BOOL fRetCode;
WCHAR * wszAllHeaders = NULL;
WCHAR * wszFirstHeader = NULL;
DWORD cb = 0;
// Validate parameter
if (IsBadWritePtr(pbstrHeaders, sizeof(BSTR)))
return E_INVALIDARG;
// Validate state
if (_eState < CHttpRequest::SENDING)
goto ErrorCannotCallBeforeSend;
*pbstrHeaders = NULL;
RetryQuery:
// Determine the length of all headers and then get all the headers
fRetCode = WinHttpQueryHeaders(
_hHTTP,
HTTP_QUERY_RAW_HEADERS_CRLF,
WINHTTP_HEADER_NAME_BY_INDEX,
wszAllHeaders,
&cb,
0);
if (!fRetCode)
{
// Allocate a buffer large enough to hold all headers
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
if (wszAllHeaders != NULL)
{
delete [] wszAllHeaders;
wszAllHeaders = NULL;
}
wszAllHeaders = New WCHAR[cb];
if (!wszAllHeaders)
goto ErrorOutOfMemory;
goto RetryQuery;
}
else
{
goto ErrorFail;
}
}
// Bypass status line - jump past first CRLF (0x13, 0x10)
wszFirstHeader = wcschr(wszAllHeaders, '\n');
if (*wszFirstHeader == '\n')
{
*pbstrHeaders = DL(SysAllocString)(wszFirstHeader + 1);
if (!*pbstrHeaders)
goto ErrorOutOfMemory;
}
hr = NOERROR;
Cleanup:
if (wszAllHeaders)
delete [] wszAllHeaders;
SetErrorInfo(hr);
return hr;
ErrorOutOfMemory:
hr = E_OUTOFMEMORY;
goto Error;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
goto Error;
ErrorCannotCallBeforeSend:
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND);
goto Error;
Error:
if (pbstrHeaders)
{
DL(SysFreeString)(*pbstrHeaders);
*pbstrHeaders = NULL;
}
goto Cleanup;
}
/*
* CHttpRequest::get_status
*
* Purpose:
* Get the request status code
*
* Parameters:
* plStatus OUT HTTP request status code
*
* Errors:
* E_FAIL
* E_INVALIDARG
* E_UNEXPECTED
*/
STDMETHODIMP
CHttpRequest::get_Status(long * plStatus)
{
HRESULT hr = NOERROR;
DWORD cb = sizeof(DWORD);
BOOL fRetCode;
DWORD dwStatus;
// Validate parameter
if (IsBadWritePtr(plStatus, sizeof(long)))
return E_INVALIDARG;
// Validate state
if (_eState < CHttpRequest::SENDING)
goto ErrorCannotCallBeforeSend;
else if (_eState < CHttpRequest::RECEIVING)
goto ErrorRequestInProgress;
fRetCode = HttpQueryInfoA(
_hHTTP,
HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX,
&dwStatus,
&cb,
0);
if (!fRetCode)
goto ErrorFail;
*plStatus = dwStatus;
hr = NOERROR;
Cleanup:
SetErrorInfo(hr);
return hr;
ErrorCannotCallBeforeSend:
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND);
goto Error;
ErrorRequestInProgress:
hr = E_PENDING;
goto Error;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
goto Error;
Error:
goto Cleanup;
}
/*
* CHttpRequest::get_StatusText
*
* Purpose:
* Get the request status text
*
* Parameters:
* pbstrStatus OUT HTTP request status text
*
* Errors:
* E_FAIL
* E_INVALIDARG
* E_UNEXPECTED
*/
STDMETHODIMP
CHttpRequest::get_StatusText(BSTR * pbstrStatus)
{
HRESULT hr = NOERROR;
WCHAR wszStatusText[32];
WCHAR * pwszStatusText = wszStatusText;
BOOL fFreeStatusString = FALSE;
DWORD cb;
BOOL fRetCode;
// Validate parameter
if (IsBadWritePtr(pbstrStatus, sizeof(BSTR)))
return E_INVALIDARG;
// Validate state
// Validate state
if (_eState < CHttpRequest::SENDING)
goto ErrorCannotCallBeforeSend;
else if (_eState < CHttpRequest::RECEIVING)
goto ErrorRequestInProgress;
*pbstrStatus = NULL;
cb = sizeof(wszStatusText) / sizeof(WCHAR);
RetryQuery:
fRetCode = WinHttpQueryHeaders(
_hHTTP,
HTTP_QUERY_STATUS_TEXT,
WINHTTP_HEADER_NAME_BY_INDEX,
pwszStatusText,
&cb,
0);
if (!fRetCode)
{
// Check for ERROR_INSUFFICIENT_BUFFER error
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
// Reallocate the status text buffer
if (fFreeStatusString)
delete [] pwszStatusText;
pwszStatusText = New WCHAR[cb];
if (!pwszStatusText)
goto ErrorOutOfMemory;
fFreeStatusString = TRUE;
goto RetryQuery;
}
else
{
goto ErrorFail;
}
}
// Convert the status text to a BSTR
*pbstrStatus = DL(SysAllocString)(pwszStatusText);
if (!*pbstrStatus)
goto ErrorOutOfMemory;
hr = NOERROR;
Cleanup:
if (fFreeStatusString)
delete [] pwszStatusText;
SetErrorInfo(hr);
return hr;
ErrorOutOfMemory:
hr = E_OUTOFMEMORY;
goto Error;
ErrorCannotCallBeforeSend:
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND);
goto Error;
ErrorRequestInProgress:
hr = E_PENDING;
goto Error;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
goto Cleanup;
Error:
goto Cleanup;
}
/*
* CHttpRequest::get_ResponseBody
*
* Purpose:
* Retrieve the response body as a SAFEARRAY of UI1
*
* Parameters:
* pvarBody OUT Response blob
*
* Errors:
* E_INVALIDARG
* E_UNEXPECTED
* E_PENDING
*/
STDMETHODIMP
CHttpRequest::get_ResponseBody(VARIANT * pvarBody)
{
HRESULT hr = NOERROR;
// Validate parameter
if (IsBadWritePtr(pvarBody, sizeof(VARIANT)))
return E_INVALIDARG;
// Validate state
if (_eState < CHttpRequest::SENDING)
goto ErrorCannotCallBeforeSend;
else if (_eState < CHttpRequest::RESPONSE)
goto ErrorPending;
DL(VariantInit)(pvarBody);
if (_cbResponseBody != 0)
{
HGLOBAL hGlobal;
hr = DL(GetHGlobalFromStream)(_pResponseStream, &hGlobal);
if (FAILED(hr))
goto Error;
const BYTE * pResponseData = (const BYTE *) GlobalLock(hGlobal);
if (!pResponseData)
goto ErrorFail;
hr = CreateVector(pvarBody, pResponseData, _cbResponseBody);
GlobalUnlock(hGlobal);
if (FAILED(hr))
goto Error;
}
else
{
V_VT(pvarBody) = VT_EMPTY;
}
hr = NOERROR;
Cleanup:
SetErrorInfo(hr);
return hr;
ErrorCannotCallBeforeSend:
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND);
goto Error;
ErrorPending:
hr = E_PENDING;
goto Error;
ErrorFail:
hr = HRESULT_FROM_WIN32(::GetLastError());
goto Error;
Error:
if (pvarBody)
DL(VariantClear)(pvarBody);
goto Cleanup;
}
/*
* CHttpRequest::get_ResponseText
*
* Purpose:
* Retrieve the response body as a BSTR
*
* Parameters:
* pbstrBody OUT response as a BSTR
*
* Errors:
* E_INVALIDARG
* E_OUTOFMEMORY
* E_UNEXPECTED
* E_PENDING
*/
STDMETHODIMP
CHttpRequest::get_ResponseText(BSTR * pbstrBody)
{
HRESULT hr;
MIMECSETINFO mimeSetInfo;
IMultiLanguage * pMultiLanguage = NULL;
IMultiLanguage2 * pMultiLanguage2 = NULL;
CHAR szContentType[1024];
DWORD cb;
BSTR bstrCharset = NULL;
HGLOBAL hGlobal = NULL;
char * pResponseData = NULL;
// Validate parameter
if (IsBadWritePtr(pbstrBody, sizeof(BSTR)))
return E_INVALIDARG;
// Validate state
if (_eState < CHttpRequest::SENDING)
goto ErrorCannotCallBeforeSend;
else if (_eState < CHttpRequest::RESPONSE)
goto ErrorPending;
if (!_hHTTP)
{
hr = E_UNEXPECTED;
goto Error;
}
if (_cbResponseBody != 0)
{
hr = DL(GetHGlobalFromStream)(_pResponseStream, &hGlobal);
if (FAILED(hr))
goto Error;
pResponseData = (char *) GlobalLock(hGlobal);
if (!pResponseData)
goto ErrorFail;
}
else
{
*pbstrBody = NULL;
}
// Check if charset is present.
cb = sizeof(szContentType);
if (HttpQueryInfoA(_hHTTP,
WINHTTP_QUERY_CONTENT_TYPE,
NULL,
szContentType,
&cb,
NULL))
{
LPSTR lpszCharset;
LPSTR lpszCharsetEnd;
if ((lpszCharset = StrStrIA(szContentType, "charset=")) != NULL)
{
LPSTR lpszBeginQuote = NULL;
LPSTR lpszEndQuote = NULL;
if ((lpszBeginQuote = StrChrA(lpszCharset, '\"')) != NULL)
{
lpszEndQuote = StrChrA(lpszBeginQuote+1, '\"');
}
if (lpszEndQuote)
{
lpszCharset = lpszBeginQuote + 1;
lpszCharsetEnd = lpszEndQuote;
}
else
{
lpszCharset += sizeof("charset=")-1;
lpszCharsetEnd = StrChrA(lpszCharset, ';');
}
// only **STRLEN** to be passed to AsciiToBSTR
AsciiToBSTR(&bstrCharset, lpszCharset, (int)(lpszCharsetEnd ? (lpszCharsetEnd-lpszCharset) : lstrlen(lpszCharset)));
}
}
if (!bstrCharset)
{
// use ISO-8859-1
mimeSetInfo.uiInternetEncoding = 28591;
mimeSetInfo.uiCodePage = 1252;
// note unitialized wszCharset - not cached, not used.
}
else
{
// obtain codepage corresponding to charset
if (!g_pMimeInfoCache)
{
//create the mimeinfo cache.
DWORD dwStatus = 0;
if (!GlobalDataInitCritSec.Lock())
{
goto ErrorOutOfMemory;
}
if (!g_pMimeInfoCache)
{
g_pMimeInfoCache = new CMimeInfoCache(&dwStatus);
if(!g_pMimeInfoCache
|| dwStatus)
{
if (g_pMimeInfoCache)
delete g_pMimeInfoCache;
g_pMimeInfoCache = NULL;
GlobalDataInitCritSec.Unlock();
goto ErrorOutOfMemory;
}
}
GlobalDataInitCritSec.Unlock();
}
//check the cache for info
if (S_OK != g_pMimeInfoCache->GetCharsetInfo(bstrCharset, &mimeSetInfo))
{
// if info not in cache, get from mlang
hr = DL(CoCreateInstance)(CLSID_CMultiLanguage, NULL, CLSCTX_INPROC_SERVER,
IID_IMultiLanguage, (void**)&pMultiLanguage);
if (FAILED(hr))
{
goto ConvertError;
}
INET_ASSERT (pMultiLanguage);
pMultiLanguage->QueryInterface(IID_IMultiLanguage2, (void **)&pMultiLanguage2);
pMultiLanguage->Release();
if (!pMultiLanguage2)
{
goto ConvertError;
}
if (FAILED((pMultiLanguage2)->GetCharsetInfo(bstrCharset, &mimeSetInfo)))
{
//Check for known-exceptions
if (!StrCmpNIW(bstrCharset, L"ISO8859_1", MAX_MIMECSET_NAME))
{
mimeSetInfo.uiInternetEncoding = 28591;
mimeSetInfo.uiCodePage = 1252;
StrCpyNW(mimeSetInfo.wszCharset, L"ISO8859_1", lstrlenW(L"ISO8859_1")+1);
}
else
{
goto ConvertError;
}
}
// add obtained info to cache.
g_pMimeInfoCache->AddCharsetInfo(&mimeSetInfo);
}
}
// here only if we have mimeSetInfo filled in correctly.
hr = MultiByteToWideCharInternal(pbstrBody, pResponseData, (int)_cbResponseBody, mimeSetInfo.uiInternetEncoding, &pMultiLanguage2);
if (hr != S_OK)
{
MultiByteToWideCharInternal(pbstrBody, pResponseData, (int)_cbResponseBody, mimeSetInfo.uiCodePage, &pMultiLanguage2);
}
Cleanup:
if (hGlobal)
GlobalUnlock(hGlobal);
if (pMultiLanguage2)
{
pMultiLanguage2->Release();
}
SetErrorInfo(hr);
return hr;
ErrorCannotCallBeforeSend:
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND);
goto Error;
ErrorPending:
hr = E_PENDING;
goto Error;
ErrorFail:
hr = HRESULT_FROM_WIN32(::GetLastError());
goto Error;
ErrorOutOfMemory:
hr = E_OUTOFMEMORY;
goto Error;
Error:
goto Cleanup;
ConvertError:
hr = HRESULT_FROM_WIN32(ERROR_NO_UNICODE_TRANSLATION);
goto Cleanup;
}
STDMETHODIMP
CHttpRequest::get_ResponseStream(VARIANT * pvarBody)
{
HRESULT hr = NOERROR;
IStream * pStm = NULL;
// Validate parameter
if (IsBadWritePtr(pvarBody, sizeof(VARIANT)))
return E_INVALIDARG;
// Validate state
if (_eState < CHttpRequest::SENDING)
goto ErrorCannotCallBeforeSend;
else if (_eState < CHttpRequest::RESPONSE)
goto ErrorPending;
DL(VariantInit)(pvarBody);
hr = CreateStreamOnResponse(&pStm);
if (FAILED(hr))
goto Error;
V_VT(pvarBody) = VT_UNKNOWN;
pvarBody->punkVal = pStm;
hr = NOERROR;
Cleanup:
SetErrorInfo(hr);
return hr;
ErrorCannotCallBeforeSend:
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND);
goto Error;
ErrorPending:
hr = E_PENDING;
goto Error;
Error:
if (pvarBody)
DL(VariantClear)(pvarBody);
goto Cleanup;
}
void
CHttpRequest::SetState(State state)
{
if (_fAsync)
{
InterlockedExchange((long *)&_eState, state);
}
else
{
_eState = state;
}
}
/*
* CHttpRequest::CreateStreamOnResponse
*
* Purpose:
* Create a Stream containing the Response data
*
* Parameters:
* ppStm IN/OUT Stream
*
* Errors:
* E_INVALIDARG
* E_OUTOFMEMORY
*/
HRESULT
CHttpRequest::CreateStreamOnResponse(IStream ** ppStm)
{
HRESULT hr = NOERROR;
LARGE_INTEGER liReset = { 0, 0 };
if (!ppStm)
goto ErrorInvalidArg;
*ppStm = NULL;
if (_cbResponseBody)
{
INET_ASSERT(_pResponseStream);
hr = _pResponseStream->Clone(ppStm);
if (FAILED(hr))
goto Error;
}
else
{
//
// No response body, return an empty stream object
//
ULARGE_INTEGER size = { 0, 0 };
hr = DL(CreateStreamOnHGlobal)(NULL, TRUE, ppStm);
if (FAILED(hr))
goto Error;
(*ppStm)->SetSize(size);
}
hr = (*ppStm)->Seek(liReset, STREAM_SEEK_SET, NULL);
if (FAILED(hr))
goto Error;
hr = NOERROR;
Cleanup:
return hr;
ErrorInvalidArg:
hr = E_INVALIDARG;
goto Error;
Error:
if (ppStm)
SafeRelease(*ppStm);
goto Cleanup;
}
STDMETHODIMP
CHttpRequest::get_Option(WinHttpRequestOption Option, VARIANT * Value)
{
HRESULT hr;
if (IsBadWritePtr(Value, sizeof(VARIANT)))
return E_INVALIDARG;
switch (Option)
{
case WinHttpRequestOption_UserAgentString:
{
V_BSTR(Value) = DL(SysAllocString)(GetUserAgentString());
if (V_BSTR(Value) == NULL)
goto ErrorOutOfMemory;
V_VT(Value) = VT_BSTR;
break;
}
case WinHttpRequestOption_URL:
{
WCHAR * pwszUrl = NULL;
DWORD dwBufferSize = 0;
if (_eState < CHttpRequest::OPENED)
goto ErrorCannotCallBeforeOpen;
if (!WinHttpQueryOption(_hHTTP, WINHTTP_OPTION_URL, NULL, &dwBufferSize) &&
(GetLastError() == ERROR_INSUFFICIENT_BUFFER))
{
pwszUrl = New WCHAR[dwBufferSize + 1];
if (!pwszUrl)
goto ErrorOutOfMemory;
if (WinHttpQueryOption(_hHTTP, WINHTTP_OPTION_URL, pwszUrl, &dwBufferSize))
{
V_BSTR(Value) = DL(SysAllocString)(pwszUrl);
V_VT(Value) = VT_BSTR;
hr = NOERROR;
}
else
{
hr = E_FAIL;
}
delete [] pwszUrl;
if (FAILED(hr))
{
goto ErrorFail;
}
else if (V_BSTR(Value) == NULL)
{
goto ErrorOutOfMemory;
}
}
break;
}
case WinHttpRequestOption_URLCodePage:
V_I4(Value) = (long) _dwCodePage;
V_VT(Value) = VT_I4;
break;
case WinHttpRequestOption_EscapePercentInURL:
V_BOOL(Value) = (_dwEscapeFlag & WINHTTP_FLAG_ESCAPE_PERCENT) ? VARIANT_TRUE : VARIANT_FALSE;
V_VT(Value) = VT_BOOL;
break;
case WinHttpRequestOption_EnableCertificateRevocationCheck:
V_BOOL(Value) = _fCheckForRevocation ? VARIANT_TRUE : VARIANT_FALSE;
V_VT(Value) = VT_BOOL;
break;
case WinHttpRequestOption_SslErrorIgnoreFlags:
if (_dwSslIgnoreFlags)
V_I4(Value) = (long) (_dwSslIgnoreFlags & SslErrorFlag_Ignore_All);
else
V_I4(Value) = (long) 0;
V_VT(Value) = VT_I4;
break;
case WinHttpRequestOption_UrlEscapeDisable:
V_BOOL(Value) = (_dwEscapeFlag & WINHTTP_FLAG_ESCAPE_DISABLE) ? VARIANT_TRUE : VARIANT_FALSE;
V_VT(Value) = VT_BOOL;
break;
case WinHttpRequestOption_UrlEscapeDisableQuery:
V_BOOL(Value) = (_dwEscapeFlag & WINHTTP_FLAG_ESCAPE_DISABLE_QUERY) ? VARIANT_TRUE : VARIANT_FALSE;
V_VT(Value) = VT_BOOL;
break;
case WinHttpRequestOption_EnableRedirects:
BOOL bEnableRedirects;
if (_dwRedirectPolicy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER)
{
bEnableRedirects = FALSE;
}
else
{
bEnableRedirects = TRUE; // for this particular query we return TRUE even HTTPS->HTTP is not allowed
// we are consistent with the SetOption where TRUE means "we allow redirs
// except HTTPS->HTTP ones
}
V_BOOL(Value) = bEnableRedirects ? VARIANT_TRUE: VARIANT_FALSE;
V_VT(Value) = VT_BOOL;
break;
case WinHttpRequestOption_EnableHttpsToHttpRedirects:
V_BOOL(Value) = ((_dwRedirectPolicy == WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS) ? VARIANT_TRUE : VARIANT_FALSE);
V_VT(Value) = VT_BOOL;
break;
case WinHttpRequestOption_EnablePassportAuthentication:
V_BOOL(Value) = ((_dwPassportConfig == (WINHTTP_DISABLE_PASSPORT_AUTH | WINHTTP_DISABLE_PASSPORT_KEYRING)) ? VARIANT_FALSE : VARIANT_TRUE);
V_VT(Value) = VT_BOOL;
break;
case WinHttpRequestOption_MaxAutomaticRedirects:
V_I4(Value) = _lMaxAutomaticRedirects;
V_VT(Value) = VT_I4;
break;
case WinHttpRequestOption_MaxResponseHeaderSize:
V_I4(Value) = _lMaxResponseHeaderSize;
V_VT(Value) = VT_I4;
break;
case WinHttpRequestOption_MaxResponseDrainSize:
V_I4(Value) = _lMaxResponseDrainSize;
V_VT(Value) = VT_I4;
break;
case WinHttpRequestOption_EnableTracing:
{
BOOL fEnableTracing;
DWORD dwBufferSize = sizeof(BOOL);
if (!WinHttpQueryOption(NULL,
WINHTTP_OPTION_ENABLETRACING,
(LPVOID)&fEnableTracing,
&dwBufferSize))
goto ErrorFail;
V_BOOL(Value) = fEnableTracing ? VARIANT_TRUE : VARIANT_FALSE;
V_VT(Value) = VT_BOOL;
break;
}
case WinHttpRequestOption_RevertImpersonationOverSsl:
V_BOOL(Value) = _bEnableSslImpersonation ? VARIANT_FALSE : VARIANT_TRUE;
V_VT(Value) = VT_BOOL;
break;
case WinHttpRequestOption_EnableHttp1_1:
V_BOOL(Value) = _bHttp1_1Mode ? VARIANT_TRUE : VARIANT_FALSE;
V_VT(Value) = VT_BOOL;
break;
default:
DL(VariantInit)(Value);
hr = E_INVALIDARG;
goto Error;
}
hr = NOERROR;
Cleanup:
SetErrorInfo(hr);
return hr;
ErrorCannotCallBeforeOpen:
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN);
goto Error;
ErrorOutOfMemory:
hr = E_OUTOFMEMORY;
goto Error;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
goto Error;
Error:
goto Cleanup;
}
STDMETHODIMP
CHttpRequest::put_Option(WinHttpRequestOption Option, VARIANT Value)
{
HRESULT hr;
if (!IsValidVariant(Value))
return E_INVALIDARG;
switch (Option)
{
case WinHttpRequestOption_UserAgentString:
{
BSTR bstrUserAgent;
hr = GetBSTRFromVariant(Value, &bstrUserAgent);
if (FAILED(hr) || !bstrUserAgent)
return E_INVALIDARG;
if (*bstrUserAgent == L'\0')
{
DL(SysFreeString)(bstrUserAgent);
return E_INVALIDARG;
}
if (_hInet)
{
if (!WinHttpSetOption(_hInet, WINHTTP_OPTION_USER_AGENT,
bstrUserAgent,
lstrlenW(bstrUserAgent)))
{
goto ErrorFail;
}
}
if (_hHTTP)
{
if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_USER_AGENT,
bstrUserAgent,
lstrlenW(bstrUserAgent)))
{
goto ErrorFail;
}
}
if (_bstrUserAgent)
DL(SysFreeString)(_bstrUserAgent);
_bstrUserAgent = bstrUserAgent;
break;
}
case WinHttpRequestOption_URL:
// The URL cannot be set using the Option property.
return E_INVALIDARG;
case WinHttpRequestOption_URLCodePage:
{
_dwCodePage = GetDwordFromVariant(Value, CP_UTF8);
if (_hInet)
{
if (!WinHttpSetOption(_hInet, WINHTTP_OPTION_CODEPAGE,
&_dwCodePage,
sizeof(_dwCodePage)))
goto ErrorFail;
}
if (_hConnection)
{
if (!WinHttpSetOption(_hConnection, WINHTTP_OPTION_CODEPAGE,
&_dwCodePage,
sizeof(_dwCodePage)))
goto ErrorFail;
}
break;
}
case WinHttpRequestOption_EscapePercentInURL:
{
BOOL fEscapePercent = GetBoolFromVariant(Value, FALSE);
if (fEscapePercent)
_dwEscapeFlag |= WINHTTP_FLAG_ESCAPE_PERCENT;
else
_dwEscapeFlag &= ~(DWORD)WINHTTP_FLAG_ESCAPE_PERCENT;
break;
}
case WinHttpRequestOption_UrlEscapeDisable:
{
BOOL fEscape = GetBoolFromVariant(Value, FALSE);
if (fEscape)
_dwEscapeFlag |= WINHTTP_FLAG_ESCAPE_DISABLE;
else
_dwEscapeFlag &= ~(DWORD)WINHTTP_FLAG_ESCAPE_DISABLE;
break;
}
case WinHttpRequestOption_UrlEscapeDisableQuery:
{
BOOL fEscape = GetBoolFromVariant(Value, FALSE);
if (fEscape)
_dwEscapeFlag |= WINHTTP_FLAG_ESCAPE_DISABLE_QUERY;
else
_dwEscapeFlag &= ~(DWORD)WINHTTP_FLAG_ESCAPE_DISABLE_QUERY;
break;
}
case WinHttpRequestOption_EnableCertificateRevocationCheck:
{
_fCheckForRevocation = GetBoolFromVariant(Value, TRUE);
if (_hHTTP && _fCheckForRevocation)
{
DWORD dwOptions = WINHTTP_ENABLE_SSL_REVOCATION;
WinHttpSetOption(_hHTTP,
WINHTTP_OPTION_ENABLE_FEATURE,
(LPVOID)&dwOptions,
sizeof(dwOptions));
}
break;
}
case WinHttpRequestOption_SslErrorIgnoreFlags:
{
DWORD dwSslIgnoreFlags = GetDwordFromVariant(Value, _dwSslIgnoreFlags);
if (dwSslIgnoreFlags & ~SECURITY_INTERNET_MASK)
{
return E_INVALIDARG;
}
dwSslIgnoreFlags &= SslErrorFlag_Ignore_All;
if (_hHTTP)
{
// Set the SSL ignore flags through an undocumented front door
if (!WinHttpSetOption(_hHTTP,
WINHTTP_OPTION_SECURITY_FLAGS,
(LPVOID)&dwSslIgnoreFlags,
sizeof(dwSslIgnoreFlags)))
goto ErrorFail;
}
_dwSslIgnoreFlags = dwSslIgnoreFlags;
break;
}
case WinHttpRequestOption_SelectCertificate:
{
BSTR bstrCertSelection;
hr = GetBSTRFromVariant(Value, &bstrCertSelection);
if (FAILED(hr))
{
hr = E_INVALIDARG;
goto Error;
}
hr = SetClientCertificate(bstrCertSelection);
DL(SysFreeString)(bstrCertSelection);
if (FAILED(hr))
goto Error;
break;
}
case WinHttpRequestOption_EnableRedirects:
{
BOOL fEnableRedirects = GetBoolFromVariant(Value, TRUE);
DWORD dwRedirectPolicy =
fEnableRedirects ? WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP : WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
if ((dwRedirectPolicy == WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP)
&& (_dwRedirectPolicy == WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS))
{
// "always" -> "disalow" transition no-op
// this means the app enabled HTTPS->HTTP before this call, and attempt to enable redir
// should not move us away from the always state
break;
}
if (_hInet)
{
if (!WinHttpSetOption(_hInet,
WINHTTP_OPTION_REDIRECT_POLICY,
(LPVOID)&dwRedirectPolicy,
sizeof(DWORD)))
goto ErrorFail;
}
if (_hHTTP)
{
if (!WinHttpSetOption(_hHTTP,
WINHTTP_OPTION_REDIRECT_POLICY,
(LPVOID)&dwRedirectPolicy,
sizeof(DWORD)))
goto ErrorFail;
}
_dwRedirectPolicy = dwRedirectPolicy;
break;
}
case WinHttpRequestOption_EnableHttpsToHttpRedirects:
{
BOOL fEnableHttpsToHttpRedirects = GetBoolFromVariant(Value, FALSE);
DWORD dwRedirectPolicy = (fEnableHttpsToHttpRedirects
? WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS
: WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP);
if (_dwRedirectPolicy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER)
{
// "never" -> "always" or "never" -> "disalow" transition not allowed
// this means the app disabled redirect before this call, it will have to re-enable redirect
// before it can enable or disable HTTPS->HTTP
break;
}
if (_hInet)
{
if (!WinHttpSetOption(_hInet,
WINHTTP_OPTION_REDIRECT_POLICY,
(LPVOID)&dwRedirectPolicy,
sizeof(DWORD)))
goto ErrorFail;
}
if (_hHTTP)
{
if (!WinHttpSetOption(_hHTTP,
WINHTTP_OPTION_REDIRECT_POLICY,
(LPVOID)&dwRedirectPolicy,
sizeof(DWORD)))
goto ErrorFail;
}
_dwRedirectPolicy = dwRedirectPolicy;
break;
}
case WinHttpRequestOption_SecureProtocols:
{
DWORD dwSecureProtocols = GetDwordFromVariant(Value, _dwSecureProtocols);
if (dwSecureProtocols & ~WINHTTP_FLAG_SECURE_PROTOCOL_ALL)
{
return E_INVALIDARG;
}
_dwSecureProtocols = dwSecureProtocols;
if (_hInet)
{
// Set the per session SSL protocols.
// This can be done at any time, so there's no need to
// keep track of this here.
if (!WinHttpSetOption(_hInet,
WINHTTP_OPTION_SECURE_PROTOCOLS,
(LPVOID)&dwSecureProtocols,
sizeof(dwSecureProtocols)))
goto ErrorFail;
}
break;
}
case WinHttpRequestOption_EnablePassportAuthentication:
{
BOOL fEnablePassportAuth = GetBoolFromVariant(Value, FALSE);
DWORD dwPassportConfig = (fEnablePassportAuth
? (WINHTTP_ENABLE_PASSPORT_AUTH | WINHTTP_ENABLE_PASSPORT_KEYRING)
: (WINHTTP_DISABLE_PASSPORT_AUTH | WINHTTP_DISABLE_PASSPORT_KEYRING));
if (_hInet)
{
if (!WinHttpSetOption(_hInet,
WINHTTP_OPTION_CONFIGURE_PASSPORT_AUTH,
(LPVOID)&dwPassportConfig,
sizeof(DWORD)))
goto ErrorFail;
}
_dwPassportConfig = dwPassportConfig;
break;
}
case WinHttpRequestOption_EnableTracing:
{
BOOL fEnableTracing = GetBoolFromVariant(Value, TRUE);
if (!WinHttpSetOption(NULL,
WINHTTP_OPTION_ENABLETRACING,
(LPVOID)&fEnableTracing,
sizeof(BOOL)))
goto ErrorFail;
break;
}
case WinHttpRequestOption_RevertImpersonationOverSsl:
{
if (_hInet)
{
// Must be called before the Open method because
// the open method also creates a request handle.
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_AFTER_OPEN);
goto Error;
}
else
{
_bEnableSslImpersonation = (GetBoolFromVariant(Value, TRUE) ? FALSE : TRUE);
}
break;
}
case WinHttpRequestOption_MaxAutomaticRedirects:
case WinHttpRequestOption_MaxResponseHeaderSize:
case WinHttpRequestOption_MaxResponseDrainSize:
{
DWORD dwSetting = (DWORD)-1;
LONG* plResultTarget = NULL;
switch(Option)
{
case WinHttpRequestOption_MaxAutomaticRedirects:
dwSetting = WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS;
plResultTarget = &_lMaxAutomaticRedirects;
break;
case WinHttpRequestOption_MaxResponseHeaderSize:
dwSetting = WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE;
plResultTarget = &_lMaxResponseHeaderSize;
break;
case WinHttpRequestOption_MaxResponseDrainSize:
dwSetting = WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE;
plResultTarget = &_lMaxResponseDrainSize;
break;
default:
INET_ASSERT(0); // shouldn't be possible
goto ErrorFail;
}
LONG lInput = GetLongFromVariant(Value, -1);
DWORD dwInput = (DWORD)lInput;
DWORD dwInputSize = sizeof(dwInput);
if (lInput < 0 || lInput != (LONG)dwInput)
{
hr = HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER);
goto Error;
}
if (_hHTTP != NULL
&& TRUE != WinHttpSetOption( _hHTTP, dwSetting, &dwInput, dwInputSize))
{
goto ErrorFail;
}
*plResultTarget = lInput;
break;
}
case WinHttpRequestOption_EnableHttp1_1:
if (_hHTTP != NULL)
{
hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_AFTER_OPEN);
goto Error;
}
_bHttp1_1Mode = GetBoolFromVariant(Value, TRUE);
break;
default:
return E_INVALIDARG;
}
hr = NOERROR;
Cleanup:
SetErrorInfo(hr);
return hr;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
goto Error;
Error:
goto Cleanup;
}
IErrorInfo *
CHttpRequest::CreateErrorObject(HRESULT hr)
{
INET_ASSERT(FAILED(hr));
ICreateErrorInfo * pCErrInfo = NULL;
IErrorInfo * pErrInfo = NULL;
DWORD error = hr;
DWORD dwFmtMsgFlag = FORMAT_MESSAGE_FROM_SYSTEM;
HMODULE hModule = NULL;
DWORD rc;
LPWSTR pwszMessage = NULL;
const DWORD dwSize = 512;
pwszMessage = New WCHAR[dwSize];
if (pwszMessage == NULL)
return NULL;
if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
{
DWORD errcode = HRESULT_CODE(hr);
if ((errcode > WINHTTP_ERROR_BASE) && (errcode <= WINHTTP_ERROR_LAST))
{
dwFmtMsgFlag = FORMAT_MESSAGE_FROM_HMODULE;
hModule = GetModuleHandle("winhttp.dll");
error = errcode;
}
}
rc = ::FormatMessageW(dwFmtMsgFlag, hModule,
error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
pwszMessage,
dwSize,
NULL);
if (rc != 0)
{
if (SUCCEEDED(DL(CreateErrorInfo)(&pCErrInfo)))
{
if (SUCCEEDED(pCErrInfo->QueryInterface(IID_IErrorInfo, (void **) &pErrInfo)))
{
pCErrInfo->SetSource(L"WinHttp.WinHttpRequest");
pCErrInfo->SetGUID(IID_IWinHttpRequest);
pCErrInfo->SetDescription(pwszMessage);
}
pCErrInfo->Release();
}
}
delete [] pwszMessage;
return pErrInfo;
}
void
CHttpRequest::SetErrorInfo(HRESULT hr)
{
if (FAILED(hr))
{
IErrorInfo * pErrInfo = CreateErrorObject(hr);
if (pErrInfo)
{
DL(SetErrorInfo)(0, pErrInfo);
pErrInfo->Release();
}
}
}
BOOL
CHttpRequest::SelectCertificate()
{
HCERTSTORE hCertStore = NULL;
BOOL fRet = FALSE;
HANDLE hThreadToken = NULL;
PCCERT_CONTEXT pCertContext = NULL;
// Make sure security DLLs are loaded
if (LoadSecurity() != ERROR_SUCCESS)
return FALSE;
// If impersonating, revert while trying to obtain the cert
if (!_bEnableSslImpersonation && OpenThreadToken(GetCurrentThread(), (TOKEN_IMPERSONATE | TOKEN_READ),
FALSE,
&hThreadToken))
{
INET_ASSERT(hThreadToken != 0);
RevertToSelf();
}
hCertStore = (*g_pfnCertOpenStore)(CERT_STORE_PROV_SYSTEM,
0,
0,
CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG |
(_fCertLocalMachine ? CERT_SYSTEM_STORE_LOCAL_MACHINE:
CERT_SYSTEM_STORE_CURRENT_USER),
_bstrCertStore ? _bstrCertStore : L"MY");
if (!hCertStore)
{
TRACE_PRINT_API(THRDINFO,
INFO,
("Unable to open certificate store %s\\%Q; GetLastError() = %s [%d]\n",
_fCertLocalMachine? "Local Machine": "Current User",
_bstrCertStore ? _bstrCertStore : L"MY",
InternetMapError(::GetLastError()),
::GetLastError()
));
goto Cleanup;
}
if (_bstrCertSubject && _bstrCertSubject[0])
{
CERT_RDN SubjectRDN;
CERT_RDN_ATTR rdnAttr;
rdnAttr.pszObjId = szOID_COMMON_NAME;
rdnAttr.dwValueType = CERT_RDN_ANY_TYPE;
rdnAttr.Value.cbData = lstrlenW(_bstrCertSubject) * sizeof(WCHAR);
rdnAttr.Value.pbData = (BYTE *) _bstrCertSubject;
SubjectRDN.cRDNAttr = 1;
SubjectRDN.rgRDNAttr = &rdnAttr;
//
// First try an exact match for the certificate lookup.
// If that fails, then try a prefix match.
//
pCertContext = (*g_pfnCertFindCertificateInStore)(hCertStore,
X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
CERT_CASE_INSENSITIVE_IS_RDN_ATTRS_FLAG |
CERT_UNICODE_IS_RDN_ATTRS_FLAG,
CERT_FIND_SUBJECT_ATTR,
&SubjectRDN,
NULL);
if (! pCertContext)
{
pCertContext = (*g_pfnCertFindCertificateInStore)(hCertStore,
X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
0,
CERT_FIND_SUBJECT_STR,
(LPVOID) _bstrCertSubject,
NULL);
}
}
else
{
pCertContext = (*g_pfnCertFindCertificateInStore)(hCertStore,
X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
0,
CERT_FIND_ANY,
NULL,
NULL);
}
if (pCertContext)
{
fRet = WinHttpSetOption(_hHTTP,
WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
(LPVOID) pCertContext,
sizeof(CERT_CONTEXT));
}
else
{
TRACE_PRINT_API(THRDINFO,
INFO,
("Unable to find certificate %Q in store %s\\%Q; GetLastError() = %s [%d]\n",
_bstrCertSubject,
_fCertLocalMachine? "Local Machine": "Current User",
_bstrCertStore ? _bstrCertStore : L"MY",
InternetMapError(::GetLastError()),
::GetLastError()
));
}
Cleanup:
if (pCertContext)
(*g_pfnCertFreeCertificateContext)(pCertContext);
if (hCertStore)
(*g_pfnCertCloseStore)(hCertStore, 0);
// Restore the impersonating state for the current thread.
if (hThreadToken)
{
(void)SetThreadToken(NULL, hThreadToken);
CloseHandle(hThreadToken);
}
return fRet;
}
/*
* ParseSelectedCert
*
* Purpose:
* Given a certificate, breakdown the location
* (local machine vs. current user), store (MY, CA, etc.), and
* subject name of the form:
* "[CURRENT_USER | LOCAL_MACHINE [\store]\]cert_subject_name"
*
* The backslash character is the delimiter, and the CURRENT_USER vs.
* LOCAL_MACHINE choice can optionally include a store (any store
* can be chosen). If there are more than two backslash characters
* present in the string, this function assumes everything after the
* second backslash is the cert subject name fragment to use for finding
* a match.
*
* If the optional pieces are not specified "CURRENT_USER\MY" are
* the defaults chosen.
*
* The pbstrLocation, pbstrStore, and pbstrSubject parameters
* are allocated and filled in with the default or parsed strings, or set
* to NULL if a failure occurs (e.g. out of memory or invalid param).
* The caller should free all params on success via DL(SysFreeString).
*/
HRESULT ParseSelectedCert(BSTR bstrSelection,
LPBOOL pfLocalMachine,
BSTR *pbstrStore,
BSTR *pbstrSubject
)
{
HRESULT hr = S_OK;
LPWSTR lpwszSelection = bstrSelection;
LPWSTR lpwszStart = lpwszSelection;
*pfLocalMachine = FALSE;
*pbstrStore = NULL;
*pbstrSubject = NULL;
if (!bstrSelection)
{
// When NULL, fill in an empty string to simulate first enum
*pbstrSubject = DL(SysAllocString)(L"");
if (!*pbstrSubject)
{
hr = E_OUTOFMEMORY;
goto quit;
}
// Need to also fill in the default "MY" store.
goto DefaultStore;
}
while (*lpwszSelection && *lpwszSelection != L'\\')
lpwszSelection++;
if (*lpwszSelection == L'\\')
{
// LOCAL_MACHINE vs. CURRENT_USER was selected.
// Check for invalid arg since it must match either.
if (!wcsncmp(lpwszStart, L"LOCAL_MACHINE", lpwszSelection-lpwszStart))
{
*pfLocalMachine = TRUE;
}
else if (wcsncmp(lpwszStart, L"CURRENT_USER", lpwszSelection-lpwszStart))
{
hr = E_INVALIDARG;
goto quit;
}
// else already defaults to having *pfLocalMachine initialized to FALSE
lpwszStart = ++lpwszSelection;
// Now look for the optional choice on the store
while (*lpwszSelection && *lpwszSelection != L'\\')
lpwszSelection++;
if (*lpwszSelection == L'\\')
{
// Accept any store name.
// When opening the store, it will fail if the selected
// store does not exist.
*pbstrStore = DL(SysAllocStringLen)(lpwszStart, (UINT) (lpwszSelection-lpwszStart));
if (!*pbstrStore)
{
hr = E_OUTOFMEMORY;
goto Cleanup;
}
lpwszStart = ++lpwszSelection;
}
}
// lpwszStart points to the portion designating the subject string
// which could be part or all of pbstrSelection.
//
// If the string is empty, then fill in an empty string, which
// will mean to use the first enumerated cert.
*pbstrSubject = DL(SysAllocString)(lpwszStart);
if (!*pbstrSubject)
{
hr = E_OUTOFMEMORY;
goto Cleanup;
}
DefaultStore:
// Fill in MY store default if the store name wasn't specified.
if (!*pbstrStore)
{
// Default to MY store
*pbstrStore = DL(SysAllocString)(L"MY");
if (!*pbstrStore)
{
hr = E_OUTOFMEMORY;
goto Cleanup;
}
}
quit:
return hr;
Cleanup:
if (*pbstrStore)
{
DL(SysFreeString)(*pbstrStore);
*pbstrStore = NULL;
}
if (*pbstrSubject)
{
DL(SysFreeString)(*pbstrSubject);
*pbstrSubject = NULL;
}
goto quit;
}
#ifdef TRUE_ASYNC
HRESULT
CHttpRequest::PrepareToReadData(HINTERNET hInternet)
{
HRESULT hr = NOERROR;
BSTR bstrContentType = NULL;
DWORD dwStatus = 0;
BOOL fRetCode;
DWORD cb;
// Get the content length
_dwContentLength = 0;
fRetCode = GetContentLengthIfResponseNotChunked(hInternet, &_dwContentLength);
INET_ASSERT((_pResponseStream == NULL) && (_cbResponseBody == 0));
hr = DL(CreateStreamOnHGlobal)(NULL, TRUE, &_pResponseStream);
if (FAILED(hr))
goto ErrorFail;
// pre-set response stream size if we have a Content-Length
if (fRetCode)
{
ULARGE_INTEGER size;
size.LowPart = _dwContentLength;
size.HighPart = 0;
_pResponseStream->SetSize(size);
}
else
{
// Content-Length was not specified in the response, but this
// does not mean Content-Length==0. We will keep reading until
// either no more data is available. Set dwContentLength to 4GB
// to trick our read loop into reading until QDA reports EOF
_dwContentLength = (DWORD)(-1L);
ULARGE_INTEGER size;
size.LowPart = SIZEOF_BUFFER;
size.HighPart = 0;
_pResponseStream->SetSize(size);
}
if ((_dwContentLength > 0) && (_Buffer == NULL))
{
_Buffer = New BYTE[SIZEOF_BUFFER];
if (!_Buffer)
{
goto ErrorOutOfMemory;
}
}
//get status
cb = sizeof(dwStatus);
if (!HttpQueryInfoA(
hInternet,
HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX,
&dwStatus,
&cb,
0))
goto ErrorFail;
//get content type
hr = _GetResponseHeader2(L"Content-Type", &bstrContentType, hInternet);
if (FAILED(hr))
{
bstrContentType = DL(SysAllocString)(L"");
if (bstrContentType == NULL)
goto ErrorOutOfMemory;
hr = NOERROR;
}
_CP.FireOnResponseStart((long)dwStatus, bstrContentType);
hr = NOERROR;
Cleanup:
if (bstrContentType)
DL(SysFreeString)(bstrContentType);
return hr;
ErrorOutOfMemory:
hr = E_OUTOFMEMORY;
goto Error;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
goto Error;
Error:
SafeRelease(_pResponseStream);
_cbResponseBody = NULL;
goto Cleanup;
}
#define ASYNC_SEND_CALLBACK_NOTIFICATIONS \
WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE |\
WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE |\
WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE |\
WINHTTP_CALLBACK_STATUS_READ_COMPLETE |\
WINHTTP_CALLBACK_STATUS_REQUEST_ERROR |\
WINHTTP_CALLBACK_STATUS_SECURE_FAILURE
HRESULT CHttpRequest::StartAsyncSend()
{
DEBUG_ENTER((DBG_HTTP,
Dword,
"IWinHttpRequest::StartAsyncSend",
NULL
));
HRESULT hr;
hr = _CP.CreateEventSinksMarshaller();
if (FAILED(hr))
goto Error;
hr = NOERROR;
//init vars
_hrAsyncResult = NOERROR;
_dwNumberOfBytesAvailable = 0;
_cbNumberOfBytesRead = 0;
if (!_hCompleteEvent)
{
_hCompleteEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (_hCompleteEvent == NULL)
goto ErrorFail;
}
else
{
if (!ResetEvent(_hCompleteEvent))
goto ErrorFail;
}
//register callback
if (WINHTTP_INVALID_STATUS_CALLBACK ==
WinHttpSetStatusCallback(_hHTTP,
AsyncCallback,
ASYNC_SEND_CALLBACK_NOTIFICATIONS,
NULL))
goto ErrorFail;
// Initiate async HTTP request
SetState(SENDING);
if (!WinHttpSendRequest(
_hHTTP,
NULL, 0, // No header info here
_szRequestBuffer,
_cbRequestBody,
_cbRequestBody,
reinterpret_cast<DWORD_PTR>(this)))
goto ErrorFailWinHttpAPI;
Cleanup:
DEBUG_LEAVE(hr);
return hr;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
Error:
if (_hCompleteEvent)
{
CloseHandle(_hCompleteEvent);
_hCompleteEvent = NULL;
}
goto Cleanup;
ErrorFailWinHttpAPI:
hr = HRESULT_FROM_WIN32(GetLastError());
_CP.FireOnError(hr);
goto Error;
}
void CHttpRequest::CompleteDataRead(bool bNotAborted, HINTERNET hInternet)
{
DEBUG_ENTER((DBG_HTTP,
None,
"IWinHttpRequest::CompleteDataRead",
"bNotAborted: %s",
bNotAborted ? "true" : "false"
));
//unregister callback
WinHttpSetStatusCallback(hInternet,
NULL,
ASYNC_SEND_CALLBACK_NOTIFICATIONS,
NULL);
if (_pResponseStream)
{
ULARGE_INTEGER size;
// set final size on stream
size.LowPart = _cbResponseBody;
size.HighPart = 0;
_pResponseStream->SetSize(size);
}
if (bNotAborted)
_CP.FireOnResponseFinished();
SetEvent(_hCompleteEvent);
DEBUG_LEAVE(0);
}
void CALLBACK CHttpRequest::SyncCallback(
HINTERNET hInternet,
DWORD_PTR dwContext,
DWORD dwInternetStatus,
LPVOID lpvStatusInformation,
DWORD dwStatusInformationLength)
{
UNREFERENCED_PARAMETER(hInternet);
UNREFERENCED_PARAMETER(dwStatusInformationLength);
DEBUG_ENTER((DBG_HTTP,
None,
"CHttpRequest::SyncCallback",
"hInternet: %#x, dwContext: %#x, dwInternetStatus:%#x, %#x, %#d",
hInternet,
dwContext,
dwInternetStatus,
lpvStatusInformation,
dwStatusInformationLength
));
if (dwContext == NULL)
{
return;
}
CHttpRequest * pRequest = reinterpret_cast<CHttpRequest*>(dwContext);
// unexpected notification?
INET_ASSERT(dwInternetStatus == WINHTTP_CALLBACK_STATUS_SECURE_FAILURE);
if (!pRequest->_bAborted)
{
switch (dwInternetStatus)
{
case WINHTTP_CALLBACK_STATUS_SECURE_FAILURE:
pRequest->_hrSecureFailure = SecureFailureFromStatus(*((DWORD *)lpvStatusInformation));
break;
}
}
DEBUG_LEAVE(0);
}
void CALLBACK CHttpRequest::AsyncCallback(HINTERNET hInternet,
DWORD_PTR dwContext,
DWORD dwInternetStatus,
LPVOID lpvStatusInformation,
DWORD dwStatusInformationLength)
{
DEBUG_ENTER((DBG_HTTP,
None,
"IWinHttpRequest::AsyncCallback",
"hInternet: %#x, dwContext: %#x, dwInternetStatus:%#x, %#x, %#d",
hInternet,
dwContext,
dwInternetStatus,
lpvStatusInformation,
dwStatusInformationLength
));
if (dwContext == NULL)
{
DEBUG_PRINT_API(ASYNC, FATAL, ("Unexpected: dwContext parameter is zero!\n"))
DEBUG_LEAVE(0);
return;
}
CHttpRequest* pRequest = reinterpret_cast<CHttpRequest*>(dwContext);
if ((dwInternetStatus & ASYNC_SEND_CALLBACK_NOTIFICATIONS) == 0)
{
//unexpected notification
DEBUG_PRINT_API(ASYNC, FATAL, ("Unexpected dwInternetStatus value!\n"))
pRequest->_hrAsyncResult = HRESULT_FROM_WIN32(ERROR_WINHTTP_INTERNAL_ERROR);
goto Error;
}
if (pRequest->_bAborted)
goto Aborted;
DWORD dwBytesToRead = 0;
switch (dwInternetStatus)
{
case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE :
//SR completed
pRequest->SetState(SENT);
if (!::WinHttpReceiveResponse(hInternet, NULL))
goto ErrorFail;
break;
case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE :
//RR completed, read data
pRequest->SetState(RECEIVING);
pRequest->_hrAsyncResult = pRequest->PrepareToReadData(hInternet);
if (FAILED(pRequest->_hrAsyncResult))
goto Error;
if (pRequest->_dwContentLength == 0)
{
goto RequestComplete;
}
//start reading data
dwBytesToRead = min(pRequest->_dwContentLength, SIZEOF_BUFFER);
break;
case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE :
//QDA completed
INET_ASSERT(dwStatusInformationLength == sizeof(DWORD));
pRequest->_dwNumberOfBytesAvailable = *(LPDWORD)lpvStatusInformation;
if (pRequest->_dwNumberOfBytesAvailable)
dwBytesToRead = min(pRequest->_dwNumberOfBytesAvailable, SIZEOF_BUFFER); //continue read
else
goto RequestComplete; //no more data to read
break;
case WINHTTP_CALLBACK_STATUS_READ_COMPLETE :
//RD completed
pRequest->_cbNumberOfBytesRead = dwStatusInformationLength;
if (pRequest->_cbNumberOfBytesRead)
{
HRESULT hr = pRequest->_pResponseStream->Write(pRequest->_Buffer,
pRequest->_cbNumberOfBytesRead,
NULL);
if (FAILED(hr))
{
pRequest->_hrAsyncResult = E_OUTOFMEMORY;
goto Error;
}
pRequest->_CP.FireOnResponseDataAvailable((const BYTE *)pRequest->_Buffer, pRequest->_cbNumberOfBytesRead);
pRequest->_cbResponseBody += pRequest->_cbNumberOfBytesRead;
if (pRequest->_cbResponseBody >= pRequest->_dwContentLength)
{
goto RequestComplete;
}
else
{
//perform QDA to make sure there is no more data to read
if (pRequest->_bAborted)
goto Aborted;
if (!WinHttpQueryDataAvailable(hInternet, NULL))
goto ErrorFail;
}
}
else
goto RequestComplete; //no more data to read
break;
case WINHTTP_CALLBACK_STATUS_SECURE_FAILURE:
pRequest->_hrSecureFailure = SecureFailureFromStatus(*((DWORD *)lpvStatusInformation));
goto Cleanup;
case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR :
{
DWORD dwError = ((LPWINHTTP_ASYNC_RESULT)lpvStatusInformation)->dwError;
if (dwError == ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED)
{
if (!pRequest->_bRetriedWithCert)
{
pRequest->_bRetriedWithCert = TRUE;
if (pRequest->SelectCertificate())
{
// Initiate async HTTP request
pRequest->SetState(SENDING);
if (!WinHttpSendRequest(
hInternet,
NULL, 0, // No header info here
pRequest->_szRequestBuffer,
pRequest->_cbRequestBody,
pRequest->_cbRequestBody,
reinterpret_cast<DWORD_PTR>(pRequest)))
goto ErrorFail;
break;
}
}
}
goto ErrorFail;
}
}
if (dwBytesToRead)
{
if (pRequest->_bAborted)
goto Aborted;
if (!WinHttpReadData(hInternet,
pRequest->_Buffer,
dwBytesToRead,
NULL))
goto ErrorFail;
}
Cleanup:
DEBUG_LEAVE(0);
return;
Aborted:
pRequest->CompleteDataRead(false, hInternet);
goto Cleanup;
ErrorFail:
pRequest->_hrAsyncResult = HRESULT_FROM_WIN32(GetLastError());
if (pRequest->_hrAsyncResult == HRESULT_FROM_WIN32(ERROR_WINHTTP_SECURE_FAILURE))
{
INET_ASSERT(FAILED(pRequest->_hrSecureFailure));
pRequest->_hrAsyncResult = pRequest->_hrSecureFailure;
}
pRequest->_CP.FireOnError(pRequest->_hrAsyncResult);
Error:
DEBUG_PRINT_API(ASYNC, ERROR, ("Error set: %#x\n", pRequest->_hrAsyncResult))
pRequest->CompleteDataRead(false, hInternet);
goto Cleanup;
RequestComplete:
pRequest->SetState(RESPONSE);
pRequest->CompleteDataRead(true, hInternet);
goto Cleanup;
}
#endif//TRUE_ASYNC
/*
* BSTRToUTF8
*
* Purpose:
* Convert a BSTR to UTF-8
*
*/
static
HRESULT
BSTRToUTF8(char ** psz, DWORD * pcbUTF8, BSTR bstr, bool * pbSetUtf8Charset)
{
UINT cch = lstrlenW(bstr);
bool bSimpleConversion = false;
*pcbUTF8 = 0;
*psz = NULL;
if (cch == 0)
return NOERROR;
PreWideCharToUtf8(bstr, cch, (UINT *)pcbUTF8, &bSimpleConversion);
*psz = New char [*pcbUTF8 + 1];
if (!*psz)
return E_OUTOFMEMORY;
WideCharToUtf8(bstr, cch, (BYTE *)*psz, bSimpleConversion);
(*psz)[*pcbUTF8] = 0;
if (pbSetUtf8Charset)
{
*pbSetUtf8Charset = !bSimpleConversion;
}
return NOERROR;
}
/**
* Scans buffer and translates Unicode characters into UTF8 characters
*/
static
void
PreWideCharToUtf8(
WCHAR * buffer,
UINT cch,
UINT * cb,
bool * bSimpleConversion)
{
UINT count = 0;
DWORD dw1;
bool surrogate = false;
for (UINT i = cch; i > 0; i--)
{
DWORD dw = *buffer;
if (surrogate) // is it the second char of a surrogate pair?
{
if (dw >= 0xdc00 && dw <= 0xdfff)
{
// four bytes 0x11110xxx 0x10xxxxxx 0x10xxxxxx 0x10xxxxxx
count += 4;
surrogate = false;
buffer++;
continue;
}
else // Then dw1 must be a three byte character
{
count += 3;
}
surrogate = false;
}
if (dw < 0x80) // one byte, 0xxxxxxx
{
count++;
}
else if (dw < 0x800) // two WORDS, 110xxxxx 10xxxxxx
{
count += 2;
}
else if (dw >= 0xd800 && dw <= 0xdbff) // Assume that it is the first char of surrogate pair
{
if (i == 1) // last wchar in buffer
break;
dw1 = dw;
surrogate = true;
}
else // three bytes, 1110xxxx 10xxxxxx 10xxxxxx
{
count += 3;
}
buffer++;
}
*cb = count;
*bSimpleConversion = (cch == count);
}
/**
* Scans buffer and translates Unicode characters into UTF8 characters
*/
static
void
WideCharToUtf8(
WCHAR * buffer,
UINT cch,
BYTE * bytebuffer,
bool bSimpleConversion)
{
DWORD dw1 = 0;
bool surrogate = false;
INET_ASSERT(bytebuffer != NULL);
if (bSimpleConversion)
{
for (UINT i = cch; i > 0; i--)
{
DWORD dw = *buffer;
*bytebuffer++ = (byte)dw;
buffer++;
}
}
else
{
for (UINT i = cch; i > 0; i--)
{
DWORD dw = *buffer;
if (surrogate) // is it the second char of a surrogate pair?
{
if (dw >= 0xdc00 && dw <= 0xdfff)
{
// four bytes 0x11110xxx 0x10xxxxxx 0x10xxxxxx 0x10xxxxxx
ULONG ucs4 = (dw1 - 0xd800) * 0x400 + (dw - 0xdc00) + 0x10000;
*bytebuffer++ = (byte)(( ucs4 >> 18) | 0xF0);
*bytebuffer++ = (byte)((( ucs4 >> 12) & 0x3F) | 0x80);
*bytebuffer++ = (byte)((( ucs4 >> 6) & 0x3F) | 0x80);
*bytebuffer++ = (byte)(( ucs4 & 0x3F) | 0x80);
surrogate = false;
buffer++;
continue;
}
else // Then dw1 must be a three byte character
{
*bytebuffer++ = (byte)(( dw1 >> 12) | 0xE0);
*bytebuffer++ = (byte)((( dw1 >> 6) & 0x3F) | 0x80);
*bytebuffer++ = (byte)(( dw1 & 0x3F) | 0x80);
}
surrogate = false;
}
if (dw < 0x80) // one byte, 0xxxxxxx
{
*bytebuffer++ = (byte)dw;
}
else if ( dw < 0x800) // two WORDS, 110xxxxx 10xxxxxx
{
*bytebuffer++ = (byte)((dw >> 6) | 0xC0);
*bytebuffer++ = (byte)((dw & 0x3F) | 0x80);
}
else if (dw >= 0xd800 && dw <= 0xdbff) // Assume that it is the first char of surrogate pair
{
if (i == 1) // last wchar in buffer
break;
dw1 = dw;
surrogate = true;
}
else // three bytes, 1110xxxx 10xxxxxx 10xxxxxx
{
*bytebuffer++ = (byte)(( dw >> 12) | 0xE0);
*bytebuffer++ = (byte)((( dw >> 6) & 0x3F) | 0x80);
*bytebuffer++ = (byte)(( dw & 0x3F) | 0x80);
}
buffer++;
}
}
}
/*
* AsciiToBSTR
*
* Purpose:
* Convert an ascii string to a BSTR
*
* only **STRLEN** to be passed to AsciiToBSTR (not including terminating NULL, if any)
*
*/
static
HRESULT
AsciiToBSTR(BSTR * pbstr, char * sz, int cch)
{
int cwch;
INET_ASSERT (cch != -1);
// Determine how big the ascii string will be
cwch = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, sz, cch,
NULL, 0);
*pbstr = DL(SysAllocStringLen)(NULL, cwch);
if (!*pbstr)
return E_OUTOFMEMORY;
cch = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, sz, cch,
*pbstr, cwch);
return NOERROR;
}
/*
* GetBSTRFromVariant
*
* Purpose:
* Convert a VARIANT to a BSTR
*
* If VariantChangeType raises an exception, then an E_INVALIDARG
* error is returned.
*/
static HRESULT GetBSTRFromVariant(VARIANT varVariant, BSTR * pBstr)
{
VARIANT varTemp;
HRESULT hr = NOERROR;
*pBstr = NULL;
if (V_VT(&varVariant) != VT_EMPTY && V_VT(&varVariant) != VT_NULL &&
V_VT(&varVariant) != VT_ERROR)
{
DL(VariantInit)(&varTemp);
__try
{
hr = DL(VariantChangeType)(
&varTemp,
&varVariant,
0,
VT_BSTR);
if (SUCCEEDED(hr))
{
*pBstr = V_BSTR(&varTemp); // take over ownership of BSTR
}
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
hr = E_INVALIDARG;
}
}
// DON'T clear the variant because we stole the BSTR
//DL(VariantClear)(&varTemp);
return hr;
}
/*
* GetBoolFromVariant
*
* Purpose:
* Convert a VARIANT to a Boolean
*
*/
static BOOL GetBoolFromVariant(VARIANT varVariant, BOOL fDefault)
{
HRESULT hr;
BOOL fResult = fDefault;
if (V_VT(&varVariant) != VT_EMPTY && V_VT(&varVariant) != VT_NULL &&
V_VT(&varVariant) != VT_ERROR)
{
VARIANT varTemp;
DL(VariantInit)(&varTemp);
hr = DL(VariantChangeType)(
&varTemp,
&varVariant,
0,
VT_BOOL);
if (FAILED(hr))
goto Cleanup;
fResult = V_BOOL(&varTemp) == VARIANT_TRUE ? TRUE : FALSE;
}
hr = NOERROR;
Cleanup:
return fResult;
}
/*
* GetDwordFromVariant
*
* Purpose:
* Convert a VARIANT to a DWORD
*
*/
static DWORD GetDwordFromVariant(VARIANT varVariant, DWORD dwDefault)
{
HRESULT hr;
DWORD dwResult = dwDefault;
if (V_VT(&varVariant) != VT_EMPTY && V_VT(&varVariant) != VT_NULL &&
V_VT(&varVariant) != VT_ERROR)
{
VARIANT varTemp;
DL(VariantInit)(&varTemp);
hr = DL(VariantChangeType)(
&varTemp,
&varVariant,
0,
VT_UI4);
if (FAILED(hr))
goto Cleanup;
dwResult = V_UI4(&varTemp);
}
hr = NOERROR;
Cleanup:
return dwResult;
}
/*
* GetLongFromVariant
*
* Purpose:
* Convert a VARIANT to a DWORD
*
*/
static long GetLongFromVariant(VARIANT varVariant, long lDefault)
{
HRESULT hr;
long lResult = lDefault;
if (V_VT(&varVariant) != VT_EMPTY && V_VT(&varVariant) != VT_NULL &&
V_VT(&varVariant) != VT_ERROR)
{
VARIANT varTemp;
DL(VariantInit)(&varTemp);
hr = DL(VariantChangeType)(
&varTemp,
&varVariant,
0,
VT_I4);
if (FAILED(hr))
goto Cleanup;
lResult = V_I4(&varTemp);
}
hr = NOERROR;
Cleanup:
return lResult;
}
/**
* Helper to create a char safearray from a string
*/
static
HRESULT
CreateVector(VARIANT * pVar, const BYTE * pData, DWORD cElems)
{
HRESULT hr;
BYTE * pB;
SAFEARRAY * psa = DL(SafeArrayCreateVector)(VT_UI1, 0, cElems);
if (!psa)
{
hr = E_OUTOFMEMORY;
goto Cleanup;
}
hr = DL(SafeArrayAccessData)(psa, (void **)&pB);
if (FAILED(hr))
goto Error;
memcpy(pB, pData, cElems);
DL(SafeArrayUnaccessData)(psa);
INET_ASSERT((pVar->vt == VT_EMPTY) || (pVar->vt == VT_NULL));
V_ARRAY(pVar) = psa;
pVar->vt = VT_ARRAY | VT_UI1;
hr = NOERROR;
Cleanup:
return hr;
Error:
if (psa)
DL(SafeArrayDestroy)(psa);
goto Cleanup;
}
/*
* ReadFromStream
*
* Purpose:
* Extract the contents of a stream into a buffer.
*
* Parameters:
* ppBuf IN/OUT Buffer
* pStm IN Stream
*
* Errors:
* E_INVALIDARG
* E_OUTOFMEMORY
*/
static
HRESULT
ReadFromStream(char ** ppData, ULONG * pcbData, IStream * pStm)
{
HRESULT hr = NOERROR;
char * pBuffer = NULL; // Buffer
ULONG cbBuffer = 0; // Bytes in buffer
ULONG cbData = 0; // Bytes of data in buffer
ULONG cbRead = 0; // Bytes read from stream
ULONG cbNewSize = 0;
char * pNewBuf = NULL;
if (!ppData || !pStm)
return E_INVALIDARG;
*ppData = NULL;
*pcbData = 0;
while (TRUE)
{
if (cbData + 512 > cbBuffer)
{
cbNewSize = (cbData ? cbData*2 : 4096);
pNewBuf = New char[cbNewSize+1];
if (!pNewBuf)
goto ErrorOutOfMemory;
if (cbData)
::memcpy(pNewBuf, pBuffer, cbData);
cbBuffer = cbNewSize;
delete[] pBuffer;
pBuffer = pNewBuf;
pBuffer[cbData] = 0;
}
hr = pStm->Read(
&pBuffer[cbData],
cbBuffer - cbData,
&cbRead);
if (FAILED(hr))
goto Error;
cbData += cbRead;
pBuffer[cbData] = 0;
// No more data
if (cbRead == 0)
break;
}
*ppData = pBuffer;
*pcbData = cbData;
hr = NOERROR;
Cleanup:
return hr;
ErrorOutOfMemory:
hr = E_OUTOFMEMORY;
goto Error;
Error:
if (pBuffer)
delete [] pBuffer;
goto Cleanup;
}
static
void
MessageLoop()
{
MSG msg;
// There is a window message available. Dispatch it.
while (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
static
DWORD
UpdateTimeout(DWORD dwTimeout, DWORD dwStartTime)
{
if (dwTimeout != INFINITE)
{
DWORD dwTimeNow = GetTickCount();
DWORD dwElapsedTime;
if (dwTimeNow >= dwStartTime)
{
dwElapsedTime = dwTimeNow - dwStartTime;
}
else
{
dwElapsedTime = dwTimeNow + (0xFFFFFFFF - dwStartTime);
}
if (dwElapsedTime < dwTimeout)
{
dwTimeout -= dwElapsedTime;
}
else
{
dwTimeout = 0;
}
}
return dwTimeout;
}
DWORD CSinkArray::Add(IUnknown * pUnk)
{
ULONG iIndex;
IUnknown** pp = NULL;
if (_nSize == 0) // no connections
{
_pUnk = pUnk;
_nSize = 1;
return 1;
}
else if (_nSize == 1)
{
// create array
pp = (IUnknown **)ALLOCATE_ZERO_MEMORY(sizeof(IUnknown*)* _DEFAULT_VECTORLENGTH);
if (pp == NULL)
return 0;
*pp = _pUnk;
_ppUnk = pp;
_nSize = _DEFAULT_VECTORLENGTH;
}
for (pp = begin(); pp < end(); pp++)
{
if (*pp == NULL)
{
*pp = pUnk;
iIndex = ULONG(pp-begin());
return iIndex+1;
}
}
int nAlloc = _nSize*2;
pp = (IUnknown **)REALLOCATE_MEMORY_ZERO(_ppUnk, sizeof(IUnknown*)*nAlloc);
if (pp == NULL)
return 0;
_ppUnk = pp;
_ppUnk[_nSize] = pUnk;
iIndex = _nSize;
_nSize = nAlloc;
return iIndex+1;
}
BOOL CSinkArray::Remove(DWORD dwCookie)
{
ULONG iIndex;
if (dwCookie == NULL)
return FALSE;
if (_nSize == 0)
return FALSE;
iIndex = dwCookie-1;
if (iIndex >= (ULONG)_nSize)
return FALSE;
if (_nSize == 1)
{
_nSize = 0;
return TRUE;
}
begin()[iIndex] = NULL;
return TRUE;
}
void CSinkArray::ReleaseAll()
{
for (IUnknown ** pp = begin(); pp < end(); pp++)
{
if (*pp != NULL)
{
SafeRelease(*pp);
}
}
}
HRESULT STDMETHODCALLTYPE
CSinkArray::QueryInterface(REFIID, void **)
{
return E_NOTIMPL;
}
ULONG STDMETHODCALLTYPE
CSinkArray::AddRef()
{
return 2;
}
ULONG STDMETHODCALLTYPE
CSinkArray::Release()
{
return 1;
}
void STDMETHODCALLTYPE
CSinkArray::OnResponseStart(long Status, BSTR bstrContentType)
{
for (IUnknown ** pp = begin(); pp < end(); pp++)
{
if (*pp != NULL)
{
IWinHttpRequestEvents * pSink;
pSink = static_cast<IWinHttpRequestEvents *>(*pp);
if (((*(DWORD_PTR **)pSink)[3]) != NULL)
{
pSink->OnResponseStart(Status, bstrContentType);
}
}
}
}
void STDMETHODCALLTYPE
CSinkArray::OnResponseDataAvailable(SAFEARRAY ** ppsaData)
{
for (IUnknown ** pp = begin(); pp < end(); pp++)
{
if (*pp != NULL)
{
IWinHttpRequestEvents * pSink;
pSink = static_cast<IWinHttpRequestEvents *>(*pp);
if (((*(DWORD_PTR **)pSink)[4]) != NULL)
{
pSink->OnResponseDataAvailable(ppsaData);
}
}
}
}
void STDMETHODCALLTYPE
CSinkArray::OnResponseFinished(void)
{
for (IUnknown ** pp = begin(); pp < end(); pp++)
{
if (*pp != NULL)
{
IWinHttpRequestEvents * pSink;
pSink = static_cast<IWinHttpRequestEvents *>(*pp);
if (((*(DWORD_PTR **)pSink)[5]) != NULL)
{
pSink->OnResponseFinished();
}
}
}
}
void STDMETHODCALLTYPE
CSinkArray::OnError(long ErrorNumber, BSTR ErrorDescription)
{
for (IUnknown ** pp = begin(); pp < end(); pp++)
{
if (*pp != NULL)
{
IWinHttpRequestEvents * pSink;
pSink = static_cast<IWinHttpRequestEvents *>(*pp);
if (((*(DWORD_PTR **)pSink)[6]) != NULL)
{
pSink->OnError(ErrorNumber, ErrorDescription);
}
}
}
}
CWinHttpRequestEventsMarshaller::CWinHttpRequestEventsMarshaller
(
CSinkArray * pSinkArray,
HWND hWnd
)
{
INET_ASSERT((pSinkArray != NULL) && (hWnd != NULL));
_pSinkArray = pSinkArray;
_hWnd = hWnd;
_cRefs = 0;
_bFireEvents = true;
_cs.Init();
}
CWinHttpRequestEventsMarshaller::~CWinHttpRequestEventsMarshaller()
{
INET_ASSERT(_pSinkArray == NULL);
INET_ASSERT(_hWnd == NULL);
INET_ASSERT(_cRefs == 0);
}
HRESULT
CWinHttpRequestEventsMarshaller::Create
(
CSinkArray * pSinkArray,
CWinHttpRequestEventsMarshaller ** ppSinkMarshaller
)
{
CWinHttpRequestEventsMarshaller * pSinkMarshaller = NULL;
HWND hWnd = NULL;
HRESULT hr = NOERROR;
if (!RegisterWinHttpEventMarshallerWndClass())
goto ErrorFail;
hWnd = CreateWindowEx(0, s_szWinHttpEventMarshallerWndClass, NULL,
0, 0, 0, 0, 0,
(IsPlatformWinNT() && GlobalPlatformVersion5) ? HWND_MESSAGE : NULL,
NULL, GlobalDllHandle, NULL);
if (!hWnd)
goto ErrorFail;
pSinkMarshaller = New CWinHttpRequestEventsMarshaller(pSinkArray, hWnd);
if (!pSinkMarshaller)
goto ErrorOutOfMemory;
SetLastError(0);
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR) pSinkMarshaller);
if (GetLastError() != 0)
goto ErrorFail;
pSinkMarshaller->AddRef();
*ppSinkMarshaller = pSinkMarshaller;
Exit:
if (FAILED(hr))
{
if (pSinkMarshaller)
{
delete pSinkMarshaller;
}
else if (hWnd)
{
DestroyWindow(hWnd);
}
}
return hr;
ErrorFail:
hr = HRESULT_FROM_WIN32(GetLastError());
goto Exit;
ErrorOutOfMemory:
hr = E_OUTOFMEMORY;
goto Exit;
}
void
CWinHttpRequestEventsMarshaller::Shutdown()
{
if (_cs.Lock())
{
FreezeEvents();
if (_hWnd)
{
MessageLoop();
DestroyWindow(_hWnd);
_hWnd = NULL;
}
_pSinkArray = NULL;
_cs.Unlock();
}
}
LRESULT CALLBACK
CWinHttpRequestEventsMarshaller::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg >= WHREM_MSG_ON_RESPONSE_START && msg <= WHREM_MSG_ON_ERROR)
{
CWinHttpRequestEventsMarshaller * pMarshaller;
CSinkArray * pSinkArray = NULL;
bool bOkToFireEvents = false;
pMarshaller = (CWinHttpRequestEventsMarshaller *) GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (pMarshaller)
{
pSinkArray = pMarshaller->GetSinkArray();
bOkToFireEvents = pMarshaller->OkToFireEvents();
}
switch (msg)
{
case WHREM_MSG_ON_RESPONSE_START:
{
BSTR bstrContentType = (BSTR) lParam;
if (bOkToFireEvents)
{
pSinkArray->OnResponseStart((long) wParam, bstrContentType);
}
if (bstrContentType)
{
DL(SysFreeString)(bstrContentType);
}
}
break;
case WHREM_MSG_ON_RESPONSE_DATA_AVAILABLE:
{
SAFEARRAY * psaData = (SAFEARRAY *) wParam;
if (bOkToFireEvents)
{
pSinkArray->OnResponseDataAvailable(&psaData);
}
if (psaData)
{
DL(SafeArrayDestroy)(psaData);
}
}
break;
case WHREM_MSG_ON_RESPONSE_FINISHED:
if (bOkToFireEvents)
{
pSinkArray->OnResponseFinished();
}
break;
case WHREM_MSG_ON_ERROR:
{
BSTR bstrErrorDescription = (BSTR) lParam;
if (bOkToFireEvents)
{
pSinkArray->OnError((long) wParam, bstrErrorDescription);
}
if (bstrErrorDescription)
{
DL(SysFreeString)(bstrErrorDescription);
}
}
break;
}
return 0;
}
else
{
return DefWindowProc(hWnd, msg, wParam, lParam);
}
}
HRESULT STDMETHODCALLTYPE
CWinHttpRequestEventsMarshaller::QueryInterface(REFIID riid, void ** ppv)
{
HRESULT hr = NOERROR;
if (ppv == NULL)
{
hr = E_INVALIDARG;
}
else if (riid == IID_IWinHttpRequestEvents || riid == IID_IUnknown)
{
*ppv = static_cast<IWinHttpRequestEvents *>(this);
AddRef();
}
else
hr = E_NOINTERFACE;
return hr;
}
ULONG STDMETHODCALLTYPE
CWinHttpRequestEventsMarshaller::AddRef()
{
return InterlockedIncrement(&_cRefs);
}
ULONG STDMETHODCALLTYPE
CWinHttpRequestEventsMarshaller::Release()
{
DWORD cRefs = InterlockedDecrement(&_cRefs);
if (cRefs == 0)
{
delete this;
return 0;
}
else
return cRefs;
}
void STDMETHODCALLTYPE
CWinHttpRequestEventsMarshaller::OnResponseStart(long Status, BSTR bstrContentType)
{
if (_cs.Lock())
{
if (OkToFireEvents())
{
BSTR bstrContentTypeCopy;
bstrContentTypeCopy = DL(SysAllocString)(bstrContentType);
PostMessage(_hWnd, WHREM_MSG_ON_RESPONSE_START,
(WPARAM) Status,
(LPARAM) bstrContentTypeCopy);
// Note: ownership of bstrContentTypeCopy is transferred to the
// message window, so the string is not freed here.
}
_cs.Unlock();
}
}
void STDMETHODCALLTYPE
CWinHttpRequestEventsMarshaller::OnResponseDataAvailable(SAFEARRAY ** ppsaData)
{
if (_cs.Lock())
{
if (OkToFireEvents())
{
SAFEARRAY * psaDataCopy = NULL;
if (SUCCEEDED(DL(SafeArrayCopy)(*ppsaData, &psaDataCopy)))
{
PostMessage(_hWnd, WHREM_MSG_ON_RESPONSE_DATA_AVAILABLE,
(WPARAM) psaDataCopy, 0);
}
// Note: ownership of psaDataCopy is transferred to the
// message window, so the array is not freed here.
}
_cs.Unlock();
}
}
void STDMETHODCALLTYPE
CWinHttpRequestEventsMarshaller::OnResponseFinished(void)
{
if (_cs.Lock())
{
if (OkToFireEvents())
{
PostMessage(_hWnd, WHREM_MSG_ON_RESPONSE_FINISHED, 0, 0);
}
_cs.Unlock();
}
}
void STDMETHODCALLTYPE
CWinHttpRequestEventsMarshaller::OnError(long ErrorNumber, BSTR ErrorDescription)
{
if (_cs.Lock())
{
if (OkToFireEvents())
{
BSTR bstrErrorDescriptionCopy;
bstrErrorDescriptionCopy = DL(SysAllocString)(ErrorDescription);
PostMessage(_hWnd, WHREM_MSG_ON_ERROR,
(WPARAM) ErrorNumber,
(LPARAM) bstrErrorDescriptionCopy);
// Note: ownership of bstrErrorDescriptionCopy is transferred to
// the message window, so the string is not freed here.
}
_cs.Unlock();
}
}
BOOL RegisterWinHttpEventMarshallerWndClass()
{
if (s_fWndClassRegistered)
return TRUE;
// only one thread should be here
if (!GeneralInitCritSec.Lock())
return FALSE;
if (s_fWndClassRegistered == FALSE)
{
WNDCLASS wndclass;
wndclass.style = 0;
wndclass.lpfnWndProc = &CWinHttpRequestEventsMarshaller::WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = GlobalDllHandle;
wndclass.hIcon = NULL;
wndclass.hCursor = NULL;;
wndclass.hbrBackground = (HBRUSH)NULL;
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = s_szWinHttpEventMarshallerWndClass;
// Register the window class
if (RegisterClass(&wndclass))
{
s_fWndClassRegistered = TRUE;
}
}
GeneralInitCritSec.Unlock();
return s_fWndClassRegistered;
}
void CleanupWinHttpRequestGlobals()
{
if (s_fWndClassRegistered)
{
// Register the window class
if (UnregisterClass(s_szWinHttpEventMarshallerWndClass, GlobalDllHandle))
{
s_fWndClassRegistered = FALSE;
}
}
if (g_pMimeInfoCache)
{
delete g_pMimeInfoCache;
g_pMimeInfoCache = NULL;
}
}
static
BOOL
IsValidVariant(VARIANT v)
{
BOOL fOk = TRUE;
if (V_ISBYREF(&v))
{
if (IsBadReadPtr(v.pvarVal, sizeof(VARIANT)))
{
fOk = FALSE;
goto Exit;
}
else
v = *(v.pvarVal);
}
switch (v.vt)
{
case VT_BSTR:
fOk = IsValidBstr(v.bstrVal);
break;
case (VT_BYREF | VT_BSTR):
fOk = !IsBadReadPtr(v.pbstrVal, sizeof(BSTR));
break;
case (VT_BYREF | VT_VARIANT):
fOk = !IsBadReadPtr(v.pvarVal, sizeof(VARIANT)) &&
IsValidVariant(*(v.pvarVal));
break;
case VT_UNKNOWN:
case VT_DISPATCH:
fOk = !IsBadReadPtr(v.punkVal, sizeof(void *));
break;
}
Exit:
return fOk;
}
static
HRESULT
SecureFailureFromStatus(DWORD dwFlags)
{
DWORD error;
if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_CERT_REV_FAILED)
{
error = ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
}
else if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_CERT_WRONG_USAGE)
{
error = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
}
else if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CERT)
{
error = ERROR_WINHTTP_SECURE_INVALID_CERT;
}
else if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_CERT_REVOKED)
{
error = ERROR_WINHTTP_SECURE_CERT_REVOKED;
}
else if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CA)
{
error = ERROR_WINHTTP_SECURE_INVALID_CA;
}
else if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_CERT_CN_INVALID)
{
error = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
}
else if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_CERT_DATE_INVALID)
{
error = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
}
else if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR)
{
error = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
}
else
{
error = ERROR_WINHTTP_SECURE_FAILURE;
}
return HRESULT_FROM_WIN32(error);
}
| 25.511975 | 148 | 0.535812 |
2118ad4c107117fafa59610627f5627cff57c214 | 1,409 | hpp | C++ | include/Nazara/VulkanRenderer/Wrapper/Semaphore.hpp | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 11 | 2019-11-27T00:40:43.000Z | 2020-01-29T14:31:52.000Z | include/Nazara/VulkanRenderer/Wrapper/Semaphore.hpp | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 7 | 2019-11-27T00:29:08.000Z | 2020-01-08T18:53:39.000Z | include/Nazara/VulkanRenderer/Wrapper/Semaphore.hpp | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 7 | 2019-11-27T10:27:40.000Z | 2020-01-15T17:43:33.000Z | // Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Vulkan renderer"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_VULKANRENDERER_WRAPPER_SEMAPHORE_HPP
#define NAZARA_VULKANRENDERER_WRAPPER_SEMAPHORE_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/VulkanRenderer/Wrapper/DeviceObject.hpp>
namespace Nz
{
namespace Vk
{
class Semaphore : public DeviceObject<Semaphore, VkSemaphore, VkSemaphoreCreateInfo, VK_OBJECT_TYPE_SEMAPHORE>
{
friend DeviceObject;
public:
Semaphore() = default;
Semaphore(const Semaphore&) = delete;
Semaphore(Semaphore&&) = default;
~Semaphore() = default;
using DeviceObject::Create;
inline bool Create(Device& device, VkSemaphoreCreateFlags flags = 0, const VkAllocationCallbacks* allocator = nullptr);
Semaphore& operator=(const Semaphore&) = delete;
Semaphore& operator=(Semaphore&&) = delete;
private:
static inline VkResult CreateHelper(Device& device, const VkSemaphoreCreateInfo* createInfo, const VkAllocationCallbacks* allocator, VkSemaphore* handle);
static inline void DestroyHelper(Device& device, VkSemaphore handle, const VkAllocationCallbacks* allocator);
};
}
}
#include <Nazara/VulkanRenderer/Wrapper/Semaphore.inl>
#endif // NAZARA_VULKANRENDERER_WRAPPER_SEMAPHORE_HPP
| 32.767442 | 158 | 0.771469 |
2118d9f3e23256b269fc4834c33f50650dc05636 | 5,646 | cc | C++ | deps/autodock/bestpdb.cc | neonious/Neonious-Node | 2859e60ca3f1303127d589d0f50c2aa2b281bc95 | [
"MIT"
] | null | null | null | deps/autodock/bestpdb.cc | neonious/Neonious-Node | 2859e60ca3f1303127d589d0f50c2aa2b281bc95 | [
"MIT"
] | null | null | null | deps/autodock/bestpdb.cc | neonious/Neonious-Node | 2859e60ca3f1303127d589d0f50c2aa2b281bc95 | [
"MIT"
] | null | null | null | /*
$Id: bestpdb.cc,v 1.11 2014/06/12 01:44:07 mp Exp $
AutoDock
Copyright (C) 2009 The Scripps Research Institute. All rights reserved.
AutoDock is a Trade Mark of The Scripps Research Institute.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* bestpdb.cc */
#include <stdio.h>
#include <string.h>
#include "constants.h"
#include "print_rem.h"
#include "strindex.h"
#include "print_avsfld.h"
#include "bestpdb.h"
extern int keepresnum;
extern char dock_param_fn[];
void bestpdb( const int ncluster,
const int num_in_clu[MAX_RUNS],
const int cluster[MAX_RUNS][MAX_RUNS],
const Real econf[MAX_RUNS],
const Real crd[MAX_RUNS][MAX_ATOMS][SPACE],
const char atomstuff[MAX_ATOMS][MAX_CHARS],
const int natom,
const Boole B_write_all_clusmem,
const Real ref_rms[MAX_RUNS],
const int outlev,
FILE *const logFile)
{
register int i=0,
j=0,
k=0,
confnum=0;
int c = 0,
kmax = 0,
/* imol = 0, */
indpf = 0,
off[7],
nframes = 0,
stride = 0,
c1 = 1,
i1 = 1;
char filnm[PATH_MAX],
label[MAX_CHARS];
char AtmNamResNamNumInsCode[20]; /* PDB record 0-origin indices 11-29 (from blank after serial_number to just before xcrd */
pr( logFile, "\n\tLOWEST ENERGY DOCKED CONFORMATION from EACH CLUSTER");
pr( logFile, "\n\t___________________________________________________\n\n\n" );
if (keepresnum > 0 ) {
pr( logFile, "\nKeeping original residue number (specified in the input PDBQ file) for outputting.\n\n");
} else {
pr( logFile, "\nResidue number will be the conformation's rank.\n\n");
}
for (i = 0; i < ncluster; i++) {
i1 = i + 1;
if (B_write_all_clusmem) {
kmax = num_in_clu[i];
} else {
kmax = 1; /* write lowest-energy only */
}
for ( k = 0; k < kmax; k++ ) {
c = cluster[i][k];
c1 = c + 1;
fprintf( logFile, "USER DPF = %s\n", dock_param_fn);
fprintf( logFile, "USER Conformation Number = %d\n", ++confnum);
print_rem(logFile, i1, num_in_clu[i], c1, ref_rms[c]);
if (keepresnum > 0) {
fprintf( logFile, "USER x y z Rank Run Energy RMS\n");
for (j = 0; j < natom; j++) {
sprintf(AtmNamResNamNumInsCode, "%-19.19s", &atomstuff[j][11]);
// retain original residue number (in fact, all fields
// from blank after atom serial number to start of coords)
// replace occupancy by cluster index,
// tempfactor by conformation index within cluster,
// add two non-standard fields with energy and RMSD from reference
#define FORMAT_PDBQT_ATOM_RANKRUN_STR "ATOM %5d%-19.19s%8.3f%8.3f%8.3f%6d%6d %+6.2f %8.3f\n"
fprintf(logFile, FORMAT_PDBQT_ATOM_RANKRUN_STR, j+1, AtmNamResNamNumInsCode,
crd[c][j][X], crd[c][j][Y], crd[c][j][Z], i1, c1, econf[c], ref_rms[c] );
} /* j */
} else {
fprintf( logFile, "USER Rank x y z Run Energy RMS\n");
for (j = 0; j < natom; j++) {
sprintf(AtmNamResNamNumInsCode, "%-11.11s%4d%-4.4s", &atomstuff[j][11],
i1, &atomstuff[j][26]);
// replace original residue number by cluster index
// replace occupancy by conformation index within cluster
// tempfactor by energy
// add one non-standard field with RMSD from reference
#define FORMAT_PDBQT_ATOM_RANKRUN_NUM "ATOM %5d%-19.19s%8.3f%8.3f%8.3f%6d%+6.2f %6.3f\n"
fprintf(logFile, FORMAT_PDBQT_ATOM_RANKRUN_NUM, j+1, AtmNamResNamNumInsCode,
crd[c][j][X], crd[c][j][Y], crd[c][j][Z], c1, econf[c], ref_rms[c] );
} /* j */
}
fprintf( logFile, "TER\n" );
fprintf( logFile, "ENDMDL\n" );
fflush( logFile );
nframes++;
} /* for k */
} /* for i */
fprintf( logFile, "\n" );
strcpy(label, "x y z Rank Run Energy RMS\0" );
if (keepresnum > 0) {
off[0]=5; off[1]=6; off[2]=7; off[3]=8; off[4]=9; off[5]=10; off[6]=11;
stride=12;
} else {
off[0]=5; off[1]=6; off[2]=7; off[3]=4; off[4]=8; off[5]=9; off[6]=10;
stride=11;
} /* if */
indpf = strindex( dock_param_fn, ".dpf" );
strncpy( filnm, dock_param_fn, (size_t)indpf );
filnm[ indpf ] = '\0';
strcat( filnm, ".dlg.pdb\0" );
print_avsfld( logFile, 7, natom, nframes, off, stride, label, filnm );
}
/* EOF */
| 34.851852 | 128 | 0.559511 |
211b8423298a8334dde179387b9288bb7e847119 | 68,192 | cpp | C++ | source/game/guis/UserInterfaceLocal.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | 2 | 2021-05-02T18:37:48.000Z | 2021-07-18T16:18:14.000Z | source/game/guis/UserInterfaceLocal.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | null | null | null | source/game/guis/UserInterfaceLocal.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | null | null | null | // Copyright (C) 2007 Id Software, Inc.
//
#include "../precompiled.h"
#pragma hdrstop
#if defined( _DEBUG ) && !defined( ID_REDIRECT_NEWDELETE )
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include "UserInterfaceLocal.h"
#include "UserInterfaceExpressions.h"
#include "UserInterfaceManagerLocal.h"
#include "UIWindow.h"
#include "../../sys/sys_local.h"
using namespace sdProperties;
idCVar sdUserInterfaceLocal::g_debugGUIEvents( "g_debugGUIEvents", "0", CVAR_GAME | CVAR_INTEGER, "Show the results of events" );
idCVar sdUserInterfaceLocal::g_debugGUI( "g_debugGUI", "0", CVAR_GAME | CVAR_INTEGER, "1 - Show GUI window outlines\n2 - Show GUI window names\n3 - Only show visible windows" );
idCVar sdUserInterfaceLocal::g_debugGUITextRect( "g_debugGUITextRect", "0", CVAR_GAME | CVAR_BOOL, "Show windows' text rectangle outlines" );
idCVar sdUserInterfaceLocal::g_debugGUITextScale( "g_debugGUITextScale", "24", CVAR_GAME | CVAR_FLOAT, "Size that the debug GUI info font is drawn in." );
idCVar sdUserInterfaceLocal::s_volumeMusic_dB( "s_volumeMusic_dB", "0", CVAR_GAME | CVAR_SOUND | CVAR_ARCHIVE | CVAR_FLOAT, "music volume in dB" );
#ifdef SD_PUBLIC_BETA_BUILD
idCVar sdUserInterfaceLocal::g_skipIntro( "g_skipIntro", "1", CVAR_GAME | CVAR_BOOL | CVAR_ROM, "skip the opening intro movie" );
#else
idCVar sdUserInterfaceLocal::g_skipIntro( "g_skipIntro", "0", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "skip the opening intro movie" );
#endif
// Crosshair
idCVar sdUserInterfaceLocal::gui_crosshairDef( "gui_crosshairDef", "crosshairs", CVAR_GAME | CVAR_ARCHIVE | CVAR_PROFILE, "name of def containing crosshair" );
idCVar sdUserInterfaceLocal::gui_crosshairKey( "gui_crosshairKey", "pin_01", CVAR_GAME | CVAR_ARCHIVE | CVAR_PROFILE, "name of crosshair key in def specified by gui_crosshairDef" );
idCVar sdUserInterfaceLocal::gui_crosshairAlpha( "gui_crosshairAlpha", "0.5", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of crosshair" );
idCVar sdUserInterfaceLocal::gui_crosshairSpreadAlpha( "gui_crosshairSpreadAlpha", "0.5", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of spread components" );
idCVar sdUserInterfaceLocal::gui_crosshairStatsAlpha( "gui_crosshairStatsAlpha", "0", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of health/ammo/reload components" );
idCVar sdUserInterfaceLocal::gui_crosshairGrenadeAlpha( "gui_crosshairGrenadeAlpha", "0.5", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of grenade timer components" );
idCVar sdUserInterfaceLocal::gui_crosshairSpreadScale( "gui_crosshairSpreadScale", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "amount to scale the spread indicator movement" );
idCVar sdUserInterfaceLocal::gui_crosshairColor( "gui_crosshairColor", "1 1 1 1", CVAR_GAME | CVAR_ARCHIVE | CVAR_PROFILE, "RGB color tint for crosshair elements" );
// HUD
idCVar sdUserInterfaceLocal::gui_chatAlpha( "gui_chatAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of chat text" );
idCVar sdUserInterfaceLocal::gui_fireTeamAlpha( "gui_fireTeamAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of fireteam list" );
idCVar sdUserInterfaceLocal::gui_commandMapAlpha( "gui_commandMapAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of command map" );
idCVar sdUserInterfaceLocal::gui_objectiveListAlpha( "gui_objectiveListAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of objective list" );
idCVar sdUserInterfaceLocal::gui_personalBestsAlpha( "gui_personalBestsAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of personal bests display list" );
idCVar sdUserInterfaceLocal::gui_objectiveStatusAlpha( "gui_objectiveStatusAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of objective status" );
idCVar sdUserInterfaceLocal::gui_obitAlpha( "gui_obitAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of obituaries" );
idCVar sdUserInterfaceLocal::gui_voteAlpha( "gui_voteAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of vote" );
idCVar sdUserInterfaceLocal::gui_tooltipAlpha( "gui_tooltipAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of tooltips" );
idCVar sdUserInterfaceLocal::gui_vehicleAlpha( "gui_vehicleAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of vehicle information" );
idCVar sdUserInterfaceLocal::gui_vehicleDirectionAlpha( "gui_vehicleDirectionAlpha", "0.5", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of vehicle direction indicators" );
idCVar sdUserInterfaceLocal::gui_showRespawnText( "gui_showRespawnText", "1", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "show text about respawning when in limbo or dead" );
idCVar sdUserInterfaceLocal::gui_tooltipDelay( "gui_tooltipDelay", "0.7", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "Delay in seconds before tooltips pop up." );
idCVar sdUserInterfaceLocal::gui_doubleClickTime( "gui_doubleClickTime", "0.2", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "Delay in seconds between considering two mouse clicks a double-click" );
idStrList sdUserInterfaceLocal::parseStack;
const int sdUserInterfaceLocal::TOOLTIP_MOVE_TOLERANCE = 2;
idBlockAlloc< uiCachedMaterial_t, 64 > sdUserInterfaceLocal::materialCacheAllocator;
const char* sdUserInterfaceLocal::partNames[ FP_MAX ] = {
"tl",
"t",
"tr",
"l",
"r",
"bl",
"b",
"br",
"c",
};
/*
===============================================================================
sdPropertyBinder
===============================================================================
*/
/*
================
sdPropertyBinder::ClearPropertyExpression
================
*/
void sdPropertyBinder::ClearPropertyExpression( int propertyKey, int propertyIndex ) {
boundProperty_t& bp = indexedProperties[ propertyKey ];
int index = bp.second + propertyIndex;
if ( !propertyExpressions[ index ] ) {
return;
}
int count = sdProperties::CountForPropertyType( propertyExpressions[ index ]->GetType() );
int i;
for ( i = 0; i < count; i++ ) {
if ( !propertyExpressions[ index + i ] ) {
continue;
}
propertyExpressions[ index + i ]->Detach();
propertyExpressions[ index + i ] = NULL;
}
}
/*
================
sdPropertyBinder::Clear
================
*/
void sdPropertyBinder::Clear( void ) {
indexedProperties.Clear();
propertyExpressions.Clear();
}
/*
================
sdPropertyBinder::IndexForProperty
================
*/
int sdPropertyBinder::IndexForProperty( sdProperties::sdProperty* property ) {
int i;
for ( i = 0; i < indexedProperties.Num(); i++ ) {
if ( indexedProperties[ i ].first == property ) {
return i;
}
}
boundProperty_t& bp = indexedProperties.Alloc();
bp.first = property;
bp.second = propertyExpressions.Num();
int count = CountForPropertyType( property->GetValueType() );
if ( count == -1 ) {
gameLocal.Error( "sdPropertyBinder::IndexForProperty Property has Invalid Field Count" );
}
for ( i = 0; i < count; i++ ) {
propertyExpressions.Append( NULL );
}
return indexedProperties.Num() - 1;
}
/*
================
sdPropertyBinder::SetPropertyExpression
================
*/
void sdPropertyBinder::SetPropertyExpression( int propertyKey, int propertyIndex, sdUIExpression* expression, sdUserInterfaceScope* scope ) {
boundProperty_t& bp = indexedProperties[ propertyKey ];
int index = bp.second + propertyIndex;
int count = sdProperties::CountForPropertyType( expression->GetType() );
int i;
for ( i = 0; i < count; i++ ) {
if ( propertyExpressions[ index + i ] ) {
propertyExpressions[ index + i ]->Detach();
propertyExpressions[ index + i ] = NULL;
}
}
propertyExpressions[ index ] = expression;
propertyExpressions[ index ]->SetProperty( bp.first, propertyIndex, propertyKey, scope );
}
/*
===============================================================================
sdUserInterfaceState
===============================================================================
*/
/*
================
sdUserInterfaceState::~sdUserInterfaceState
================
*/
sdUserInterfaceState::~sdUserInterfaceState( void ) {
for ( int i = 0; i < expressions.Num(); i++ ) {
expressions[ i ]->Free();
}
expressions.Clear();
}
/*
============
sdUserInterfaceState::GetName
============
*/
const char* sdUserInterfaceState::GetName() const {
return ui->GetName();
}
/*
============
sdUserInterfaceState::GetSubScope
============
*/
sdUserInterfaceScope* sdUserInterfaceState::GetSubScope( const char* name ) {
if ( !idStr::Icmp( name, "module" ) ) {
return ( ui->GetModule() != NULL ) ? ui->GetModule()->GetScope() : NULL;
}
if( !idStr::Icmp( name, "gui" ) ) {
return this;
}
if( !idStr::Icmp( name, "timeline" ) ) {
return ui->GetTimelineManager();
}
sdUIObject* window = ui->GetWindow( name );
if ( window ) {
return &window->GetScope();
}
return NULL;
}
/*
================
sdUserInterfaceState::GetProperty
================
*/
sdProperties::sdProperty* sdUserInterfaceState::GetProperty( const char* name ) {
return properties.GetProperty( name, PT_INVALID, false );
}
/*
============
sdUserInterfaceState::GetProperty
============
*/
sdProperties::sdProperty* sdUserInterfaceState::GetProperty( const char* name, sdProperties::ePropertyType type ) {
sdProperties::sdProperty* prop = properties.GetProperty( name, PT_INVALID, false );
if ( prop && prop->GetValueType() != type && type != PT_INVALID ) {
gameLocal.Error( "sdUserInterfaceState::GetProperty: type mismatch for property '%s'", name );
}
return prop;
}
/*
================
sdUserInterfaceState::SetPropertyExpression
================
*/
void sdUserInterfaceState::SetPropertyExpression( int propertyKey, int propertyIndex, sdUIExpression* expression ) {
boundProperties.SetPropertyExpression( propertyKey, propertyIndex, expression, this );
}
/*
================
sdUserInterfaceState::ClearPropertyExpression
================
*/
void sdUserInterfaceState::ClearPropertyExpression( int propertyKey, int propertyIndex ) {
boundProperties.ClearPropertyExpression( propertyKey, propertyIndex );
}
/*
================
sdUserInterfaceState::RunFunction
================
*/
void sdUserInterfaceState::RunFunction( int expressionIndex ) {
expressions[ expressionIndex ]->Evaluate();
}
/*
================
sdUserInterfaceState::IndexForProperty
================
*/
int sdUserInterfaceState::IndexForProperty( sdProperties::sdProperty* property ) {
return boundProperties.IndexForProperty( property );
}
/*
============
sdUserInterfaceState::GetEvent
============
*/
sdUIEventHandle sdUserInterfaceState::GetEvent( const sdUIEventInfo& info ) const {
return ui->GetEvent( info );
}
/*
============
sdUserInterfaceState::AddEvent
============
*/
void sdUserInterfaceState::AddEvent( const sdUIEventInfo& info, sdUIEventHandle scriptHandle ) {
ui->AddEvent( info, scriptHandle );
}
/*
============
sdUserInterfaceState::ClearExpressions
============
*/
void sdUserInterfaceState::ClearExpressions() {
for ( int i = 0; i < expressions.Num(); i++ ) {
expressions[ i ]->Free();
}
expressions.Clear();
}
/*
============
sdUserInterfaceState::Clear
============
*/
void sdUserInterfaceState::Clear() {
properties.Clear();
transitionExpressions.Clear();
boundProperties.Clear();
}
/*
============
sdUserInterfaceState::GetFunction
============
*/
sdUIFunctionInstance* sdUserInterfaceState::GetFunction( const char* name ) {
return ui->GetFunction( name );
}
/*
============
sdUserInterfaceState::RunNamedFunction
============
*/
bool sdUserInterfaceState::RunNamedFunction( const char* name, sdUIFunctionStack& stack ) {
const sdUserInterfaceLocal::uiFunction_t* func = sdUserInterfaceLocal::FindFunction( name );
if ( !func ) {
return false;
}
CALL_MEMBER_FN_PTR( ui, func->GetFunction() )( stack );
return true;
}
/*
============
sdUserInterfaceState::FindPropertyName
============
*/
const char* sdUserInterfaceState::FindPropertyName( sdProperties::sdProperty* property, sdUserInterfaceScope*& scope ) {
scope = this;
const char* name = properties.NameForProperty( property );
if ( name != NULL ) {
return name;
}
for ( int i = 0 ; i < ui->GetNumWindows(); i++ ) {
sdUIObject* obj = ui->GetWindow( i );
name = obj->GetScope().FindPropertyName( property, scope );
if ( name != NULL ) {
return name;
}
}
return NULL;
}
/*
============
sdUserInterfaceState::GetEvaluator
============
*/
sdUIEvaluatorTypeBase* sdUserInterfaceState::GetEvaluator( const char* name ) {
return GetUI()->GetEvaluator( name );
}
/*
============
sdUserInterfaceState::Update
============
*/
void sdUserInterfaceState::Update( void ) {
int i;
for ( i = 0; i < transitionExpressions.Num(); ) {
sdUIExpression* expression = transitionExpressions[ i ];
if ( !expression->UpdateValue() ) {
transitionExpressions.RemoveIndex( i );
} else {
i++;
}
}
}
/*
================
sdUserInterfaceState::AddTransition
================
*/
void sdUserInterfaceState::AddTransition( sdUIExpression* expression ) {
transitionExpressions.AddUnique( expression );
}
/*
================
sdUserInterfaceState::RemoveTransition
================
*/
void sdUserInterfaceState::RemoveTransition( sdUIExpression* expression ) {
transitionExpressions.Remove( expression );
}
/*
============
sdUserInterfaceState::OnSnapshotHitch
============
*/
void sdUserInterfaceState::OnSnapshotHitch( int delta ) {
for( int i = 0; i < transitionExpressions.Num(); i++ ) {
transitionExpressions[ i ]->OnSnapshotHitch( delta );
}
}
/*
===============================================================================
sdUserInterfaceLocal
===============================================================================
*/
idHashMap< sdUserInterfaceLocal::uiFunction_t* > sdUserInterfaceLocal::uiFunctions;
idList< sdUIEvaluatorTypeBase* > sdUserInterfaceLocal::uiEvaluators;
SD_UI_PUSH_CLASS_TAG( sdUserInterfaceLocal )
const char* sdUserInterfaceLocal::eventNames[ GE_NUM_EVENTS ] = {
SD_UI_EVENT_TAG( "onCreate", "", "Called on window creation" ),
SD_UI_EVENT_TAG( "onActivate", "", "This happens when the GUI is activated." ),
SD_UI_EVENT_TAG( "onDeactivate", "", "This happens when the GUI is activated." ),
SD_UI_EVENT_TAG( "onNamedEvent", "[Event ...]", "Called when one of the events specified occurs" ),
SD_UI_EVENT_TAG( "onPropertyChanged", "[Property ...]", "Called when one of the properties specified occurs" ),
SD_UI_EVENT_TAG( "onCVarChanged", "[CVar ...]", "Called when one of the CVars' value changes" ),
SD_UI_EVENT_TAG( "onCancel", "", "Called when any key bound to the _menuCancel is pressed" ),
SD_UI_EVENT_TAG( "onCancel", "", "Called when any key bound to the _menuCancel is pressed" ),
SD_UI_EVENT_TAG( "onToolTipEvent", "", "Called when a tooltip event occurs" ),
};
SD_UI_POP_CLASS_TAG
/*
================
sdUserInterfaceLocal::sdUserInterfaceLocal
================
*/
sdUserInterfaceLocal::sdUserInterfaceLocal( int _spawnId, bool _isUnique, bool _isPermanent, sdHudModule* _module ) :
spawnId( _spawnId ),
desktop( NULL ),
focusedWindow( NULL ),
entity( NULL ),
guiTime( 0.0f ){
guiDecl = NULL;
theme = NULL;
module = _module;
bindContext = NULL;
shaderParms.SetNum( MAX_ENTITY_SHADER_PARMS - 4 );
for( int i = 0 ; i < shaderParms.Num(); i++ ) {
shaderParms[ i ] = 0.0f;
}
flags.isActive = false;
flags.isUnique = _isUnique;
flags.isPermanent = _isPermanent;
flags.shouldUpdate = true;
currentTime = 0;
scriptState.Init( this );
UI_ADD_STR_CALLBACK( cursorMaterialName, sdUserInterfaceLocal, OnCursorMaterialNameChanged )
UI_ADD_STR_CALLBACK( postProcessMaterialName,sdUserInterfaceLocal, OnPostProcessMaterialNameChanged )
UI_ADD_STR_CALLBACK( focusedWindowName, sdUserInterfaceLocal, OnFocusedWindowNameChanged )
UI_ADD_STR_CALLBACK( screenSaverName, sdUserInterfaceLocal, OnScreenSaverMaterialNameChanged )
UI_ADD_STR_CALLBACK( themeName, sdUserInterfaceLocal, OnThemeNameChanged )
UI_ADD_STR_CALLBACK( bindContextName, sdUserInterfaceLocal, OnBindContextChanged )
UI_ADD_VEC2_CALLBACK( screenDimensions, sdUserInterfaceLocal, OnScreenDimensionChanged )
postProcessMaterial = NULL;
screenSaverMaterial = NULL;
lastMouseMoveTime = 0;
nextAllowToolTipTime = 0;
generalStacks.SetGranularity( 1 );
}
/*
============
sdUserInterfaceLocal::Init
============
*/
void sdUserInterfaceLocal::Init() {
scriptState.GetPropertyHandler().RegisterProperty( "cursorMaterial", cursorMaterialName );
scriptState.GetPropertyHandler().RegisterProperty( "cursorSize", cursorSize );
scriptState.GetPropertyHandler().RegisterProperty( "cursorColor", cursorColor );
scriptState.GetPropertyHandler().RegisterProperty( "cursorPos", cursorPos );
scriptState.GetPropertyHandler().RegisterProperty( "postProcessMaterial", postProcessMaterialName );
scriptState.GetPropertyHandler().RegisterProperty( "focusedWindow", focusedWindowName );
scriptState.GetPropertyHandler().RegisterProperty( "screenDimensions", screenDimensions );
scriptState.GetPropertyHandler().RegisterProperty( "screenCenter", screenCenter );
scriptState.GetPropertyHandler().RegisterProperty( "screenSaverName", screenSaverName );
scriptState.GetPropertyHandler().RegisterProperty( "time", guiTime );
scriptState.GetPropertyHandler().RegisterProperty( "theme", themeName );
scriptState.GetPropertyHandler().RegisterProperty( "bindContext", bindContextName );
scriptState.GetPropertyHandler().RegisterProperty( "flags", scriptFlags );
scriptState.GetPropertyHandler().RegisterProperty( "inputScale", inputScale );
scriptState.GetPropertyHandler().RegisterProperty( "blankWStr", blankWStr );
inputScale = 1.0f;
cursorSize = idVec2( 32.0f, 32.0f );
cursorColor = GetColor( "system/cursor" );
screenSaverName = "system/screensaver";
cursorMaterialName = "system/cursor";
scriptFlags = GUI_INTERACTIVE | GUI_SCREENSAVER;
screenDimensions = idVec2( SCREEN_WIDTH, SCREEN_HEIGHT );
screenDimensions .SetReadOnly( true );
screenCenter = idVec2( SCREEN_WIDTH * 0.5f, SCREEN_HEIGHT * 0.5f );
screenCenter .SetReadOnly( true );
guiTime.SetReadOnly( true );
blankWStr.SetReadOnly( true );
cursorPos = screenCenter;
focusedWindow = NULL;
focusedWindowName = "";
flags.ignoreLocalCursorUpdates = false;
flags.shouldUpdate = true;
toolTipWindow = NULL;
toolTipSource = NULL;
tooltipAnchor = vec2_origin;
postProcessMaterialName = "";
themeName = "default";
generalStacks.Clear();
scriptStack.Clear();
colorStack.Clear();
colorStack.SetGranularity( 1 );
currentColor = colorWhite;
}
/*
================
sdUserInterfaceLocal::~sdUserInterfaceLocal
================
*/
sdUserInterfaceLocal::~sdUserInterfaceLocal( void ) {
parseStack.Clear();
Clear();
}
/*
============
sdUserInterfaceLocal::PushTrace
============
*/
void sdUserInterfaceLocal::PushTrace( const char* info ) {
parseStack.Append( info );
}
/*
============
sdUserInterfaceLocal::PopTrace
============
*/
void sdUserInterfaceLocal::PopTrace() {
if( parseStack.Num() == 0 ) {
gameLocal.Warning( "sdUserInterfaceLocal::PopTrace: Stack underflow" );
return;
}
parseStack.RemoveIndex( parseStack.Num() - 1 );
}
/*
============
sdUserInterfaceLocal::PrintStackTrace
============
*/
void sdUserInterfaceLocal::PrintStackTrace() {
if( parseStack.Num() == 0 ) {
return;
}
gameLocal.Printf( "^3===============================================\n" );
for( int i = parseStack.Num() - 1; i >= 0; i-- ) {
gameLocal.Printf( "%s\n", parseStack[ i ].c_str() );
}
gameLocal.Printf( "^3===============================================\n" );
parseStack.Clear();
}
/*
================
sdUserInterfaceLocal::Load
================
*/
bool sdUserInterfaceLocal::Load( const char* name ) {
if ( guiDecl ) {
assert( false );
return false;
}
guiDecl = gameLocal.declGUIType[ name ];
if ( guiDecl == NULL ) {
gameLocal.Warning( "sdUserInterfaceLocal::Load Invalid GUI '%s'", name );
return false;
}
Init();
PushTrace( va( "Loading %s", GetName() ) );
scriptStack.SetID( GetName() );
const sdDeclGUITheme* theme = gameLocal.declGUIThemeType.LocalFind( "default" );
declManager->AddDependency( GetDecl(), theme );
idTokenCache& tokenCache = declManager->GetGlobalTokenCache();
try {
sdUIWindow::SetupProperties( scriptState.GetPropertyHandler(), guiDecl->GetProperties(), this, tokenCache );
int i;
for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) {
const sdDeclGUIWindow* windowDecl = guiDecl->GetWindow( i );
PushTrace( windowDecl->GetName() );
sdUIObject* object = uiManager->CreateWindow( windowDecl->GetTypeName() );
if ( !object ) {
gameLocal.Error( "sdUserInterfaceLocal::Load Invalid Window Type '%s'", windowDecl->GetTypeName() );
}
object->CreateProperties( this, windowDecl, tokenCache );
object->CreateTimelines( this, windowDecl, tokenCache );
if( windows.Find( object->GetName() ) != windows.End() ) {
gameLocal.Error( "Window named '%s' already exists", object->GetName() );
}
windows.Set( object->GetName(), object );
PopTrace();
}
CreateEvents( guiDecl, tokenCache );
assert( windows.Num() == guiDecl->GetNumWindows() );
for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) {
GetWindow( i )->InitEvents();
}
for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) {
GetWindow( i )->CreateEvents( this, guiDecl->GetWindow( i ), tokenCache );
}
for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) {
GetWindow( i )->CacheEvents();
}
desktop = GetWindow( "desktop" )->Cast< sdUIWindow >();
if( desktop == NULL ) {
gameLocal.Warning( "sdUserInterfaceLocal::Load: could not find 'desktop' in '%s'", name );
}
toolTipWindow = GetWindow( "toolTip" )->Cast< sdUIWindow >();
// parent all the nested windows
for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) {
const sdDeclGUIWindow* windowDecl = guiDecl->GetWindow( i );
const idStrList& children = windowDecl->GetChildren();
PushTrace( windowDecl->GetName() );
windowHash_t::Iterator parentIter = windows.Find( windowDecl->GetName() );
if( parentIter == windows.End() ) {
gameLocal.Error( "sdUserInterfaceLocal::Could not find window '%s'", windowDecl->GetName() );
}
for( int childIndex = 0; childIndex < children.Num(); childIndex++ ) {
windowHash_t::Iterator iter = windows.Find( children[ childIndex ] );
if( iter == windows.End() ) {
gameLocal.Error( "sdUserInterfaceLocal::Could not find window '%s'", children[ childIndex ].c_str() );
}
iter->second->SetParent( parentIter->second );
}
PopTrace();
}
// run constructors now that everything is parented
for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) {
GetWindow( i )->RunEvent( sdUIEventInfo( sdUIObject::OE_CREATE, 0 ) );
GetWindow( i )->OnCreate();
}
} catch ( idException& exception ) {
PrintStackTrace();
throw exception;
}
PopTrace();
return true;
}
/*
================
sdUserInterfaceLocal::Draw
================
*/
void sdUserInterfaceLocal::Draw() {
#ifdef _DEBUG
if( guiDecl && guiDecl->GetBreakOnDraw() ) {
assert( !"BREAK_ON_DRAW" );
}
#endif // _DEBUG
if ( !desktop ) {
return;
}
deviceContext->SetRegisters( shaderParms.Begin() );
bool allowScreenSaver = TestGUIFlag( GUI_SCREENSAVER ) && !TestGUIFlag( GUI_FULLSCREEN );
if ( IsActive() || !allowScreenSaver ) {
desktop->ApplyLayout();
desktop->Draw();
desktop->FinalDraw();
if ( TestGUIFlag( GUI_SHOWCURSOR ) ) {
deviceContext->DrawMaterial( cursorPos.GetValue().x, cursorPos.GetValue().y, cursorSize.GetValue().x, cursorSize.GetValue().y, cursorMaterial, cursorColor );
}
} else if ( screenSaverMaterial != NULL && allowScreenSaver ) {
deviceContext->DrawMaterial( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, screenSaverMaterial, colorWhite );
}
if( g_debugGUI.GetBool() ) {
sdBounds2D rect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT );
deviceContext->SetColor( colorWhite );
deviceContext->SetFontSize( g_debugGUITextScale.GetFloat() );
deviceContext->DrawText( va( L"%hs", guiDecl->GetName() ), rect, DTF_CENTER | DTF_VCENTER | DTF_SINGLELINE );
}
UpdateToolTip();
if ( postProcessMaterial != NULL ) {
deviceContext->DrawMaterial( 0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT, postProcessMaterial, colorWhite );
}
assert( colorStack.Num() == 0 );
}
/*
============
sdUserInterfaceLocal::UpdateToolTip
============
*/
void sdUserInterfaceLocal::UpdateToolTip() {
if( TestGUIFlag( GUI_TOOLTIPS ) ) {
if( toolTipWindow == NULL ) {
gameLocal.Warning( "%s: could not find windowDef 'tooltip' for updating", GetName() );
ClearGUIFlag( GUI_TOOLTIPS );
return;
}
if( toolTipSource == NULL && GetCurrentTime() >= nextAllowToolTipTime ) {
if( !keyInputManager->AnyKeysDown() ) {
// try to spawn a new tool-tip
if( toolTipSource = desktop->UpdateToolTip( cursorPos ) ) {
tooltipAnchor = cursorPos;
} else {
nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() );
}
}
} else if( toolTipSource != NULL ) {
bool keepWindow = false;
if( sdUIWindow* window = toolTipSource->Cast< sdUIWindow >() ) {
// see if the cursor has moved outside of the tool-tip window
sdBounds2D bounds( window->GetWorldRect() );
keepWindow = bounds.ContainsPoint( cursorPos );
}
if( !keepWindow ) {
toolTipSource = NULL;
nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() );
}
}
if( !toolTipSource ) {
CancelToolTip();
return;
}
if( idMath::Fabs( cursorPos.GetValue().x - tooltipAnchor.x ) >= TOOLTIP_MOVE_TOLERANCE ||
idMath::Fabs( cursorPos.GetValue().y - tooltipAnchor.y ) >= TOOLTIP_MOVE_TOLERANCE ) {
CancelToolTip();
nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() );
return;
}
sdProperties::sdProperty* toolText = toolTipSource->GetScope().GetProperty( "toolTipText", PT_WSTRING );
sdProperties::sdProperty* active = toolTipWindow->GetScope().GetProperty( "active", PT_FLOAT );
sdProperties::sdProperty* tipText = toolTipWindow->GetScope().GetProperty( "tipText", PT_WSTRING );
sdProperties::sdProperty* rect = toolTipWindow->GetScope().GetProperty( "rect", PT_VEC4 );
if( toolText && tipText && active ) {
*tipText->value.wstringValue = *toolText->value.wstringValue;
*active->value.floatValue = 1.0f;
}
if( rect != NULL ) {
idVec4 temp = *rect->value.vec4Value;
temp.x = cursorPos.GetValue().x;
temp.y = cursorPos.GetValue().y + cursorSize.GetValue().y * 0.5f;
if( temp.x + temp.z >= screenDimensions.GetValue().x ) {
temp.x -= temp.z;
}
if( temp.y + temp.w >= screenDimensions.GetValue().y ) {
temp.y -= temp.w + cursorSize.GetValue().y * 0.5f;;
}
*rect->value.vec4Value = temp;
}
tooltipAnchor = cursorPos;
nextAllowToolTipTime = 0;
}
}
/*
============
sdUserInterfaceLocal::CancelToolTip
============
*/
void sdUserInterfaceLocal::CancelToolTip() {
if( !toolTipWindow ) {
return;
}
sdProperties::sdProperty* active = toolTipWindow->GetScope().GetProperty( "active" );
if( active ) {
*active->value.floatValue = 0.0f;
}
toolTipSource = NULL;
}
/*
================
sdUserInterfaceLocal::GetWindow
================
*/
sdUIObject* sdUserInterfaceLocal::GetWindow( const char* name ) {
windowHash_t::Iterator iter = windows.Find( name );
if( iter == windows.End() ) {
return NULL;
}
return iter->second;
}
/*
================
sdUserInterfaceLocal::GetWindow
================
*/
const sdUIObject* sdUserInterfaceLocal::GetWindow( const char* name ) const {
windowHash_t::ConstIterator iter = windows.Find( name );
if( iter == windows.End() ) {
return NULL;
}
return iter->second;
}
/*
============
sdUserInterfaceLocal::Clear
============
*/
void sdUserInterfaceLocal::Clear() {
scriptState.ClearExpressions();
// we must do this before we destroy any windows, since a window could be watching other windows' properties
DisconnectGlobalCallbacks();
windowHash_t::Iterator iter = windows.Begin();
while( iter != windows.End() ) {
iter->second->DisconnectGlobalCallbacks();
++iter;
}
for( int i = 0; i < materialCache.Num(); i++ ) {
uiMaterialCache_t::Iterator entry = materialCache.FindIndex( i );
entry->second->material.Clear();
materialCacheAllocator.Free( entry->second );
}
materialCache.Clear();
timelineWindows.Clear();
windows.DeleteValues();
windows.Clear();
externalProperties.DeleteContents( true );
scriptState.Clear();
script.Clear();
scriptStack.Clear();
if( timelines.Get() != NULL ) {
timelines->Clear();
}
focusedWindow = NULL;
desktop = NULL;
guiDecl = NULL;
toolTipSource = NULL;
toolTipWindow = NULL;
themeName = "";
focusedWindowName = "";
cursorMaterialName = "";
cursorSize = vec2_zero;
cursorColor = vec4_zero;
screenSaverName = "";
postProcessMaterialName = "";
}
/*
============
sdUserInterfaceLocal::RegisterTimelineWindow
============
*/
void sdUserInterfaceLocal::RegisterTimelineWindow( sdUIObject* window ) {
timelineWindows.Alloc() = window;
}
idCVar sdUserInterfaceLocal::gui_invertMenuPitch( "gui_invertMenuPitch", "0", CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "invert mouse movement in in-game menus" );
/*
============
sdUserInterfaceLocal::PostEvent
============
*/
bool sdUserInterfaceLocal::PostEvent( const sdSysEvent* event ) {
if ( !desktop || !IsInteractive() ) {
return false;
}
if ( event->IsControllerButtonEvent() || event->IsKeyEvent() ) {
if ( bindContext != NULL ) {
bool down;
sdKeyCommand* cmd = keyInputManager->GetCommand( bindContext, *keyInputManager->GetKeyForEvent( *event, down ) );
if ( cmd != NULL ) {
keyInputManager->ProcessUserCmdEvent( *event );
return true;
}
}
}
// save these off for the events
if ( !flags.ignoreLocalCursorUpdates && event->IsMouseEvent() ) {
idVec2 pos = cursorPos;
idVec2 scaledDelta( event->GetXCoord(), event->GetYCoord() );
scaledDelta *= inputScale;
if ( TestGUIFlag( GUI_FULLSCREEN ) ) {
scaledDelta.x *= ( 1.0f / deviceContext->GetAspectRatioCorrection() );
}
pos.x += scaledDelta.x;
if ( TestGUIFlag( GUI_USE_MOUSE_PITCH ) && gui_invertMenuPitch.GetBool() ) {
pos.y -= scaledDelta.y;
} else {
pos.y += scaledDelta.y;
}
pos.x = idMath::ClampFloat( 0.0f, screenDimensions.GetValue().x, pos.x );
pos.y = idMath::ClampFloat( 0.0f, screenDimensions.GetValue().y, pos.y );
cursorPos = pos;
}
bool retVal = false;
if ( !TestGUIFlag( GUI_SHOWCURSOR ) &&
( event->IsMouseEvent() || ( event->IsMouseButtonEvent() && event->GetMouseButton() >= M_MOUSE1 && event->GetMouseButton() <= M_MOUSE12 ) && !TestGUIFlag( GUI_NON_FOCUSED_MOUSE_EVENTS ) )) {
retVal = false;
} else {
if ( event->IsMouseButtonEvent() && event->IsButtonDown() ) {
if( focusedWindow ) {
retVal |= focusedWindow->HandleFocus( event );
}
if( !retVal ) {
retVal |= desktop->HandleFocus( event );
}
nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() );
}
if( ( ( event->IsMouseButtonEvent() || event->IsKeyEvent() ) && event->IsButtonDown() ) || event->IsGuiEvent() ) {
CancelToolTip();
nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() );
}
if ( focusedWindow == NULL && focusedWindowName.GetValue().Length() ) {
SetFocus( GetWindow( focusedWindowName.GetValue().c_str() )->Cast< sdUIWindow >() );
}
if ( focusedWindow ) {
bool focusedRetVal = focusedWindow->PostEvent( event );
retVal |= focusedRetVal;
if( !focusedRetVal ) {
// give immediate parents that capture key events a crack
if( !retVal && event->IsKeyEvent() || event->IsGuiEvent() ) {
sdUIObject* parent = focusedWindow->GetNode().GetParent();
while( parent != NULL && retVal == false ) {
if( sdUIWindow* window = parent->Cast< sdUIWindow >() ) {
if( window->TestFlag( sdUIWindow::WF_CAPTURE_KEYS ) ) {
retVal |= parent->PostEvent( event );
}
}
parent = parent->GetNode().GetParent();
}
}
}
}
if( !retVal ) {
retVal |= desktop->PostEvent( event );
}
}
// eat everything but the F-Keys
if ( TestGUIFlag( GUI_CATCH_ALL_EVENTS ) ) {
keyNum_t keyNum;
if ( event->IsKeyEvent() ) {
keyNum = event->GetKey();
} else {
keyNum = K_INVALID;
}
if ( ( keyNum != K_INVALID && ( keyNum < K_F1 || keyNum > K_F15 ) ) || ( event->IsControllerButtonEvent() ) ) {
retVal = true;
}
}
if( TestGUIFlag( GUI_TOOLTIPS ) && event->IsMouseEvent() ) {
lastMouseMoveTime = GetCurrentTime();
}
return retVal;
}
/*
============
sdUserInterfaceLocal::Shutdown
============
*/
void sdUserInterfaceLocal::Shutdown( void ) {
uiFunctions.DeleteContents();
uiEvaluators.DeleteContents( true );
}
/*
============
sdUserInterfaceLocal::FindFunction
============
*/
sdUserInterfaceLocal::uiFunction_t* sdUserInterfaceLocal::FindFunction( const char* name ) {
sdUserInterfaceLocal::uiFunction_t** ptr;
return uiFunctions.Get( name, &ptr ) ? *ptr : NULL;
}
/*
============
sdUserInterfaceLocal::GetFunction
============
*/
sdUIFunctionInstance* sdUserInterfaceLocal::GetFunction( const char* name ) {
uiFunction_t* function = FindFunction( name );
if ( function == NULL ) {
return NULL;
}
return new sdUITemplateFunctionInstance< sdUserInterfaceLocal, sdUITemplateFunctionInstance_Identifier >( this, function );
}
/*
============
sdUserInterfaceLocal::GetEvaluator
============
*/
sdUIEvaluatorTypeBase* sdUserInterfaceLocal::GetEvaluator( const char* name ) {
int i;
for ( i = 0; i < uiEvaluators.Num(); i++ ) {
if ( !idStr::Cmp( uiEvaluators[ i ]->GetName(), name ) ) {
return uiEvaluators[ i ];
}
}
return NULL;
}
/*
================
sdUserInterfaceLocal::CreateEvents
================
*/
void sdUserInterfaceLocal::CreateEvents( const sdDeclGUI* guiDecl, idTokenCache& tokenCache ) {
parseStack.Clear();
const idList< sdDeclGUIProperty* >& guiProperties = guiDecl->GetProperties();
events.Clear();
events.SetNumEvents( GE_NUM_EVENTS );
namedEvents.Clear();
sdUserInterfaceLocal::PushTrace( va( "sdUserInterfaceLocal::CreateEvents for gui '%s'", guiDecl->GetName() ));
idList<unsigned short> constructorTokens;
bool hasValues = sdDeclGUI::CreateConstructor( guiDecl->GetProperties(), constructorTokens, tokenCache );
if( hasValues ) {
sdUserInterfaceLocal::PushTrace( "<constructor>" );
idLexer parser( sdDeclGUI::LEXER_FLAGS );
parser.LoadTokenStream( constructorTokens, tokenCache, "sdUserInterfaceLocal::CreateEvents" );
sdUIEventInfo constructionEvent( GE_CONSTRUCTOR, 0 );
GetScript().ParseEvent( &parser, constructionEvent, &scriptState );
RunEvent( constructionEvent );
sdUserInterfaceLocal::PopTrace();
}
if( guiDecl->GetTimelines().GetNumTimelines() > 0 ) {
timelines.Reset( new sdUITimelineManager( *this, scriptState, script ));
timelines->CreateTimelines( guiDecl->GetTimelines(), guiDecl );
timelines->CreateProperties( guiDecl->GetTimelines(), guiDecl, tokenCache );
}
const idList< sdDeclGUIEvent* >& guiEvents = guiDecl->GetEvents();
idList< sdUIEventInfo > eventList;
for ( int i = 0; i < guiEvents.Num(); i++ ) {
const sdDeclGUIEvent* eventInfo = guiEvents[ i ];
sdUserInterfaceLocal::PushTrace( tokenCache[ eventInfo->GetName() ] );
eventList.Clear();
EnumerateEvents( tokenCache[ eventInfo->GetName() ], eventInfo->GetFlags(), eventList, tokenCache );
for ( int j = 0; j < eventList.Num(); j++ ) {
idLexer parser( sdDeclGUI::LEXER_FLAGS );
parser.LoadTokenStream( eventInfo->GetTokenIndices(), tokenCache, tokenCache[ eventInfo->GetName() ] );
GetScript().ParseEvent( &parser, eventList[ j ], &scriptState );
}
sdUserInterfaceLocal::PopTrace();
}
if( timelines.Get() != NULL ) {
timelines->CreateEvents( guiDecl->GetTimelines(), guiDecl, tokenCache );
}
RunEvent( sdUIEventInfo( GE_CREATE, 0 ) );
}
/*
================
sdUserInterfaceLocal::EnumerateEvents
================
*/
void sdUserInterfaceLocal::EnumerateEvents( const char* name, const idList<unsigned short>& flags, idList< sdUIEventInfo >& events, const idTokenCache& tokenCache ) {
if ( !idStr::Icmp( name, "onActivate" ) ) {
events.Append( sdUIEventInfo( GE_ACTIVATE, 0 ) );
return;
}
if ( !idStr::Icmp( name, "onDeactivate" ) ) {
events.Append( sdUIEventInfo( GE_DEACTIVATE, 0 ) );
return;
}
if ( !idStr::Icmp( name, "onCancel" ) ) {
events.Append( sdUIEventInfo( GE_CANCEL, 0 ) );
return;
}
if ( !idStr::Icmp( name, "onNamedEvent" ) ) {
int i;
for ( i = 0; i < flags.Num(); i++ ) {
events.Append( sdUIEventInfo( GE_NAMED, NamedEventHandleForString( tokenCache[ flags[ i ] ] ) ) );
}
return;
}
if( !idStr::Icmp( name, "onCVarChanged" ) ) {
int i;
for( i = 0; i < flags.Num(); i++ ) {
const idToken& name = tokenCache[ flags[ i ] ];
idCVar* cvar = cvarSystem->Find( name.c_str() );
if( cvar == NULL ) {
gameLocal.Error( "Event 'onCVarChanged' could not find cvar '%s'", name.c_str() );
return;
}
int eventHandle = NamedEventHandleForString( name.c_str() );
cvarCallback_t* callback = new cvarCallback_t( *this, *cvar, eventHandle );
cvarCallbacks.Append( callback );
events.Append( sdUIEventInfo( GE_CVARCHANGED, eventHandle ) );
}
return;
}
if ( !idStr::Icmp( name, "onToolTipEvent" ) ) {
events.Append( sdUIEventInfo( GE_TOOLTIPEVENT, 0 ) );
return;
}
if ( !idStr::Icmp( name, "onPropertyChanged" ) ) {
int i;
for ( i = 0; i < flags.Num(); i++ ) {
const idToken& name = tokenCache[ flags[ i ] ];
// do a proper lookup, so windows can watch guis and vice-versa
idLexer p( sdDeclGUI::LEXER_FLAGS );
p.LoadMemory( name, name.Length(), "onPropertyChanged event handler" );
sdUserInterfaceScope* propertyScope = gameLocal.GetUserInterfaceScope( GetState(), &p );
idToken token;
p.ReadToken( &token );
sdProperty* prop = propertyScope->GetProperty( token );
if( !prop ) {
gameLocal.Error( "sdUserInterfaceLocal::EnumerateEvents: event 'onPropertyChanged' could not find property '%s'", name.c_str() );
return;
}
int eventHandle = NamedEventHandleForString( name.c_str() );
int cbHandle = -1;
switch( prop->GetValueType() ) {
case PT_VEC4:
cbHandle = prop->value.vec4Value->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idVec4&, const idVec4& >( &sdUserInterfaceLocal::OnVec4PropertyChanged, this , eventHandle ) );
break;
case PT_VEC3:
cbHandle = prop->value.vec3Value->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idVec3&, const idVec3& >( &sdUserInterfaceLocal::OnVec3PropertyChanged, this , eventHandle ) );
break;
case PT_VEC2:
cbHandle = prop->value.vec2Value->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idVec2&, const idVec2& >( &sdUserInterfaceLocal::OnVec2PropertyChanged, this , eventHandle ) );
break;
case PT_INT:
cbHandle = prop->value.intValue->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const int, const int >( &sdUserInterfaceLocal::OnIntPropertyChanged, this , eventHandle ) );
break;
case PT_FLOAT:
cbHandle = prop->value.floatValue->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const float, const float >( &sdUserInterfaceLocal::OnFloatPropertyChanged, this , eventHandle ) );
break;
case PT_STRING:
cbHandle = prop->value.stringValue->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idStr&, const idStr& >( &sdUserInterfaceLocal::OnStringPropertyChanged, this , eventHandle ) );
break;
case PT_WSTRING:
cbHandle = prop->value.wstringValue->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idWStr&, const idWStr& >( &sdUserInterfaceLocal::OnWStringPropertyChanged, this , eventHandle ) );
break;
}
toDisconnect.Append( callbackHandler_t( prop, cbHandle ));
events.Append( sdUIEventInfo( GE_PROPCHANGED, eventHandle ) );
}
return;
}
gameLocal.Error( "sdUserInterfaceLocal::EnumerateEvents: unknown event '%s'", name );
}
/*
================
sdUserInterfaceLocal::Activate
================
*/
void sdUserInterfaceLocal::Activate( void ) {
if( !guiDecl ) {
return;
}
if ( flags.isActive ) {
return;
}
flags.isActive = true;
CancelToolTip();
if ( NonGameGui() ) {
SetCurrentTime( sys->Milliseconds() );
} else {
SetCurrentTime( gameLocal.time + gameLocal.timeOffset );
}
Update();
if( timelines.Get() != NULL ) {
timelines->ResetAllTimelines();
}
int i;
for ( i = 0; i < windows.Num(); i++ ) {
sdUIObject* object = windows.FindIndex( i )->second;
if( sdUIWindow* window = object->Cast< sdUIWindow >() ) {
window->OnActivate();
}
}
RunEvent( sdUIEventInfo( GE_ACTIVATE, 0 ) );
}
/*
================
sdUserInterfaceLocal::Deactivate
================
*/
void sdUserInterfaceLocal::Deactivate( bool forceDeactivate ) {
if( !guiDecl ) {
return;
}
if ( !flags.isActive || ( !forceDeactivate && !TestGUIFlag( GUI_SCREENSAVER ) )) {
return;
}
flags.isActive = false;
if( timelines.Get() != NULL ) {
timelines->ClearAllTimelines();
}
RunEvent( sdUIEventInfo( GE_DEACTIVATE, 0 ) );
}
/*
================
sdUserInterfaceLocal::Update
================
*/
void sdUserInterfaceLocal::Update( void ) {
if ( !IsActive() ) {
return;
}
guiTime.SetReadOnly( false );
guiTime = currentTime;
guiTime.SetReadOnly( true );
screenDimensions.SetReadOnly( false );
screenCenter.SetReadOnly( false );
if ( TestGUIFlag( GUI_FULLSCREEN ) ) {
float adjustedWidth = idMath::Ceil( SCREEN_WIDTH * ( 1.0f / deviceContext->GetAspectRatioCorrection() ) );
screenDimensions.SetIndex( 0, adjustedWidth );
} else {
screenDimensions.SetIndex( 0, SCREEN_WIDTH );
}
screenCenter.SetIndex( 0 , screenDimensions.GetValue().x / 2.0f );
screenCenter.SetReadOnly( true );
screenDimensions.SetReadOnly( true );
if ( timelines.Get() != NULL ) {
timelines->Run( currentTime );
}
for ( int i = 0; i < timelineWindows.Num(); i++ ) {
sdUITimelineManager* manager = timelineWindows[ i ]->GetTimelineManager();
manager->Run( currentTime );
}
scriptState.Update();
}
/*
================
sdUserInterfaceLocal::AddEvent
================
*/
void sdUserInterfaceLocal::AddEvent( const sdUIEventInfo& info, sdUIEventHandle scriptHandle ) {
events.AddEvent( info, scriptHandle );
}
/*
================
sdUserInterfaceLocal::GetEvent
================
*/
sdUIEventHandle sdUserInterfaceLocal::GetEvent( const sdUIEventInfo& info ) const {
return events.GetEvent( info );
}
/*
============
sdUserInterfaceLocal::RunEvent
============
*/
bool sdUserInterfaceLocal::RunEvent( const sdUIEventInfo& info ) {
return GetScript().RunEventHandle( GetEvent( info ), &scriptState );
}
/*
============
sdUserInterfaceLocal::SetFocus
============
*/
void sdUserInterfaceLocal::SetFocus( sdUIWindow* focus ) {
if( focusedWindow == focus ) {
return;
}
if( focusedWindow ) {
focusedWindow->OnLoseFocus();
}
focusedWindow = focus;
if( focusedWindow ) {
focusedWindow->OnGainFocus();
}
}
/*
============
sdUserInterfaceLocal::OnCursorMaterialNameChanged
============
*/
void sdUserInterfaceLocal::OnCursorMaterialNameChanged( const idStr& oldValue, const idStr& newValue ) {
if( newValue.Length() ) {
cursorMaterial = gameLocal.declMaterialType.LocalFind( GetMaterial( newValue ));
if( cursorMaterial && cursorMaterial->GetSort() < SS_POST_PROCESS ) {
if ( cursorMaterial->GetSort() != SS_GUI && cursorMaterial->GetSort() != SS_NEAREST ) {
gameLocal.Warning( "sdUserInterfaceLocal::OnCursorMaterialNameChanged: material %s used in gui '%s' without proper sort", cursorMaterial->GetName(), GetName() );
}
}
} else {
cursorMaterial = NULL;
}
}
/*
============
sdUserInterfaceLocal::OnPostProcessMaterialNameChanged
============
*/
void sdUserInterfaceLocal::OnPostProcessMaterialNameChanged( const idStr& oldValue, const idStr& newValue ) {
if( newValue.Length() ) {
postProcessMaterial = gameLocal.declMaterialType.LocalFind( GetMaterial( newValue ));
} else {
postProcessMaterial = NULL;
}
}
/*
============
sdUserInterfaceLocal::OnFocusedWindowNameChanged
============
*/
void sdUserInterfaceLocal::OnFocusedWindowNameChanged( const idStr& oldValue, const idStr& newValue ) {
SetFocus( GetWindow( newValue )->Cast< sdUIWindow >() );
if( newValue.Length() && !focusedWindow ) {
gameLocal.Warning( "sdUserInterfaceLocal::OnFocusedWindowNameChanged: '%s' could not find windowDef '%s' for focus", GetName(), newValue.c_str() );
}
}
/*
============
sdUserInterfaceLocal::OnOnScreenSaverMaterialNameChanged
============
*/
void sdUserInterfaceLocal::OnScreenSaverMaterialNameChanged( const idStr& oldValue, const idStr& newValue ) {
if( newValue.Length() ) {
screenSaverMaterial = gameLocal.declMaterialType.LocalFind( GetMaterial( newValue ));
} else {
screenSaverMaterial = NULL;
}
}
/*
============
sdUserInterfaceLocal::SetRenderCallback
============
*/
void sdUserInterfaceLocal::SetRenderCallback( const char* objectName, uiRenderCallback_t callback, uiRenderCallbackType_t type ) {
sdUIWindow* object = GetWindow( objectName )->Cast< sdUIWindow >();
if( object == NULL ) {
gameLocal.Error( "sdUserInterfaceLocal::SetRenderCallback: could not find window '%s'", objectName );
}
object->SetRenderCallback( callback, type );
}
/*
============
sdUserInterfaceLocal::PostNamedEvent
============
*/
bool sdUserInterfaceLocal::PostNamedEvent( const char* event, bool allowMissing ) {
assert( event );
int index = namedEvents.FindIndex( event );
if( index == -1 ) {
if( !allowMissing ) {
gameLocal.Error( "sdUserInterfaceLocal::PostNamedEvent: could not find event '%s' in '%s'", event, guiDecl != NULL ? guiDecl->GetName() : "unknown GUI" );
}
return false;
}
if( g_debugGUIEvents.GetBool() ) {
gameLocal.Printf( "GUI '%s': named event '%s'\n", GetName(), event );
}
return RunEvent( sdUIEventInfo( GE_NAMED, index ) );
}
/*
============
sdUserInterfaceLocal::NamedEventHandleForString
============
*/
int sdUserInterfaceLocal::NamedEventHandleForString( const char* name ) {
int index = namedEvents.FindIndex( name );
if( index == -1 ) {
index = namedEvents.Append( name ) ;
}
return index;
}
/*
============
sdUserInterfaceLocal::OnStringPropertyChanged
============
*/
void sdUserInterfaceLocal::OnStringPropertyChanged( int event, const idStr& oldValue, const idStr& newValue ) {
RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) );
}
/*
============
sdUserInterfaceLocal::OnWStringPropertyChanged
============
*/
void sdUserInterfaceLocal::OnWStringPropertyChanged( int event, const idWStr& oldValue, const idWStr& newValue ) {
RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) );
}
/*
============
sdUserInterfaceLocal::OnIntPropertyChanged
============
*/
void sdUserInterfaceLocal::OnIntPropertyChanged( int event, const int oldValue, const int newValue ) {
RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) );
}
/*
============
sdUserInterfaceLocal::OnFloatPropertyChanged
============
*/
void sdUserInterfaceLocal::OnFloatPropertyChanged( int event, const float oldValue, const float newValue ) {
RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) );
}
/*
============
sdUserInterfaceLocal::OnVec4PropertyChanged
============
*/
void sdUserInterfaceLocal::OnVec4PropertyChanged( int event, const idVec4& oldValue, const idVec4& newValue ) {
RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) );
}
/*
============
sdUserInterfaceLocal::OnVec3PropertyChanged
============
*/
void sdUserInterfaceLocal::OnVec3PropertyChanged( int event, const idVec3& oldValue, const idVec3& newValue ) {
RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) );
}
/*
============
sdUserInterfaceLocal::OnVec2PropertyChanged
============
*/
void sdUserInterfaceLocal::OnVec2PropertyChanged( int event, const idVec2& oldValue, const idVec2& newValue ) {
RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) );
}
/*
============
sdUserInterfaceLocal::SetCursor
============
*/
void sdUserInterfaceLocal::SetCursor( const int x, const int y ) {
idVec2 pos( idMath::ClampInt( 0, SCREEN_WIDTH, x ), idMath::ClampInt( 0, SCREEN_HEIGHT, y ) );
cursorPos = pos;
}
/*
============
sdUserInterfaceLocal::SetTheme
============
*/
void sdUserInterfaceLocal::SetTheme( const char* theme ) {
const sdDeclGUITheme* newTheme = gameLocal.declGUIThemeType.LocalFind( theme, false );
if( !newTheme ) {
newTheme = gameLocal.declGUIThemeType.LocalFind( "default", true );
}
if( this->theme != newTheme ) {
bool isActive = IsActive();
if ( isActive ) {
Deactivate( true );
}
this->theme = newTheme;
if ( guiDecl != NULL ) {
declManager->AddDependency( GetDecl(), newTheme );
// regenerate
idStr name = guiDecl->GetName();
guiDecl = NULL;
Clear();
Load( name );
}
if ( isActive ) {
Activate();
}
}
}
/*
============
sdUserInterfaceLocal::GetMaterial
============
*/
const char* sdUserInterfaceLocal::GetMaterial( const char* key ) const {
if( key[ 0 ] == '\0' ) {
return "";
}
const char* out = GetDecl() ? GetDecl()->GetMaterials().GetString( key, "" ) : "";
if( out[ 0 ] == '\0' && GetTheme() ) {
out = GetTheme()->GetMaterial( key );
}
return out;
}
/*
============
sdUserInterfaceLocal::GetSound
============
*/
const char* sdUserInterfaceLocal::GetSound( const char* key ) const {
if( key[ 0 ] == '\0' ) {
return "";
}
if( idStr::Icmpn( key, "::", 2 ) == 0 ) {
return key + 2;
}
const char* out = GetDecl() ? GetDecl()->GetSounds().GetString( key, "" ) : "";
if( out[ 0 ] == '\0' && GetTheme() ) {
out = GetTheme()->GetSound( key );
}
return out;
}
/*
============
sdUserInterfaceLocal::GetColor
============
*/
idVec4 sdUserInterfaceLocal::GetColor( const char* key ) const {
if( key[ 0 ] == '\0' ) {
return colorWhite;
}
idVec4 out;
if( !GetDecl() || !GetDecl()->GetColors().GetVec4( key, "1 1 1 1", out ) && GetTheme() ) {
out = GetTheme()->GetColor( key );
}
return out;
}
/*
============
sdUserInterfaceLocal::ApplyLatchedTheme
============
*/
void sdUserInterfaceLocal::ApplyLatchedTheme() {
if ( latchedTheme.Length() > 0 ) {
SetTheme( latchedTheme );
latchedTheme.Clear();
}
}
/*
============
sdUserInterfaceLocal::OnThemeNameChanged
============
*/
void sdUserInterfaceLocal::OnThemeNameChanged( const idStr& oldValue, const idStr& newValue ) {
if( newValue.IsEmpty() ) {
latchedTheme = "default";
} else {
latchedTheme = newValue;
}
}
/*
============
sdUserInterfaceLocal::OnBindContextChanged
============
*/
void sdUserInterfaceLocal::OnBindContextChanged( const idStr& oldValue, const idStr& newValue ) {
if ( newValue.IsEmpty() ) {
bindContext = NULL;
} else {
bindContext = keyInputManager->AllocBindContext( newValue.c_str() );
}
}
/*
============
sdUserInterfaceLocal::OnScreenDimensionChanged
============
*/
void sdUserInterfaceLocal::OnScreenDimensionChanged( const idVec2& oldValue, const idVec2& newValue ) {
windowHash_t::Iterator iter = windows.Begin();
while( iter != windows.End() ) {
if( sdUIWindow* window = iter->second->Cast< sdUIWindow >() ) {
window->MakeLayoutDirty();
}
++iter;
}
}
/*
============
sdUserInterfaceLocal::Translate
============
*/
bool sdUserInterfaceLocal::Translate( const idKey& key, sdKeyCommand** cmd ) {
if ( bindContext == NULL ) {
return false;
}
*cmd = keyInputManager->GetCommand( bindContext, key );
return *cmd != NULL;
}
/*
============
sdUserInterfaceLocal::EndLevelLoad
============
*/
void sdUserInterfaceLocal::EndLevelLoad() {
uiMaterialCache_t::Iterator cacheIter= materialCache.Begin();
while( cacheIter != materialCache.End() ) {
uiCachedMaterial_t& cached = *( cacheIter->second );
LookupPartSizes( cached.parts.Begin(), cached.parts.Num() );
SetupMaterialInfo( cached.material );
++cacheIter;
}
windowHash_t::Iterator iter = windows.Begin();
while( iter != windows.End() ) {
iter->second->EndLevelLoad();
++iter;
}
}
/*
============
sdUserInterfaceLocal::PopGeneralScriptVar
============
*/
void sdUserInterfaceLocal::PopGeneralScriptVar( const char* stackName, idStr& str ) {
if( stackName[ 0 ] == '\0' ) {
gameLocal.Error( "sdUserInterfaceLocal::PopGeneralScriptVar: empty stack name" );
}
stringStack_t& stack = generalStacks[ stackName ];
if( stack.Num() == 0 ) {
gameLocal.Error( "sdUserInterfaceLocal::PopGeneralScriptVar: stack underflow for '%s'", stackName );
}
int index = stack.Num() - 1;
str = stack[ index ];
stack.SetNum( index );
}
/*
============
sdUserInterfaceLocal::PushGeneralScriptVar
============
*/
void sdUserInterfaceLocal::PushGeneralScriptVar( const char* stackName, const char* str ) {
if( stackName[ 0 ] == '\0' ) {
gameLocal.Error( "sdUserInterfaceLocal::PushGeneralScriptVar: empty stack name" );
}
generalStacks[ stackName ].Append( str );
}
/*
============
sdUserInterfaceLocal::GetGeneralScriptVar
============
*/
void sdUserInterfaceLocal::GetGeneralScriptVar( const char* stackName, idStr& str ) {
if( stackName[ 0 ] == '\0' ) {
gameLocal.Error( "sdUserInterfaceLocal::GetGeneralScriptVar: empty stack name" );
}
stringStack_t& stack = generalStacks[ stackName ];
if( stack.Num() == 0 ) {
gameLocal.Error( "sdUserInterfaceLocal::GetGeneralScriptVar: stack underflow for '%s'", stackName );
}
int index = stack.Num() - 1;
str = stack[ index ];
}
/*
============
sdUserInterfaceLocal::ClearGeneralStrings
============
*/
void sdUserInterfaceLocal::ClearGeneralStrings( const char* stackName ) {
if( stackName[ 0 ] == '\0' ) {
gameLocal.Error( "sdUserInterfaceLocal::ClearGeneralStrings: empty stack name" );
}
stringStack_t& stack = generalStacks[ stackName ];
stack.Clear();
}
/*
============
sdUserInterfaceLocal::OnCVarChanged
============
*/
void sdUserInterfaceLocal::OnCVarChanged( idCVar& cvar, int id ) {
bool result = RunEvent( sdUIEventInfo( GE_CVARCHANGED, id ) );
if( result && sdUserInterfaceLocal::g_debugGUIEvents.GetInteger() ) {
gameLocal.Printf( "%s: OnCVarChanged\n", GetName() );
}
}
/*
============
sdUserInterfaceLocal::OnInputInit
============
*/
void sdUserInterfaceLocal::OnInputInit( void ) {
if ( bindContextName.GetValue().IsEmpty() ) {
bindContext = NULL;
} else {
bindContext = keyInputManager->AllocBindContext( bindContextName.GetValue().c_str() );
}
}
/*
============
sdUserInterfaceLocal::OnInputShutdown
============
*/
void sdUserInterfaceLocal::OnInputShutdown( void ) {
bindContext = NULL;
}
/*
============
sdUserInterfaceLocal::OnLanguageInit
============
*/
void sdUserInterfaceLocal::OnLanguageInit( void ) {
if ( desktop != NULL ) {
desktop->OnLanguageInit();
sdUIObject::OnLanguageInit_r( desktop );
}
}
/*
============
sdUserInterfaceLocal::OnLanguageShutdown
============
*/
void sdUserInterfaceLocal::OnLanguageShutdown( void ) {
if ( desktop != NULL ) {
desktop->OnLanguageShutdown();
sdUIObject::OnLanguageShutdown_r( desktop );
}
}
/*
============
sdUserInterfaceLocal::MakeLayoutDirty
============
*/
void sdUserInterfaceLocal::MakeLayoutDirty() {
if ( desktop != NULL ) {
desktop->MakeLayoutDirty();
sdUIObject::MakeLayoutDirty_r( desktop );
}
}
/*
============
sdUserInterfaceLocal::SetCachedMaterial
============
*/
uiMaterialCache_t::Iterator sdUserInterfaceLocal::SetCachedMaterial( const char* alias, const char* newMaterial, int& handle ) {
uiMaterialCache_t::Iterator findResult = FindCachedMaterial( alias, handle );
if( findResult == materialCache.End() ) {
uiMaterialCache_t::InsertResult result = materialCache.Set( alias, materialCacheAllocator.Alloc() );
findResult = result.first;
}
handle = findResult - materialCache.Begin();
uiCachedMaterial_t& cached = *( findResult->second );
idStr material;
bool globalLookup = false;
bool literal = false;
int offset = ParseMaterial( newMaterial, material, globalLookup, literal, cached.drawMode );
if( cached.drawMode != BDM_SINGLE_MATERIAL && cached.drawMode != BDM_USE_ST ) {
InitPartsForBaseMaterial( material, cached );
return findResult;
}
if( globalLookup ) {
material = "::" + material;
}
if( literal ) {
LookupMaterial( va( "literal: %hs", newMaterial + offset ), cached.material );
} else if( ( material.Length() && !globalLookup ) || ( material.Length() > 2 && globalLookup ) ) {
LookupMaterial( material, cached.material );
}
return findResult;
}
/*
============
sdUserInterfaceLocal::FindCachedMaterial
============
*/
uiMaterialCache_t::Iterator sdUserInterfaceLocal::FindCachedMaterial( const char* alias, int& handle ) {
uiMaterialCache_t::Iterator iter = materialCache.Find( alias );
if( iter == materialCache.End() ) {
handle = -1;
} else {
handle = iter - materialCache.Begin();
}
return iter;
}
/*
============
sdUserInterfaceLocal::FindCachedMaterialForHandle
============
*/
uiMaterialCache_t::Iterator sdUserInterfaceLocal::FindCachedMaterialForHandle( int handle ) {
if( handle < 0 || handle >= materialCache.Num() ) {
return materialCache.End();
}
return materialCache.Begin() + handle;
}
/*
============
sdUserInterfaceLocal::LookupPartSizes
============
*/
void sdUserInterfaceLocal::LookupPartSizes( uiDrawPart_t* parts, int num ) {
for ( int i= 0; i < num; i++ ) {
uiDrawPart_t& part = parts[ i ];
if ( part.mi.material == NULL || ( part.width != 0 && part.height != 0 ) ) {
continue;
}
if ( part.mi.material->GetNumStages() == 0 ) {
part.mi.material = NULL;
continue;
}
SetupMaterialInfo( part.mi, &part.width, &part.height );
if ( part.width == 0 || part.height == 0 ) {
assert( 0 );
part.mi.material = NULL;
}
}
}
/*
============
sdUserInterfaceLocal::SetupMaterialInfo
============
*/
void sdUserInterfaceLocal::SetupMaterialInfo( uiMaterialInfo_t& mi, int* baseWidth, int* baseHeight ) {
if( mi.material == NULL ) {
return;
}
if( const idImage* image = mi.material->GetEditorImage() ) {
if( image->sourceWidth == 0 ) { // the image hasn't been loaded yet, so defer texture coordinate calculation
mi.flags.lookupST = true;
return;
}
}
if( !mi.flags.lookupST ) {
return;
}
if( const idImage* image = mi.material->GetEditorImage() ) {
// if they're zeroed assume 0-1 range
if( mi.st0.Compare( vec2_zero, idMath::FLT_EPSILON ) && mi.st1.Compare( vec2_zero, idMath::FLT_EPSILON ) ) {
mi.st0.Set( 0.0f, 0.0f );
mi.st1.Set( 1.0f, 1.0f );
if( baseWidth != NULL ) {
*baseWidth = image->sourceWidth;
}
if( baseHeight != NULL ) {
*baseHeight = image->sourceHeight;
}
} else {
if( baseWidth != NULL ) {
*baseWidth = idMath::Ftoi( mi.st1.x );
}
if( baseHeight != NULL ) {
*baseHeight = idMath::Ftoi( mi.st1.y );
}
mi.st0.x = mi.st0.x / static_cast< float >( image->sourceWidth );
mi.st0.y = mi.st0.y / static_cast< float >( image->sourceHeight );
mi.st1.x = mi.st0.x + ( mi.st1.x / static_cast< float >( image->sourceWidth ) );
mi.st1.y = mi.st0.y + ( mi.st1.y / static_cast< float >( image->sourceHeight ) );
}
}
if( mi.flags.flipX ) {
idSwap( mi.st0.x, mi.st1.x );
}
if( mi.flags.flipY ) {
idSwap( mi.st0.y, mi.st1.y );
}
mi.flags.lookupST = false;
}
/*
============
sdUserInterfaceLocal::ParseMaterial
============
*/
int sdUserInterfaceLocal::ParseMaterial( const char* mat, idStr& outMaterial, bool& globalLookup, bool& literal, uiDrawMode_e& mode ) {
idLexer src( mat, idStr::Length( mat ), "ParseMaterial", LEXFL_ALLOWPATHNAMES );
idToken token;
outMaterial.Empty();
globalLookup = false;
literal = false;
mode = BDM_SINGLE_MATERIAL;
int materialStart = 0;
while( !src.HadError() ) {
materialStart = src.GetFileOffset();
if( !src.ReadToken( &token )) {
break;
}
if( token.Icmp( "literal:" ) == 0 ) {
literal = true;
continue;
}
if( token.Icmp( "_frame" ) == 0 ) {
mode = BDM_FRAME;
continue;
}
if( token.Icmp( "_st" ) == 0 ) {
mode = BDM_USE_ST;
continue;
}
if( token.Icmp( "_3v" ) == 0 ) {
mode = BDM_TRI_PART_V;
continue;
}
if( token.Icmp( "_3h" ) == 0 ) {
mode = BDM_TRI_PART_H;
continue;
}
if( token.Icmp( "_5h" ) == 0 ) {
mode = BDM_FIVE_PART_H;
continue;
}
if( token == "::" ) {
globalLookup = true;
continue;
}
outMaterial = token;
break;
}
return materialStart;
}
/*
============
sdUserInterfaceLocal::InitPartsForBaseMaterial
============
*/
void sdUserInterfaceLocal::InitPartsForBaseMaterial( const char* material, uiCachedMaterial_t& cached ) {
cached.parts.SetNum( FP_MAX );
if( cached.drawMode == BDM_FIVE_PART_H ) {
SetupPart( cached.parts[ FP_TOPLEFT ], partNames[ FP_TOPLEFT ], material );
SetupPart( cached.parts[ FP_LEFT ], partNames[ FP_LEFT ], material ); // stretched
SetupPart( cached.parts[ FP_CENTER ], partNames[ FP_CENTER ], material );
SetupPart( cached.parts[ FP_RIGHT ], partNames[ FP_RIGHT ], material ); // stretched
SetupPart( cached.parts[ FP_TOPRIGHT ], partNames[ FP_TOPRIGHT ], material );
return;
}
if( cached.drawMode == BDM_TRI_PART_H ) {
SetupPart( cached.parts[ FP_LEFT ], partNames[ FP_LEFT ], material );
SetupPart( cached.parts[ FP_RIGHT ], partNames[ FP_RIGHT ], material );
SetupPart( cached.parts[ FP_CENTER ], partNames[ FP_CENTER ], material );
return;
}
if( cached.drawMode == BDM_TRI_PART_V ) {
SetupPart( cached.parts[ FP_TOP ], partNames[ FP_TOP ], material );
SetupPart( cached.parts[ FP_BOTTOM ], partNames[ FP_BOTTOM ], material );
SetupPart( cached.parts[ FP_CENTER ], partNames[ FP_CENTER ], material );
return;
}
for( int i = 0; i < FP_MAX; i++ ) {
SetupPart( cached.parts[ i ], partNames[ i ], material );
}
}
/*
============
sdUserInterfaceLocal::SetupPart
============
*/
void sdUserInterfaceLocal::SetupPart( uiDrawPart_t& part, const char* partName, const char* material ) {
if( idStr::Length( material ) == 0 ) {
part.mi.material = NULL;
part.width = 0;
part.height = 0;
return;
}
LookupMaterial( va( "%s_%s", material, partName ), part.mi, &part.width, &part.height );
if( part.mi.material->GetNumStages() == 0 ) {
part.mi.material = NULL;
part.width = 0;
part.height = 0;
return;
}
}
/*
============
sdUserInterfaceLocal::LookupMaterial
============
*/
void sdUserInterfaceLocal::LookupMaterial( const char* materialName, uiMaterialInfo_t& mi, int* baseWidth, int* baseHeight ) {
mi.Clear();
bool globalLookup = false;
static const char* LITERAL_ID = "literal:";
static const int LITERAL_ID_LENGTH = idStr::Length( LITERAL_ID );
bool literal = !idStr::Icmpn( LITERAL_ID, materialName, LITERAL_ID_LENGTH );
if( !literal ) {
globalLookup = !idStr::Icmpn( "::", materialName, 2 );
if( globalLookup ) {
materialName += 2;
}
}
if( globalLookup ) {
if(idStr::Length( materialName ) == 0 ) {
mi.material = declHolder.FindMaterial( "_default" );
} else {
mi.material = declHolder.FindMaterial( materialName );
}
} else {
const char* materialInfo = materialName;
if( literal ) {
materialInfo += LITERAL_ID_LENGTH;
} else {
materialInfo = GetMaterial( materialName );
}
idToken token;
char buffer[128];
token.SetStaticBuffer( buffer, sizeof(buffer) );
idLexer src( materialInfo, idStr::Length( materialInfo ), "LookupMaterial", LEXFL_ALLOWPATHNAMES );
src.ReadToken( &token ); // material name
if( token.Length() == 0 ) {
mi.material = declHolder.FindMaterial( "_default" );
} else {
mi.material = declHolder.FindMaterial( token );
}
while( src.ReadToken( &token )) {
if( token == "," ) {
continue;
}
if( token.Icmp( "flipX" ) == 0 ) {
mi.flags.flipX = true;
continue;
}
if( token.Icmp( "flipY" ) == 0 ) {
mi.flags.flipY = true;
continue;
}
static idVec4 vec;
if( token.Icmp( "rect" ) == 0 ) {
src.Parse1DMatrix( 4, vec.ToFloatPtr(), true );
mi.st0.x = vec.x;
mi.st0.y = vec.y;
mi.st1.x = vec.z;
mi.st1.y = vec.w;
continue;
}
src.Error( "Unknown token '%s'", token.c_str() );
break;
}
}
if ( mi.material->GetSort() < SS_POST_PROCESS ) {
if ( mi.material->GetSort() != SS_GUI && mi.material->GetSort() != SS_NEAREST ) {
gameLocal.Warning( "LookupMaterial: '%s' material '%s' (alias '%s') used without proper sort", GetName(), mi.material->GetName(), materialName );
}
}
mi.flags.lookupST = true;
SetupMaterialInfo( mi, baseWidth, baseHeight );
}
/*
============
sdUserInterfaceLocal::PushColor
============
*/
void sdUserInterfaceLocal::PushColor( const idVec4& color ) {
currentColor = color;
colorStack.Push( deviceContext->SetColorMultiplier( color ) );
}
/*
============
sdUserInterfaceLocal::PopColor
============
*/
idVec4 sdUserInterfaceLocal::PopColor() {
idVec4 c = colorStack.Top();
deviceContext->SetColorMultiplier( c );
colorStack.Pop();
currentColor = c;
return c;
}
/*
============
sdUserInterfaceLocal::TopColor
============
*/
const idVec4& sdUserInterfaceLocal::TopColor() const{
return currentColor;
}
/*
============
sdUserInterfaceLocal::OnSnapshotHitch
============
*/
void sdUserInterfaceLocal::OnSnapshotHitch( int delta ) {
scriptState.OnSnapshotHitch( delta );
if( timelines.IsValid() ) {
timelines->OnSnapshotHitch( delta );
}
}
/*
============
sdUserInterfaceLocal::OnToolTipEvent
============
*/
void sdUserInterfaceLocal::OnToolTipEvent( const char* arg ) {
sdUIEventInfo event( GE_TOOLTIPEVENT, 0 );
if ( event.eventType.IsValid() ) {
PushScriptVar( arg );
RunEvent( sdUIEventInfo( GE_TOOLTIPEVENT, 0 ) );
ClearScriptStack();
}
} | 28.907164 | 208 | 0.64534 |
211beb59677d3c88fe37fd2d46ea5ced20f24cd1 | 7,492 | cpp | C++ | source/Structure/custom_plugins/plugins/HIL_server/server.cpp | Guiraffo/ProVANT_Simulator | ef2260204b13f39a9f83ad2ab88a9552a0699bff | [
"MIT"
] | null | null | null | source/Structure/custom_plugins/plugins/HIL_server/server.cpp | Guiraffo/ProVANT_Simulator | ef2260204b13f39a9f83ad2ab88a9552a0699bff | [
"MIT"
] | null | null | null | source/Structure/custom_plugins/plugins/HIL_server/server.cpp | Guiraffo/ProVANT_Simulator | ef2260204b13f39a9f83ad2ab88a9552a0699bff | [
"MIT"
] | null | null | null |
#include "server.h"
#include <time.h>
#include "XMLRead.h"
namespace gazebo
{
HilServer::HilServer()
{
Fr = 0;
Fl = 0;
Tr = 0;
Tl = 0;
}
HilServer::~HilServer()
{
try
{
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
void HilServer::Update()
{
// static int i = 0;
// mutex.lock();
std::lock_guard<std::mutex> lck(mtx);
SetInputVANT20(Fr, Fl, Tr, Tl);
// std::cout << "Fr: " << Fr << std::endl;
// std::cout << "Fl: " << Fl << std::endl;
// std::cout << "Tr: " << Tr << std::endl;
// std::cout << "Tl: " << Tl << std::endl;
// mutex.unlock();
// i++;
// std::cout << "Contador: " << i << std::endl;
}
void HilServer::thread()
{
struct timespec start, stop;
std::chrono::high_resolution_clock::time_point tf;
std::chrono::high_resolution_clock::time_point tf2;
std::chrono::high_resolution_clock::time_point to;
std::chrono::high_resolution_clock::time_point to2;
// clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
to = std::chrono::high_resolution_clock::now();
to2 = to;
while (true)
{
Frame frame;
frame = receive(serial);
if (frame.unbuild())
{
float flag = frame.getFloat();
if (flag == 1) // Envia os estados
{
// std::cout << "1" << std::endl;
// clock_gettime(CLOCK_REALTIME, &stop);
/*double result = (stop.tv_sec - start.tv_sec) * 1e3 + (stop.tv_nsec - start.tv_nsec) / 1e6; // in
microseconds std::cout << result << std::endl; clock_gettime(CLOCK_REALTIME, &start);*/
// depois
tf = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::nano> delta_t = tf - to;
std::chrono::duration<double, std::nano> delta_t2 = tf - to2;
// std::chrono::duration<double,std::ratio<1l,1000000l>> delta_t =
// std::chrono::duration_cast<std::chrono::miliseconds>(tf - to);
std::cout << delta_t.count() / 1000000.0 << "," << delta_t2.count() / 1000000000.0 << ",";
// std::cout << model->GetWorld()->GetRealTime().FormattedString() << ",";
// antes
to = tf;
GetStatesVANT20();
SetSerialData();
}
else
{
if (flag == 0) // se 0
{
// std::cout << "0" << std::endl;
// mutex.lock();
std::lock_guard<std::mutex> lck(mtx);
Fr = frame.getFloat();
Fl = frame.getFloat();
Tr = frame.getFloat();
Tl = frame.getFloat();
std::cout << Fr << ",";
std::cout << Fl << ",";
std::cout << Tr << ",";
std::cout << Tl << std::endl;
// mutex.unlock();
}
else
{
if (flag == 3) // Updates the control inputs
{
std::lock_guard<std::mutex> lck(mtx);
Fr = frame.getFloat();
Fl = frame.getFloat();
Tr = frame.getFloat();
Tl = frame.getFloat();
// Frame frame2;
// frame2.addFloat(3);
// frame2.build();
// serial.send(frame2.buffer(),frame2.buffer_size());
model->GetWorld()->SetPaused(false);
}
else
{
std::cout << "Deu ruim" << std::endl;
}
}
}
}
}
}
void HilServer::Load(physics::ModelPtr _model, sdf::ElementPtr _sdf)
{
try
{
model = _model;
// std::cout << "Load" << std::endl;
// conectando comunicação serial
// if (!serial.connect("/tmp/ttyS1",115200)) exit(1);
if (serial.connect("/dev/ttyUSB0", 921600 /*576000*/))
{
// obtendo dados do arquivo de descrição "model.sdf"
NameOfJointR_ = XMLRead::ReadXMLString("NameOfJointR", _sdf);
NameOfJointL_ = XMLRead::ReadXMLString("NameOfJointL", _sdf);
link_name_ = XMLRead::ReadXMLString("bodyName", _sdf);
link_right_ = XMLRead::ReadXMLString("BrushlessR", _sdf);
link_left_ = XMLRead::ReadXMLString("BrushlessL", _sdf);
// apontando ponteiros para acesso a dados do mundo, elo e juntas
world = _model->GetWorld();
link = _model->GetLink(link_name_);
linkR = _model->GetLink(link_right_);
linkL = _model->GetLink(link_left_);
juntaR = _model->GetJoint(NameOfJointR_);
juntaL = _model->GetJoint(NameOfJointL_);
// Iniciando comunicação serial
t = new boost::thread(boost::bind(&gazebo::HilServer::thread, this));
// configurando temporizador para callback
updateConnection = event::Events::ConnectWorldUpdateBegin([this](const common::UpdateInfo& info) {
(void)info; // Supress unused variable warning
this->Update();
});
}
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
void HilServer::Reset()
{
}
// Método para enviar dados para o sistema embarcado
void HilServer::SetSerialData()
{
Frame frame;
frame.addFloat(x);
frame.addFloat(y);
frame.addFloat(z);
frame.addFloat(roll);
frame.addFloat(pitch);
frame.addFloat(yaw);
frame.addFloat(alphar);
frame.addFloat(alphal);
frame.addFloat(vx);
frame.addFloat(vy);
frame.addFloat(vz);
frame.addFloat(wx);
frame.addFloat(wy);
frame.addFloat(wz);
frame.addFloat(dalphar);
frame.addFloat(dalphal);
frame.build();
serial.send(frame.buffer(), frame.buffer_size());
// std::cout << "Dados:" << std::endl;
std::cout << x << ",";
std::cout << y << ",";
std::cout << z << ",";
std::cout << roll << ",";
std::cout << pitch << ",";
std::cout << yaw << ",";
std::cout << alphar << ",";
std::cout << alphal << ",";
std::cout << vx << ",";
std::cout << vy << ",";
std::cout << vz << ",";
std::cout << wx << ",";
std::cout << wy << ",";
std::cout << wz << ",";
std::cout << dalphar << ",";
std::cout << dalphal << ",";
}
// Método para Ler dados de simulação
void HilServer::GetStatesVANT20()
{
// dados da pose inicial
ignition::math::Pose3d pose = link->WorldPose();
x = pose.Pos().X(); // x
y = pose.Pos().Y(); // y
z = pose.Pos().Z(); // z
roll = pose.Rot().Euler().X(); // roll
pitch = pose.Rot().Euler().Y(); // pitch
yaw = pose.Rot().Euler().Z(); // yaw
alphar = juntaR->Position(0); // alphaR
alphal = juntaL->Position(0); // alphaL
ignition::math::Vector3d linear = link->WorldLinearVel();
vx = linear.X(); // vx
vy = linear.Y(); // vy
vz = linear.Z(); // vz
ignition::math::Vector3d angular = link->WorldAngularVel();
wx = angular.X(); // wx
wy = angular.Y(); // wy
wz = angular.Z(); // wz
dalphar = juntaR->GetVelocity(0); // dalphaR
dalphal = juntaL->GetVelocity(0); // dalphaL
}
// Método para escrever dados de simulação
void HilServer::SetInputVANT20(double Fr_, double Fl_, double Tr_, double Tl_)
{
// Força de propulsão do motor direito
ignition::math::Vector3d forceR(0, 0, Fr_);
ignition::math::Vector3d torqueR(0, 0, 0.0178947368 * Fr_);
linkR->AddRelativeForce(forceR);
linkR->AddRelativeTorque(torqueR);
// Força de propulsão do motor esquerdo
ignition::math::Vector3d forceL(0, 0, Fl_);
ignition::math::Vector3d torqueL(0, 0, -0.0178947368 * Fl_);
linkL->AddRelativeForce(forceL);
linkL->AddRelativeTorque(torqueL);
// Torque do servo direito
juntaR->SetForce(0, Tr_);
// Torque do servo esquerdo
juntaL->SetForce(0, Tl_);
}
GZ_REGISTER_MODEL_PLUGIN(HilServer)
} // namespace gazebo
| 28.271698 | 109 | 0.565937 |