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
int64 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
int64 1
67k
⌀ | 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
int64 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
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3415954e216bb53928018e5951bfdded31f93395
| 9,872
|
cpp
|
C++
|
Engine/src/Core/IO/icFileWin.cpp
|
binofet/ice
|
dee91da76df8b4f46ed4727d901819d8d20aefe3
|
[
"MIT"
] | null | null | null |
Engine/src/Core/IO/icFileWin.cpp
|
binofet/ice
|
dee91da76df8b4f46ed4727d901819d8d20aefe3
|
[
"MIT"
] | null | null | null |
Engine/src/Core/IO/icFileWin.cpp
|
binofet/ice
|
dee91da76df8b4f46ed4727d901819d8d20aefe3
|
[
"MIT"
] | null | null | null |
#ifdef WIN32
#include "Core/IO/icFile.h"
/*! Function converts ICE file modes to Microsoft flags
*
* @param u8Mode 8-bit mask of ICFILEMODE flags
* @param[out] pAccess Pointer for access rights
* @param[out] pCreateD Pointer for creation disposition
* @param[out] pFandA Pointer for flags and attributes
**/
void _GetFileParams(uchar u8Mode, DWORD* pAccess, DWORD* pCreateD,
DWORD* pFandA)
{
*pAccess=0; *pFandA = 0;
if (u8Mode&ICFM_READ) *pAccess |= GENERIC_READ;
if (u8Mode&ICFM_WRITE) *pAccess |= GENERIC_WRITE;
if (u8Mode&ICFM_CREATE_ALWAYS) *pCreateD = CREATE_ALWAYS;
if (u8Mode&ICFM_CREATE_NEW) *pCreateD = CREATE_NEW;
if (u8Mode&ICFM_OPEN_ALWAYS) *pCreateD = OPEN_ALWAYS;
if (u8Mode&ICFM_OPEN_EXISTING) *pCreateD = OPEN_EXISTING;
if (u8Mode&ICFM_ASYNC) *pFandA |= FILE_FLAG_OVERLAPPED|FILE_FLAG_NO_BUFFERING;
}// END FUNCTION _GetFileParams(uchar u8Mode, DWORD* pAccess, DWORD* pCreateD)
/*! Asynchronous operation callback
*
*
* @param dwErrorCode Error flags
* @param dwBytesMoved The number of bytes transferred
* @param lpOverlapped The overlapped structure for async op
**/
VOID CALLBACK icFile::AsyncCB(__in DWORD dwErrorCode,
__in DWORD dwBytesMoved,
__in LPOVERLAPPED lpOverlapped)
{
if (lpOverlapped)
{
icFile* pFile = static_cast<icFile*>(lpOverlapped);
// check for errors
if (dwErrorCode)
{
// should probably take a look at better way to handle this
icWarning("There was an error returned from Async Operation");
}
pFile->m_u64FilePos += dwBytesMoved;
pFile->m_bStreaming = false;
// call user callback function with their pointer
if (pFile->m_pVoidCallback)
(*pFile->m_pVoidCallback)(pFile->m_ptrUser, (size_t)dwBytesMoved);
}
else
{
// this should likely never happen
icError("Undefined behavior in Asynchronous callback");
}
}
/*! c'tor
**/
icFile::icFile(void)
{
ZeroMemory(this,sizeof(icFile));
m_pFile = NULL;
m_ptrUser = NULL;
m_pVoidCallback = NULL;
m_u64FilePos = 0;
m_bStreaming = false;
}// END FUNCTION icFile(void)
/*! d'tor
**/
icFile::~icFile(void)
{
if (m_pFile)
{
StopAsync();
if (hEvent)
CloseHandle(hEvent);
CloseHandle(m_pFile);
}
}// END FUNCTION ~icFile(void)
/*! Opens a file
*
* @param szFile Name of file to open
* @param u8Mode File mode (read/write/etc)
* @returns ICRESULT Status after open
**/
ICRESULT icFile::Open(const char *szFile, uchar u8Mode)
{
Close();
DWORD dwAccess=0;
DWORD dwShareMode=FILE_SHARE_READ; //! should this be exposed?
DWORD dwCreateDisp=0;
DWORD dwFandA=0;
m_FileMode = u8Mode;
_GetFileParams(u8Mode, &dwAccess, &dwCreateDisp, &dwFandA);
m_pFile = CreateFileA(szFile, // LPCSTR
dwAccess, // Desired Access
dwShareMode, // Share Mode
NULL, // lpSecurityAttributes
dwCreateDisp, // Creation Disposition
dwFandA, // Flags and attributes
NULL); // HANDLE to template file
if (m_pFile && m_pFile != INVALID_HANDLE_VALUE)
return IC_OK;
return IC_FAIL_GEN;
}// END FUNCTION Open(const char* szFile, u
/*! Closes the file
*
* This will stall in the event there is an asynchronous operation
* still in progress.
*
* @returns ICRESULT Status after closing the file
**/
ICRESULT icFile::Close(void)
{
m_FileMode = 0;
m_ptrUser = NULL;
m_pVoidCallback = NULL;
m_u64FilePos = 0;
if (m_pFile)
{
// WAIT FOR ANY PENDING ASYNCHRONOUS CALLS
while (m_bStreaming)
SleepEx(50, TRUE);
if (hEvent)
{
CloseHandle(hEvent);
hEvent = NULL;
}
if (CloseHandle(m_pFile))
{
m_pFile = NULL;
return IC_OK;
}
m_pFile = NULL;
return IC_FAIL_GEN;
}
m_bStreaming = false;
return IC_OK;
}// END FUNCTION Close(void)
/*! Reads data from file
*
* Note: This should not be called by ASYNC File objects
*
* @param pDest Destination buffer
* @param size Size in bytes to read
* @param sizeread Pointer to store size actually read
* @returns ICRESULT Status after file read
**/
ICRESULT icFile::Read(void* pDest, size_t size, size_t* sizeread)
{
if (m_pFile && !(m_FileMode&ICFM_ASYNC))
{
if (ReadFile(m_pFile, pDest, size, (LPDWORD)sizeread, NULL))
{
m_u64FilePos += *sizeread;
return IC_OK;
}
}
return IC_WARN_GEN;
}// END FUNCTION Read(void* pDest, size_t size, size_t* sizeread)
/*! Asynchronous Read
*
*
*
* @param pDest Destination buffer
* @param size Size in bytes to read
* @param userPtr Pointer user can use as needed
* @param callback Function to call when read is finished
* @returns ICRESULT Status after starting the async-read
**/
ICRESULT icFile::ReadAsync(void* pDest, size_t size,
void* userPtr, void (*callback)(void*,size_t))
{
if (m_pFile && !m_bStreaming)
{
m_pVoidCallback = callback;
m_ptrUser = userPtr;
m_bStreaming = true;
hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
if (ReadFileEx(m_pFile, pDest, size,
(LPOVERLAPPED)this, AsyncCB))
return IC_OK;
m_bStreaming = false;
}
return IC_WARN_GEN;
}// END FUNCTION ReadAsync(void* pDest, size_t size, void (*callback)(void))
/*! Stops all Asynchronous operations
*
* @returns ICRESULT Status after stopping asynchronous ops
**/
ICRESULT icFile::StopAsync(void)
{
if (m_pFile && m_bStreaming)
{
if (CancelIo(m_pFile))
//if (CancelIoEx(m_pFile, this))
{
m_bStreaming = false;
return IC_OK;
}
}
return IC_WARN_GEN;
}// END FUNCTION StopRead(void)
/*! Writes data to a file
*
* @param pSource Pointer to data to be written to file
* @param size Size of data (in bytes) to write
* @param[out] sizewritten Size of data actually written to the file
* @returns ICRESULT Status after the file write
**/
ICRESULT icFile::Write(void* pSource, size_t size, size_t* sizewritten)
{
if (m_pFile && !(m_FileMode&ICFM_ASYNC))
{
if (WriteFile(m_pFile, pSource, (DWORD)size,
(LPDWORD)sizewritten, NULL))
{
m_u64FilePos += *sizewritten;
return IC_OK;
}
}
return IC_FAIL_GEN;
}// END FUNCTION Write(void* pSource, size_t size, size_t* sizewritten)
/*! Writes to a file asynchronously
*
* @param pSource Pointer to data to be written to file
* @param size Size of data (in bytes) to write
* @param userPtr Pointer for user to use in callback
* @param callback Function pointer for user callback
* @returns ICRESULT Status after the file write
**/
ICRESULT icFile::WriteAsync(void* pSource, size_t size,
void* userPtr, void (*callback)(void*,size_t))
{
if (m_pFile && !m_bStreaming)
{
m_pVoidCallback = callback;
m_ptrUser = userPtr;
m_bStreaming = true;
hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
if (WriteFileEx(m_pFile, pSource, (DWORD)size, (LPOVERLAPPED)this, AsyncCB))
{
FlushFileBuffers(m_pFile);
return IC_OK;
}
else
{
m_bStreaming = false;
DWORD err = GetLastError();
icWarningf("icFile::WriteAsync failed with error: %i",err);
}
}
return IC_FAIL_GEN;
}// END FUNCTION WriteAsync(void* pSource, size_t size,
// void* userPtr, void (*callback)(void*,size_t))
/*! Get File Size in bytes
*
* @param size Pointer to store file size
* @returns ICRESULT Status after getting size
**/
ICRESULT icFile::GetSize(uint64* size)
{
if (m_pFile)
{
DWORD high=0;
DWORD low = GetFileSize(m_pFile, &high);
// check fail condition
if (low != INVALID_FILE_SIZE)
{
*size = (uint64)low | (uint64)high<<32;
return IC_OK;
}
}
return IC_FAIL_GEN;
}// END FUNCTION GetSize(size_t* size)
/*! Get the current file position
*
*
* @param pos Pointer to store file position
* @returns ICRESULT Status after getting file position
**/
ICRESULT icFile::GetPos(uint64* pos)
{
if (m_pFile)
{
*pos = m_u64FilePos;
return IC_OK;
}
return IC_FAIL_GEN;
}// END FUNCTION GetPos(size_t* pos)
/*! Sets the file pointer
*
* @param pos Desired file position
* @returns ICRESULT Status after changing file position
**/
ICRESULT icFile::SetPos(const uint64 pos)
{
if (m_pFile)
{
#if 1
LARGE_INTEGER liPos;
liPos.QuadPart = pos;
if (SetFilePointerEx(m_pFile, liPos,
(PLARGE_INTEGER)&m_u64FilePos, FILE_BEGIN))
#else
long liPos = (long)pos;
if (SetFilePointer(m_pFile, liPos,
0, FILE_BEGIN))
#endif
return IC_OK;
}
::MessageBoxA(NULL, "Failed to set file position", "Shit Ballz", 0);
return IC_FAIL_GEN;
}// END FUNCTION SetPos(const uint64 pos)
#endif// ifdef WIN32
| 26.972678
| 84
| 0.588533
|
binofet
|
341750081f42a0714498e4ee2a0c996609a8b1b4
| 634
|
cpp
|
C++
|
codes/raulcr-p2624-Accepted-s747689.cpp
|
raulcr98/coj-solutions
|
b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca
|
[
"MIT"
] | 1
|
2020-03-17T01:44:21.000Z
|
2020-03-17T01:44:21.000Z
|
codes/raulcr-p2624-Accepted-s747689.cpp
|
raulcr98/coj-solutions
|
b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca
|
[
"MIT"
] | null | null | null |
codes/raulcr-p2624-Accepted-s747689.cpp
|
raulcr98/coj-solutions
|
b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int N, M, T;
int main()
{
cin >> T;
while(T--){
cin >> N >> M;
vector<int> V;
int sum = 0;
for(int i = 1 ; i <= M ; i++){
int a;
cin >> a;
sum += a;
V.push_back(a);
}
sort(V.begin(), V.end());
int sol = 0, i = 0;
while(i < M && sol < N){
sol += V[i];
i++;
}
if(sum >= sol && sol > N)
cout << i - 1 << '\n';
else
cout << i << '\n';
}
return 0;
}
| 17.135135
| 39
| 0.29653
|
raulcr98
|
3419a5f363a8fffd9b1b22cdb8c06ef6890742f8
| 31,404
|
cc
|
C++
|
physicalrobots/player/server/drivers/mixed/botrics/obot.cc
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
physicalrobots/player/server/drivers/mixed/botrics/obot.cc
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
physicalrobots/player/server/drivers/mixed/botrics/obot.cc
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Player - One Hell of a Robot Server
* Copyright (C) 2000-2003
* Brian Gerkey
*
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*
* $Id: obot.cc 7278 2009-01-16 22:32:00Z thjc $
*
*
* Some of this code is borrowed and/or adapted from the 'cerebellum'
* module of CARMEN; thanks to the authors of that module.
*/
/** @ingroup drivers */
/** @{ */
/** @defgroup driver_obot obot
* @brief Botrics Obot mobile robot
The obot driver controls the Obot robot, made by Botrics. It's a
small, very fast robot that can carry a SICK laser (talk to the laser
over a normal serial port using the @ref driver_sicklms200 driver).
@par Compile-time dependencies
- none
@par Provides
- @ref interface_position2d
- @ref interface_power
@par Requires
- none
@par Supported commands
- PLAYER_POSITION2D_CMD_VEL
- PLAYER_POSITION2D_CMD_CAR
@par Supported configuration requests
- PLAYER_POSITION2D_REQ_GET_GEOM
- PLAYER_POSITION2D_REQ_SET_ODOM
- PLAYER_POSITION2D_REQ_RESET_ODOM
@par Configuration file options
- offset (length tuple)
- Default: [0.0 0.0 0.0]
- Offset of the robot's center of rotation
- size (length tuple)
- Default: [0.45 0.45]
- Bounding box (length, width) of the robot
- port (string)
- Default: "/dev/usb/ttyUSB1"
- Serial port used to communicate with the robot.
- max_speed (length, angle tuple)
- Default: [0.5 40.0]
- Maximum (translational, rotational) velocities
- max_accel (integer)
- Default: 5
- Maximum acceleration/deceleration (units?)
- motors_swapped (integer)
- Default: 0
- If non-zero, then assume that the motors and encoders connections
are swapped.
- car_angle_deadzone (angle)
- Default: 5.0 degrees
- Minimum angular error required to induce servoing when in car-like
command mode.
- car_angle_p (float)
- Default: 1.0
- Value to be multiplied by angular error (in rad) to produce angular
velocity command (in rad/sec) when in car-like command mode
- watchdog_timeout (float, seconds)
- Default: 1.0
- How long since receiving the last command before the robot is stopped,
for safety. Set to -1.0 for no watchdog (DANGEROUS!).
@par Example
@verbatim
driver
(
name "obot"
provides ["position2d:0"]
)
@endverbatim
@author Brian Gerkey
*/
/** @} */
#include "config.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <termios.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <replace/replace.h>
#include <libplayercore/playercore.h>
#include "obot_constants.h"
static void StopRobot(void* obotdev);
class Obot : public ThreadedDriver
{
private:
// this function will be run in a separate thread
virtual void Main();
// bookkeeping
bool fd_blocking;
double px, py, pa; // integrated odometric pose (m,m,rad)
int last_ltics, last_rtics;
bool odom_initialized;
player_devaddr_t position_addr;
player_devaddr_t power_addr;
double max_xspeed, max_yawspeed;
bool motors_swapped;
int max_accel;
// Minimum angular error required to induce servoing when in car-like
// command mode.
double car_angle_deadzone;
// Value to be multiplied by angular error (in rad) to produce angular
// velocity command (in rad/sec) when in car-like command mode
double car_angle_p;
// How long since receiving the last command before we stop the robot,
// for safety.
double watchdog_timeout;
// Robot geometry (size and rotational offset)
player_bbox3d_t robot_size;
player_pose3d_t robot_pose;
// methods for internal use
int WriteBuf(unsigned char* s, size_t len);
int ReadBuf(unsigned char* s, size_t len);
int BytesToInt32(unsigned char *ptr);
void Int32ToBytes(unsigned char* buf, int i);
int ValidateChecksum(unsigned char *ptr, size_t len);
int GetOdom(int *ltics, int *rtics, int *lvel, int *rvel);
void UpdateOdom(int ltics, int rtics);
unsigned char ComputeChecksum(unsigned char *ptr, size_t len);
int SendCommand(unsigned char cmd, int val1, int val2);
int ComputeTickDiff(int from, int to);
int ChangeMotorState(int state);
int OpenTerm();
int InitRobot();
int GetBatteryVoltage(int* voltage);
double angle_diff(double a, double b);
player_position2d_cmd_car_t last_car_cmd;
int last_final_lvel, last_final_rvel;
double last_cmd_time;
bool sent_new_command;
bool car_command_mode;
public:
int fd; // device file descriptor
const char* serial_port; // name of dev file
// public, so that it can be called from pthread cleanup function
int SetVelocity(int lvel, int rvel);
Obot(ConfigFile* cf, int section);
void ProcessCommand(player_position2d_cmd_vel_t * cmd);
void ProcessCarCommand(player_position2d_cmd_car_t * cmd);
// Process incoming messages from clients
int ProcessMessage(QueuePointer & resp_queue,
player_msghdr * hdr,
void * data);
virtual int MainSetup();
virtual void MainQuit();
};
// initialization function
Driver* Obot_Init( ConfigFile* cf, int section)
{
return((Driver*)(new Obot( cf, section)));
}
// a driver registration function
void
obot_Register(DriverTable* table)
{
table->AddDriver("obot", Obot_Init);
}
Obot::Obot( ConfigFile* cf, int section)
: ThreadedDriver(cf,section,true,PLAYER_MSGQUEUE_DEFAULT_MAXLEN)
{
memset(&this->position_addr,0,sizeof(player_devaddr_t));
memset(&this->power_addr,0,sizeof(player_devaddr_t));
// Do we create a robot position interface?
if(cf->ReadDeviceAddr(&(this->position_addr), section, "provides",
PLAYER_POSITION2D_CODE, -1, NULL) == 0)
{
if(this->AddInterface(this->position_addr) != 0)
{
this->SetError(-1);
return;
}
this->robot_size.sl = cf->ReadTupleLength(section, "size",
0, OBOT_LENGTH);
this->robot_size.sw = cf->ReadTupleLength(section, "size",
1, OBOT_WIDTH);
this->robot_pose.px = cf->ReadTupleLength(section, "offset",
0, OBOT_POSE_X);
this->robot_pose.py = cf->ReadTupleLength(section, "offset",
1, OBOT_POSE_Y);
this->robot_pose.pyaw = cf->ReadTupleAngle(section, "offset",
2, OBOT_POSE_A);
this->max_xspeed = cf->ReadTupleLength(section, "max_speed",
0, 0.5);
this->max_yawspeed = cf->ReadTupleAngle(section, "max_speed",
1, DTOR(40.0));
this->motors_swapped = cf->ReadInt(section, "motors_swapped", 0);
this->max_accel = cf->ReadInt(section, "max_accel", 5);
this->car_angle_deadzone = cf->ReadAngle(section, "car_angle_deadzone",
DTOR(5.0));
this->car_angle_p = cf->ReadFloat(section, "car_angle_p", 1.0);
this->watchdog_timeout = cf->ReadFloat(section, "watchdog_timeout", 1.0);
}
// Do we create a power interface?
if(cf->ReadDeviceAddr(&(this->power_addr), section, "provides",
PLAYER_POWER_CODE, -1, NULL) == 0)
{
if(this->AddInterface(this->power_addr) != 0)
{
this->SetError(-1);
return;
}
}
this->fd = -1;
this->serial_port = cf->ReadString(section, "port", OBOT_DEFAULT_PORT);
}
int
Obot::InitRobot()
{
// initialize the robot
unsigned char initstr[3];
initstr[0] = OBOT_INIT1;
initstr[1] = OBOT_INIT2;
initstr[2] = OBOT_INIT3;
unsigned char deinitstr[1];
deinitstr[0] = OBOT_DEINIT;
if(tcflush(this->fd, TCIOFLUSH) < 0 )
{
PLAYER_ERROR1("tcflush() failed: %s", strerror(errno));
close(this->fd);
this->fd = -1;
return(-1);
}
if(WriteBuf(initstr,sizeof(initstr)) < 0)
{
PLAYER_WARN("failed to initialize robot; i'll try to de-initializate it");
if(WriteBuf(deinitstr,sizeof(deinitstr)) < 0)
{
PLAYER_ERROR("failed on write of de-initialization string");
return(-1);
}
if(WriteBuf(initstr,sizeof(initstr)) < 0)
{
PLAYER_ERROR("failed on 2nd write of initialization string; giving up");
return(-1);
}
}
return(0);
}
int
Obot::OpenTerm()
{
struct termios term;
// open it. non-blocking at first, in case there's no robot
if((this->fd = open(serial_port, O_RDWR | O_SYNC | O_NONBLOCK, S_IRUSR | S_IWUSR )) < 0 )
{
PLAYER_ERROR1("open() failed: %s", strerror(errno));
return(-1);
}
if(tcgetattr(this->fd, &term) < 0 )
{
PLAYER_ERROR1("tcgetattr() failed: %s", strerror(errno));
close(this->fd);
this->fd = -1;
return(-1);
}
cfmakeraw(&term);
cfsetispeed(&term, B57600);
cfsetospeed(&term, B57600);
if(tcsetattr(this->fd, TCSAFLUSH, &term) < 0 )
{
PLAYER_ERROR1("tcsetattr() failed: %s", strerror(errno));
close(this->fd);
this->fd = -1;
return(-1);
}
fd_blocking = false;
return(0);
}
int
Obot::MainSetup()
{
int flags;
int ltics,rtics,lvel,rvel;
this->px = this->py = this->pa = 0.0;
this->odom_initialized = false;
this->last_final_rvel = this->last_final_lvel = 0;
this->last_cmd_time = -1.0;
this->sent_new_command = false;
this->car_command_mode = false;
printf("Botrics Obot connection initializing (%s)...", serial_port);
fflush(stdout);
if(OpenTerm() < 0)
{
PLAYER_ERROR("failed to initialize robot");
return(-1);
}
if(InitRobot() < 0)
{
PLAYER_ERROR("failed to initialize robot");
close(this->fd);
this->fd = -1;
return(-1);
}
/* try to get current odometry, just to make sure we actually have a robot */
if(GetOdom(<ics,&rtics,&lvel,&rvel) < 0)
{
PLAYER_ERROR("failed to get odometry");
close(this->fd);
this->fd = -1;
return(-1);
}
UpdateOdom(ltics,rtics);
/* ok, we got data, so now set NONBLOCK, and continue */
if((flags = fcntl(this->fd, F_GETFL)) < 0)
{
PLAYER_ERROR1("fcntl() failed: %s", strerror(errno));
close(this->fd);
this->fd = -1;
return(-1);
}
if(fcntl(this->fd, F_SETFL, flags ^ O_NONBLOCK) < 0)
{
PLAYER_ERROR1("fcntl() failed: %s", strerror(errno));
close(this->fd);
this->fd = -1;
return(-1);
}
fd_blocking = true;
puts("Done.");
// TODO: what are reasoanable numbers here?
if(SendCommand(OBOT_SET_ACCELERATIONS,this->max_accel,this->max_accel) < 0)
{
PLAYER_ERROR("failed to set accelerations on setup");
close(this->fd);
this->fd = -1;
return(-1);
}
return(0);
}
void
Obot::MainQuit()
{
unsigned char deinitstr[1];
usleep(OBOT_DELAY_US);
deinitstr[0] = OBOT_DEINIT;
if(WriteBuf(deinitstr,sizeof(deinitstr)) < 0)
PLAYER_ERROR("failed to deinitialize connection to robot");
if(close(this->fd))
PLAYER_ERROR1("close() failed:%s",strerror(errno));
this->fd = -1;
puts("Botrics Obot has been shutdown");
}
void
Obot::Main()
{
player_position2d_data_t data;
player_power_data_t charge_data;
double lvel_mps, rvel_mps;
int lvel, rvel;
int ltics, rtics;
double last_publish_time = 0.0;
double t;
bool stopped=false;
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL);
// push a pthread cleanup function that stops the robot
pthread_cleanup_push(StopRobot,this);
for(;;)
{
pthread_testcancel();
this->sent_new_command = false;
ProcessMessages();
if(!this->sent_new_command)
{
// Have we received a command lately?
GlobalTime->GetTimeDouble(&t);
if((this->last_cmd_time > 0.0) && (this->watchdog_timeout > 0.0) &&
((t - this->last_cmd_time) >= this->watchdog_timeout))
{
if(!stopped)
{
PLAYER_WARN("Watchdog timer stopping robot");
stopped = true;
}
if(this->SetVelocity(0,0) < 0)
PLAYER_ERROR("failed to set velocity");
}
else
{
stopped = false;
// Which mode are we in?
if(this->car_command_mode)
{
// Car-like command mode. Re-compute angular vel based on target
// heading
this->ProcessCarCommand(&this->last_car_cmd);
}
else
{
// Direct velocity command mode. Re-send last set of velocities.
if(this->SetVelocity(this->last_final_lvel, this->last_final_rvel) < 0)
PLAYER_ERROR("failed to set velocity");
}
}
}
// Update and publish odometry info
if(this->GetOdom(<ics,&rtics,&lvel,&rvel) < 0)
{
PLAYER_ERROR("failed to get odometry");
//pthread_exit(NULL);
}
else
this->UpdateOdom(ltics,rtics);
// Update and publish power info
int volt;
if(GetBatteryVoltage(&volt) < 0)
PLAYER_WARN("failed to get voltage");
GlobalTime->GetTimeDouble(&t);
if((t - last_publish_time) > OBOT_PUBLISH_INTERVAL)
{
data.pos.px = this->px;
data.pos.py = this->py;
data.pos.pa = this->pa;
data.vel.py = 0;
lvel_mps = lvel * OBOT_MPS_PER_TICK;
rvel_mps = rvel * OBOT_MPS_PER_TICK;
data.vel.px = (lvel_mps + rvel_mps) / 2.0;
data.vel.pa = (rvel_mps-lvel_mps) / OBOT_AXLE_LENGTH;
data.stall = 0;
//printf("publishing: %.3f %.3f %.3f\n",
//data.pos.px,
//data.pos.py,
//RTOD(data.pos.pa));
this->Publish(this->position_addr,
PLAYER_MSGTYPE_DATA, PLAYER_POSITION2D_DATA_STATE,
(void*)&data,sizeof(data),NULL);
charge_data.valid = PLAYER_POWER_MASK_VOLTS | PLAYER_POWER_MASK_PERCENT;
charge_data.volts = ((float)volt) / 1e1;
charge_data.percent = 1e2 * (charge_data.volts /
OBOT_NOMINAL_VOLTAGE);
this->Publish(this->power_addr,
PLAYER_MSGTYPE_DATA,
PLAYER_POWER_DATA_STATE,
(void*)&charge_data, sizeof(player_power_data_t), NULL);
last_publish_time = t;
}
//usleep(OBOT_DELAY_US);
}
pthread_cleanup_pop(0);
}
// Process car-like command, which sets an angular position target and
// translational velocity target. The basic idea is to compute angular
// velocity so as to servo (with P-control) to target angle. Then pass the
// two velocities to ProcessCommand() for thresholding and unit conversion.
void
Obot::ProcessCarCommand(player_position2d_cmd_car_t * cmd)
{
// Cache this command for later reuse
this->last_car_cmd = *cmd;
// Build up a cmd_vel structure to pass to ProcessCommand()
player_position2d_cmd_vel_t vel_cmd;
memset(&vel_cmd,0,sizeof(vel_cmd));
// Pass through trans vel unmodified
vel_cmd.vel.px = cmd->velocity;
// Compute rot vel
double da = this->angle_diff(cmd->angle, this->pa);
if(fabs(da) < DTOR(this->car_angle_deadzone))
vel_cmd.vel.pa = 0.0;
else
vel_cmd.vel.pa = this->car_angle_p * da;
this->ProcessCommand(&vel_cmd);
}
void
Obot::ProcessCommand(player_position2d_cmd_vel_t * cmd)
{
double rotational_term, command_lvel, command_rvel;
int final_lvel, final_rvel;
double xspeed, yawspeed;
xspeed = cmd->vel.px;
yawspeed = cmd->vel.pa;
// Clamp velocities according to given maxima
// TODO: test this to see if it does the right thing. We could clamp
// individual wheel velocities instead.
if(fabs(xspeed) > this->max_xspeed)
{
if(xspeed > 0)
xspeed = this->max_xspeed;
else
xspeed = -this->max_xspeed;
}
if(fabs(yawspeed) > this->max_yawspeed)
{
if(yawspeed > 0)
yawspeed = this->max_yawspeed;
else
yawspeed = -this->max_yawspeed;
}
// convert (tv,rv) to (lv,rv) and send to robot
rotational_term = yawspeed * OBOT_AXLE_LENGTH / 2.0;
command_rvel = xspeed + rotational_term;
command_lvel = xspeed - rotational_term;
// sanity check on per-wheel speeds
if(fabs(command_lvel) > OBOT_MAX_WHEELSPEED)
{
if(command_lvel > 0)
{
command_lvel = OBOT_MAX_WHEELSPEED;
command_rvel *= OBOT_MAX_WHEELSPEED/command_lvel;
}
else
{
command_lvel = - OBOT_MAX_WHEELSPEED;
command_rvel *= -OBOT_MAX_WHEELSPEED/command_lvel;
}
}
if(fabs(command_rvel) > OBOT_MAX_WHEELSPEED)
{
if(command_rvel > 0)
{
command_rvel = OBOT_MAX_WHEELSPEED;
command_lvel *= OBOT_MAX_WHEELSPEED/command_rvel;
}
else
{
command_rvel = - OBOT_MAX_WHEELSPEED;
command_lvel *= -OBOT_MAX_WHEELSPEED/command_rvel;
}
}
final_lvel = (int)rint(command_lvel / OBOT_MPS_PER_TICK);
final_rvel = (int)rint(command_rvel / OBOT_MPS_PER_TICK);
// TODO: do this min threshold smarter, to preserve desired travel
// direction
/* to account for our bad low-level PID motor controller */
if(abs(final_rvel) > 0 && abs(final_rvel) < OBOT_MIN_WHEELSPEED_TICKS)
{
if(final_rvel > 0)
final_rvel = OBOT_MIN_WHEELSPEED_TICKS;
else
final_rvel = -OBOT_MIN_WHEELSPEED_TICKS;
}
if(abs(final_lvel) > 0 && abs(final_lvel) < OBOT_MIN_WHEELSPEED_TICKS)
{
if(final_lvel > 0)
final_lvel = OBOT_MIN_WHEELSPEED_TICKS;
else
final_lvel = -OBOT_MIN_WHEELSPEED_TICKS;
}
// Record that we got a command at this time
GlobalTime->GetTimeDouble(&(this->last_cmd_time));
if((final_lvel != last_final_lvel) ||
(final_rvel != last_final_rvel))
{
if(SetVelocity(final_lvel,final_rvel) < 0)
{
PLAYER_ERROR("failed to set velocity");
pthread_exit(NULL);
}
last_final_lvel = final_lvel;
last_final_rvel = final_rvel;
}
}
////////////////////////////////////////////////////////////////////////////////
// Process an incoming message
int Obot::ProcessMessage(QueuePointer & resp_queue,
player_msghdr * hdr,
void * data)
{
if(Message::MatchMessage(hdr, PLAYER_MSGTYPE_CMD,
PLAYER_POSITION2D_CMD_VEL,
this->position_addr))
{
// Only take the first new command (should probably take the last,
// but...)
if(!this->sent_new_command)
{
assert(hdr->size == sizeof(player_position2d_cmd_vel_t));
this->ProcessCommand((player_position2d_cmd_vel_t*)data);
this->sent_new_command = true;
this->car_command_mode = false;
}
return(0);
}
else if(Message::MatchMessage(hdr, PLAYER_MSGTYPE_CMD,
PLAYER_POSITION2D_CMD_CAR,
this->position_addr))
{
// Only take the first new command (should probably take the last,
// but...)
if(!this->sent_new_command)
{
assert(hdr->size == sizeof(player_position2d_cmd_vel_t));
this->ProcessCarCommand((player_position2d_cmd_car_t*)data);
this->sent_new_command = true;
this->car_command_mode = true;
}
return(0);
}
else if(Message::MatchMessage(hdr, PLAYER_MSGTYPE_REQ,
PLAYER_POSITION2D_REQ_GET_GEOM,
this->position_addr))
{
player_position2d_geom_t geom;
geom.pose = this->robot_pose;
geom.size = this->robot_size;
this->Publish(this->position_addr, resp_queue,
PLAYER_MSGTYPE_RESP_ACK,
PLAYER_POSITION2D_REQ_GET_GEOM,
(void*)&geom, sizeof(geom), NULL);
return(0);
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,
PLAYER_POSITION2D_REQ_MOTOR_POWER,
this->position_addr))
{
/* motor state change request
* 1 = enable motors
* 0 = disable motors (default)
*/
if(hdr->size != sizeof(player_position2d_power_config_t))
{
PLAYER_WARN("Arg to motor state change request wrong size; ignoring");
return(-1);
}
player_position2d_power_config_t* power_config =
(player_position2d_power_config_t*)data;
this->ChangeMotorState(power_config->state);
this->Publish(this->position_addr, resp_queue,
PLAYER_MSGTYPE_RESP_ACK,
PLAYER_POSITION2D_REQ_MOTOR_POWER);
return(0);
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,
PLAYER_POSITION2D_REQ_SET_ODOM,
this->position_addr))
{
if(hdr->size != sizeof(player_position2d_set_odom_req_t))
{
PLAYER_WARN("Arg to odometry set requests wrong size; ignoring");
return(-1);
}
player_position2d_set_odom_req_t* set_odom_req =
(player_position2d_set_odom_req_t*)data;
// Just overwrite our current odometric pose.
this->px = set_odom_req->pose.px;
this->py = set_odom_req->pose.py;
this->pa = set_odom_req->pose.pa;
this->Publish(this->position_addr, resp_queue,
PLAYER_MSGTYPE_RESP_ACK, PLAYER_POSITION2D_REQ_SET_ODOM);
return(0);
}
else if(Message::MatchMessage(hdr,PLAYER_MSGTYPE_REQ,
PLAYER_POSITION2D_REQ_RESET_ODOM,
this->position_addr))
{
// Just overwrite our current odometric pose.
this->px = 0.0;
this->py = 0.0;
this->pa = 0.0;
this->Publish(this->position_addr, resp_queue,
PLAYER_MSGTYPE_RESP_ACK, PLAYER_POSITION2D_REQ_RESET_ODOM);
return(0);
}
else
return -1;
}
int
Obot::ReadBuf(unsigned char* s, size_t len)
{
int thisnumread;
size_t numread = 0;
int loop;
int maxloops=10;
loop=0;
while(numread < len)
{
//printf("loop %d of %d\n", loop,maxloops);
// apparently the underlying PIC gets overwhelmed if we read too fast
// wait...how can that be?
if((thisnumread = read(this->fd,s+numread,len-numread)) < 0)
{
if(!this->fd_blocking && errno == EAGAIN && ++loop < maxloops)
{
usleep(OBOT_DELAY_US);
continue;
}
PLAYER_ERROR1("read() failed: %s", strerror(errno));
return(-1);
}
if(thisnumread == 0)
PLAYER_WARN("short read");
numread += thisnumread;
}
/*
printf("read: ");
for(size_t i=0;i<numread;i++)
printf("%d ", s[i]);
puts("");
*/
return(0);
}
int
Obot::WriteBuf(unsigned char* s, size_t len)
{
size_t numwritten;
int thisnumwritten;
unsigned char ack[1];
/*
static double last = 0.0;
double t;
GlobalTime->GetTimeDouble(&t);
printf("WriteBuf: %d bytes (time since last: %f)\n",
len, t-last);
last=t;
*/
for(;;)
{
numwritten=0;
while(numwritten < len)
{
if((thisnumwritten = write(this->fd,s+numwritten,len-numwritten)) < 0)
{
if(!this->fd_blocking && errno == EAGAIN)
{
usleep(OBOT_DELAY_US);
continue;
}
PLAYER_ERROR1("write() failed: %s", strerror(errno));
return(-1);
}
numwritten += thisnumwritten;
}
// get acknowledgement
if(ReadBuf(ack,1) < 0)
{
PLAYER_ERROR("failed to get acknowledgement");
return(-1);
}
// TODO: re-init robot on NACK, to deal with underlying cerebellum reset
// problem
switch(ack[0])
{
case OBOT_ACK:
usleep(OBOT_DELAY_US);
return(0);
case OBOT_NACK:
PLAYER_WARN("got NACK; reinitializing connection");
usleep(OBOT_DELAY_US);
if(close(this->fd) < 0)
PLAYER_WARN1("close failed: %s", strerror(errno));
if(OpenTerm() < 0)
{
PLAYER_ERROR("failed to re-open connection");
return(-1);
}
if(InitRobot() < 0)
{
PLAYER_ERROR("failed to reinitialize");
return(-1);
}
else
{
usleep(OBOT_DELAY_US);
return(0);
}
break;
default:
PLAYER_WARN1("got unknown value for acknowledgement: %d",ack[0]);
usleep(OBOT_DELAY_US);
return(-1);
}
}
}
int
Obot::BytesToInt32(unsigned char *ptr)
{
unsigned char char0,char1,char2,char3;
int data = 0;
char0 = ptr[0];
char1 = ptr[1];
char2 = ptr[2];
char3 = ptr[3];
data |= ((int)char0) & 0x000000FF;
data |= (((int)char1) << 8) & 0x0000FF00;
data |= (((int)char2) << 16) & 0x00FF0000;
data |= (((int)char3) << 24) & 0xFF000000;
return data;
}
int
Obot::GetBatteryVoltage(int* voltage)
{
unsigned char buf[5];
buf[0] = OBOT_GET_VOLTAGE;
if(WriteBuf(buf,1) < 0)
{
PLAYER_ERROR("failed to send battery voltage command");
return(-1);
}
if(ReadBuf(buf,5) < 0)
{
PLAYER_ERROR("failed to read battery voltage");
return(-1);
}
if(ValidateChecksum(buf,5) < 0)
{
PLAYER_ERROR("checksum failed on battery voltage");
return(-1);
}
*voltage = BytesToInt32(buf);
return(0);
}
void
Obot::Int32ToBytes(unsigned char* buf, int i)
{
buf[0] = (i >> 0) & 0xFF;
buf[1] = (i >> 8) & 0xFF;
buf[2] = (i >> 16) & 0xFF;
buf[3] = (i >> 24) & 0xFF;
}
int
Obot::GetOdom(int *ltics, int *rtics, int *lvel, int *rvel)
{
unsigned char buf[20];
int index;
buf[0] = OBOT_GET_ODOM;
if(WriteBuf(buf,1) < 0)
{
PLAYER_ERROR("failed to send command to retrieve odometry");
return(-1);
}
//usleep(OBOT_DELAY_US);
// read 4 int32's, 1 error byte, and 1 checksum
if(ReadBuf(buf, 18) < 0)
{
PLAYER_ERROR("failed to read odometry");
return(-1);
}
if(ValidateChecksum(buf, 18) < 0)
{
PLAYER_ERROR("checksum failed on odometry packet");
return(-1);
}
if(buf[16] == 1)
{
PLAYER_ERROR("Cerebellum error with encoder board");
return(-1);
}
index = 0;
*ltics = BytesToInt32(buf+index);
index += 4;
*rtics = BytesToInt32(buf+index);
index += 4;
*rvel = BytesToInt32(buf+index);
index += 4;
*lvel = BytesToInt32(buf+index);
//printf("ltics: %d rtics: %d\n", *ltics, *rtics);
//puts("got good odom packet");
return(0);
}
int
Obot::ComputeTickDiff(int from, int to)
{
int diff1, diff2;
// find difference in two directions and pick shortest
if(to > from)
{
diff1 = to - from;
diff2 = (-OBOT_MAX_TICS - from) + (to - OBOT_MAX_TICS);
}
else
{
diff1 = to - from;
diff2 = (from - OBOT_MAX_TICS) + (-OBOT_MAX_TICS - to);
}
if(abs(diff1) < abs(diff2))
return(diff1);
else
return(diff2);
}
void
Obot::UpdateOdom(int ltics, int rtics)
{
int ltics_delta, rtics_delta;
double l_delta, r_delta, a_delta, d_delta;
int max_tics;
static struct timeval lasttime;
struct timeval currtime;
double timediff;
if(this->motors_swapped)
{
int tmp = ltics;
ltics = rtics;
rtics = tmp;
}
if(!this->odom_initialized)
{
this->last_ltics = ltics;
this->last_rtics = rtics;
gettimeofday(&lasttime,NULL);
this->odom_initialized = true;
return;
}
// MAJOR HACK!
// The problem comes from one or the other encoder returning 0 ticks (always
// the left, I think), we'll just throw out those readings. Shouldn't have
// too much impact.
if(!ltics || !rtics)
{
PLAYER_WARN("Invalid odometry reading (zeros); ignoring");
return;
}
//ltics_delta = ComputeTickDiff(last_ltics,ltics);
//rtics_delta = ComputeTickDiff(last_rtics,rtics);
ltics_delta = ltics - this->last_ltics;
rtics_delta = rtics - this->last_rtics;
// mysterious rollover code borrowed from CARMEN
/*
if(ltics_delta > SHRT_MAX/2)
ltics_delta += SHRT_MIN;
if(ltics_delta < -SHRT_MIN/2)
ltics_delta -= SHRT_MIN;
if(rtics_delta > SHRT_MAX/2)
rtics_delta += SHRT_MIN;
if(rtics_delta < -SHRT_MIN/2)
rtics_delta -= SHRT_MIN;
*/
gettimeofday(&currtime,NULL);
timediff = (currtime.tv_sec + currtime.tv_usec/1e6)-
(lasttime.tv_sec + lasttime.tv_usec/1e6);
max_tics = (int)rint(OBOT_MAX_WHEELSPEED / OBOT_M_PER_TICK / timediff);
lasttime = currtime;
//printf("ltics: %d\trtics: %d\n", ltics,rtics);
//printf("ldelt: %d\trdelt: %d\n", ltics_delta, rtics_delta);
//printf("maxtics: %d\n", max_tics);
if(abs(ltics_delta) > max_tics || abs(rtics_delta) > max_tics)
{
PLAYER_WARN("Invalid odometry change (too big); ignoring");
return;
}
l_delta = ltics_delta * OBOT_M_PER_TICK;
r_delta = rtics_delta * OBOT_M_PER_TICK;
//printf("Left speed: %f\n", l_delta / timediff);
//printf("Right speed: %f\n", r_delta / timediff);
a_delta = (r_delta - l_delta) / OBOT_AXLE_LENGTH;
d_delta = (l_delta + r_delta) / 2.0;
this->px += d_delta * cos(this->pa);
this->py += d_delta * sin(this->pa);
this->pa += a_delta;
this->pa = NORMALIZE(this->pa);
//printf("obot: pose: %f,%f,%f\n", this->px,this->py, RTOD(this->pa));
this->last_ltics = ltics;
this->last_rtics = rtics;
}
// Validate XOR checksum
int
Obot::ValidateChecksum(unsigned char *ptr, size_t len)
{
size_t i;
unsigned char checksum = 0;
for(i = 0; i < len-1; i++)
checksum ^= ptr[i];
if(checksum == ptr[len-1])
return(0);
else
return(-1);
}
// Compute XOR checksum
unsigned char
Obot::ComputeChecksum(unsigned char *ptr, size_t len)
{
size_t i;
unsigned char chksum = 0;
for(i = 0; i < len; i++)
chksum ^= ptr[i];
return(chksum);
}
int
Obot::SendCommand(unsigned char cmd, int val1, int val2)
{
unsigned char buf[10];
int i;
//printf("SendCommand: %d %d %d\n", cmd, val1, val2);
i=0;
buf[i] = cmd;
i+=1;
Int32ToBytes(buf+i,val1);
i+=4;
Int32ToBytes(buf+i,val2);
i+=4;
buf[i] = ComputeChecksum(buf,i);
if(WriteBuf(buf,10) < 0)
{
PLAYER_ERROR("failed to send command");
return(-1);
}
return(0);
}
int
Obot::SetVelocity(int lvel, int rvel)
{
int retval;
//printf("SetVelocity: %d %d\n", lvel, rvel);
if(!this->motors_swapped)
retval = SendCommand(OBOT_SET_VELOCITIES,lvel,rvel);
else
retval = SendCommand(OBOT_SET_VELOCITIES,rvel,lvel);
if(retval < 0)
{
PLAYER_ERROR("failed to set velocities");
return(-1);
}
return(0);
}
int
Obot::ChangeMotorState(int state)
{
unsigned char buf[1];
if(state)
buf[0] = OBOT_ENABLE_VEL_CONTROL;
else
buf[0] = OBOT_DISABLE_VEL_CONTROL;
return(WriteBuf(buf,sizeof(buf)));
}
static void
StopRobot(void* obotdev)
{
Obot* td = (Obot*)obotdev;
tcflush(td->fd,TCIOFLUSH);
if(td->SetVelocity(0,0) < 0)
PLAYER_ERROR("failed to stop robot on thread exit");
}
// computes the signed minimum difference between the two angles.
double
Obot::angle_diff(double a, double b)
{
double d1, d2;
a = NORMALIZE(a);
b = NORMALIZE(b);
d1 = a-b;
d2 = 2*M_PI - fabs(d1);
if(d1 > 0)
d2 *= -1.0;
if(fabs(d1) < fabs(d2))
return(d1);
else
return(d2);
}
| 25.42834
| 91
| 0.629156
|
parasol-ppl
|
341f5f51dd2e5f71923d964fb9924d9f9a11bc08
| 18,473
|
cpp
|
C++
|
src/BCRext/BwtIndex.cpp
|
ndaniel/BEETL
|
4f35e2f6a18be624c1159f3ffe042eb8490f94bf
|
[
"BSD-2-Clause"
] | 53
|
2015-02-05T02:26:15.000Z
|
2022-01-13T05:37:06.000Z
|
src/BCRext/BwtIndex.cpp
|
ndaniel/BEETL
|
4f35e2f6a18be624c1159f3ffe042eb8490f94bf
|
[
"BSD-2-Clause"
] | 9
|
2015-09-03T23:42:14.000Z
|
2021-10-15T15:25:49.000Z
|
src/BCRext/BwtIndex.cpp
|
ndaniel/BEETL
|
4f35e2f6a18be624c1159f3ffe042eb8490f94bf
|
[
"BSD-2-Clause"
] | 23
|
2015-01-08T13:43:07.000Z
|
2021-05-19T17:35:42.000Z
|
/**
** Copyright (c) 2011-2014 Illumina, Inc.
**
** This file is part of the BEETL software package,
** covered by the "BSD 2-Clause License" (see accompanying LICENSE file)
**
** Citation: Markus J. Bauer, Anthony J. Cox and Giovanna Rosone
** Lightweight BWT Construction for Very Large String Collections.
** Proceedings of CPM 2011, pp.219-231
**
**/
#include "BwtIndex.hh"
#include "BwtReader.hh"
#include "libzoo/util/Logger.hh"
#include <algorithm>
#include <unistd.h>
#include <sys/types.h>
#ifndef DONT_USE_MMAP
# include <fcntl.h>
# include <sys/mman.h>
# include <sys/stat.h>
# include <sys/types.h>
#endif
using namespace std;
template< class T >
BwtReaderIndex<T>::BwtReaderIndex( const string &filename, const string &optionalSharedMemoryPath ):
T( filename ),
indexFilename_( filename + ".idx" ),
// isNextIndex_( false ),
pIndexFile_( NULL )
{
// current_.clear();
initIndex( optionalSharedMemoryPath );
}
template< class T >
void BwtReaderIndex<T>::rewindFile( void )
{
// rewind file and set all vars as per constructor
// current_.clear();
indexNext_ = 0;
// initIndex();
T::rewindFile();
} // ~rewindFile
template< class T >
LetterNumber BwtReaderIndex<T>::readAndCount( LetterCount &c, const LetterNumber numChars )
{
#ifdef DEBUG_RAC
std::cout << "BR RLI readAndCount " << numChars << " chars " << endl;
std::cout << "Before: " << currentPos_ << " " << ftell( T::pFile_ ) << " ";
std::cout << c << endl;;
#endif
LetterNumber charsLeft( numChars );
uint32_t indexLast;
#ifdef DEBUG_RAC
if ( indexNext_ != indexSize_ )
assert( currentPos_ <= indexPosBwt_[indexNext_] );
#endif
// gotcha: numChars can be set to maxLetterNumber so no expressions should
// add to it - wraparound issues!
// if indexLast==indexPosBwtSize we know we have gone past last index point
// or that none are present at all
if ( ( indexNext_ != indexSize_ )
&& ( numChars > ( indexPosBwt_[indexNext_] - T::currentPos_ ) ) )
{
// count interval spans at least one index point
// how many index points does the count interval span?
indexLast = indexNext_;
while ( ( indexLast != indexSize_ )
&& ( numChars > ( indexPosBwt_[indexLast] - T::currentPos_ ) ) )
{
indexLast++;
}
indexLast--;
if ( indexNext_ <= indexLast )
{
// more than one index point in count interval - can use index
if ( ! ( T::currentPos_ == 0 && charsLeft >= indexPosBwt_[indexNext_] ) )
charsLeft -= T::readAndCount( c, indexPosBwt_[indexNext_] - T::currentPos_ );
else
{
charsLeft -= indexPosBwt_[0];
c += indexCount_[0];
if ( indexNext_ == indexLast )
T::seek( indexPosFile_[0], indexPosBwt_[0] );
}
// assert(T::currentPos_==indexNext_);
if ( indexNext_ != indexLast )
{
charsLeft -= ( indexPosBwt_[indexLast] - indexPosBwt_[indexNext_] );
// update counts and also indexNext_
while ( ++indexNext_ <= indexLast )
{
c += indexCount_[indexNext_];
#ifdef DEBUG_RAC_VERBOSE
std::cout << indexNext_ << " " << indexPosBwt_[indexNext_] << " " << indexPosFile_[indexNext_] << " " << indexCount_[indexNext_] << endl;
#endif
} //
// skip to last index point and reset buffers
T::seek( indexPosFile_[indexLast], indexPosBwt_[indexLast] );
}
else
{
assert( T::currentPos_ == indexPosBwt_[indexLast] );
++indexNext_;
}
/*
T::runLength_ = 0;
T::pBuf_ = T::buf_ + ReadBufferSize;
T::pBufMax_ = T::buf_ + ReadBufferSize;
*/
} // if more than one index point
// if we're in this clause we've gone past at least one index
indexLast++;
assert( indexLast <= indexSize_ );
}
#ifdef DEBUG_RAC
std::cout << "After (RLI) skip: " << T::currentPos_ << " " << ftell( T::pFile_ ) << " " << c << endl;
#endif
// now read as normal until done
charsLeft -= T::readAndCount( c, charsLeft );
// assert(T::currentPos_==desiredPos);
#ifdef DEBUG_RAC
std::cout << "After (RLI) final read: " << T::currentPos_ << " " << ftell( T::pFile_ ) << " " << c << endl;
#endif
return ( numChars - charsLeft );
}
template< class T >
void BwtReaderIndex<T>::initIndex( const string &optionalSharedMemoryPath )
{
indexNext_ = 0;
bool useSharedMemory = !optionalSharedMemoryPath.empty();
string shmFilename1, shmFilename2, shmFilename3;
if ( useSharedMemory )
{
string filenameWithoutSlash = T::filename_;
std::replace( filenameWithoutSlash.begin(), filenameWithoutSlash.end(), '/', '_' );
shmFilename1 = optionalSharedMemoryPath + "/BeetlIndexPosFile_" + filenameWithoutSlash;
shmFilename2 = optionalSharedMemoryPath + "/BeetlIndexCount_" + filenameWithoutSlash;
shmFilename3 = optionalSharedMemoryPath + "/BeetlIndexPosBwt_" + filenameWithoutSlash;
if ( readWriteCheck( shmFilename1.c_str(), false, false ) )
{
// Load vectors from shared memory
{
cerr << "Info: Using mmap'ed index " << shmFilename1 << endl;
int fd = open( shmFilename1.c_str(), O_RDONLY );
assert( fd >= 0 );
off_t fileSize = lseek( fd, 0, SEEK_END );
lseek( fd, 0, SEEK_SET );
char *mmappedFile = ( char * )mmap( NULL, fileSize, PROT_READ, MAP_SHARED /*| MAP_LOCKED | MAP_POPULATE*/, fd, 0 );
if ( mmappedFile == ( void * ) - 1 )
{
perror( "Error: Map failed" );
assert( false );
}
indexSize_ = *reinterpret_cast<uint32_t *>( mmappedFile );
indexPosFile_ = reinterpret_cast<LetterNumber *>( mmappedFile + sizeof( indexSize_ ) );
close( fd );
}
{
int fd = open( shmFilename2.c_str(), O_RDONLY );
assert( fd >= 0 );
off_t fileSize = lseek( fd, 0, SEEK_END );
lseek( fd, 0, SEEK_SET );
char *mmappedFile = ( char * )mmap( NULL, fileSize, PROT_READ, MAP_SHARED /*| MAP_LOCKED | MAP_POPULATE*/, fd, 0 );
if ( mmappedFile == ( void * ) - 1 )
{
perror( "Error: Map failed" );
assert( false );
}
assert( indexSize_ == *reinterpret_cast<uint32_t *>( mmappedFile ) );
indexCount_ = reinterpret_cast<LETTER_COUNT_CLASS *>( mmappedFile + sizeof( indexSize_ ) );
close( fd );
}
{
int fd = open( shmFilename3.c_str(), O_RDONLY );
assert( fd >= 0 );
off_t fileSize = lseek( fd, 0, SEEK_END );
lseek( fd, 0, SEEK_SET );
char *mmappedFile = ( char * )mmap( NULL, fileSize, PROT_READ, MAP_SHARED /*| MAP_LOCKED | MAP_POPULATE*/, fd, 0 );
if ( mmappedFile == ( void * ) - 1 )
{
perror( "Error: Map failed" );
assert( false );
}
assert( indexSize_ == *reinterpret_cast<uint32_t *>( mmappedFile ) );
indexPosBwt_ = reinterpret_cast<LetterNumber *>( mmappedFile + sizeof( indexSize_ ) );
close( fd );
}
return;
}
}
LetterNumber currentPosBwt( 0 );
uint8_t unusedAlphabetEntries( 0 );
if ( pIndexFile_ != NULL ) fclose( pIndexFile_ );
pIndexFile_ = fopen( indexFilename_.c_str(), "r" );
if ( pIndexFile_ == NULL )
{
// Logger::error() << "Error opening index file " << indexFilename_;
// exit( -1 );
}
else
{
// read file header
bool isIndexV2 = false;
uint8_t sizeOfAlphabet = 0;
uint8_t sizeOfLetterNumber = 0;
uint16_t sizeOfLetterCountCompact = 0;
vector<char> buf( indexV1Header.size() );
fread( buf.data(), indexV1Header.size(), 1, pIndexFile_ );
if ( equal( buf.begin(), buf.end(), indexV1Header.begin() ) )
{
// index v1 detected
fread( &sizeOfAlphabet, sizeof( uint8_t ), 1, pIndexFile_ );
fread( &sizeOfLetterNumber, sizeof( uint8_t ), 1, pIndexFile_ );
fread( &sizeOfLetterCountCompact, sizeof( uint16_t ), 1, pIndexFile_ );
}
else if ( equal( buf.begin(), buf.end(), indexV2Header.begin() ) )
{
// index v2 detected
isIndexV2 = true;
fread( &sizeOfAlphabet, sizeof( uint8_t ), 1, pIndexFile_ );
fread( &sizeOfLetterNumber, sizeof( uint8_t ), 1, pIndexFile_ );
sizeOfLetterCountCompact = sizeof( LetterCountCompact ); // unused in index v2
}
else
{
// default value from previous header-less format
sizeOfAlphabet = 7;
sizeOfLetterNumber = 8;
sizeOfLetterCountCompact = 4*sizeOfAlphabet;
rewind( pIndexFile_ );
}
if ( sizeOfAlphabet > alphabetSize )
{
Logger::error() << "WARNING: Index file " << indexFilename_ << " was built with alphabetSize == " << (int)sizeOfAlphabet << " whereas the current tools are using alphabetSize == " << alphabetSize << ".\n => You should rebuild the index files with beetl-index (or rebuild the tools using the same data widths (specified in Types.hh))." << endl;
unusedAlphabetEntries = sizeOfAlphabet - alphabetSize;
}
else if ( sizeOfAlphabet < alphabetSize )
{
Logger::error() << "ERROR: Index file " << indexFilename_ << " was built with alphabetSize == " << (int)sizeOfAlphabet << " whereas the current tools are using alphabetSize == " << alphabetSize << ".\n => You should rebuild the index files with beetl-index (or rebuild the tools using the same data widths (specified in Types.hh))." << endl;
exit( -1 );
}
if ( sizeOfLetterNumber != sizeof( LetterNumber ) )
{
Logger::error() << "ERROR: Index file " << indexFilename_ << " was built with sizeof(LetterNumber) == " << (int)sizeOfLetterNumber << " whereas the current tools are using sizeof(LetterNumber) == " << sizeof( LetterNumber ) << ".\n => You should rebuild the index files with beetl-index (or rebuild the tools using the same data widths (specified in Types.hh))." << endl;
exit( -1 );
}
if ( sizeOfLetterCountCompact != sizeof( LetterCountCompact ) + 4 * unusedAlphabetEntries ) // allow 32 bits per unused entry to be automatically ignored
{
Logger::error() << "ERROR: Index file " << indexFilename_ << " was built with sizeof(LetterCountCompact) == " << sizeOfLetterCountCompact << " whereas the current tools are using sizeof(LetterCountCompact) == " << sizeof( LetterCountCompact ) << " + " << unusedAlphabetEntries << "unused alphabet entries.\n => You should rebuild the index files with beetl-index (or rebuild the tools using the same data widths (specified in Types.hh))." << endl;
exit( -1 );
}
indexPosFile0_.push_back( 0 );
while ( fread( &indexPosFile0_.back(), sizeof( LetterNumber ), 1, pIndexFile_ ) == 1 )
{
indexCount0_.push_back( LETTER_COUNT_CLASS() );
if (!isIndexV2)
{
// In Index v1, counts were always stored using compact 32 bits values, which now need to be scaled to LETTER_COUNT_CLASS
for (int i=0; i<alphabetSize; ++i)
{
assert ( fread( &indexCount0_.back().count_[i], sizeof( uint32_t ), 1, pIndexFile_ ) == 1 );
}
uint32_t unusedEntry;
for (int i=0; i<unusedAlphabetEntries; ++i)
{
assert ( fread( &unusedEntry, sizeof( uint32_t ), 1, pIndexFile_ ) == 1 );
}
}
else
{
for (int i=0; i<alphabetSize; ++i)
{
int byteCount;
assert ( fread( &byteCount, 1, 1, pIndexFile_ ) == 1 );
if (byteCount)
{
#ifdef USE_COMPACT_STRUCTURES
if ( byteCount > sizeof(LetterNumberCompact) )
{
Logger::error() << "ERROR: Index file " << indexFilename_ << " contains large values. BEETL needs to be built without USE_COMPACT_STRUCTURES in BwtIndex.hh." << endl;
exit( -1 );
}
#endif
assert ( fread( &indexCount0_.back().count_[i], byteCount, 1, pIndexFile_ ) == 1 );
}
}
}
for ( int i( 0 ); i < alphabetSize; i++ )
currentPosBwt += indexCount0_.back().count_[i];
indexPosBwt0_.push_back( currentPosBwt );
#ifdef DEBUG_RAC_VERBOSE
cout << indexPosBwt0_.back() << " " << indexPosFile0_.back() << " " << indexCount0_.back() << endl;
#endif
// skip unused alphabet entries, and check that they were indeed useless
for (int i=0; i<unusedAlphabetEntries; ++i)
{
uint32_t unusedEntry;
assert( fread( &unusedEntry, sizeof( uint32_t ), 1, pIndexFile_ ) == 1 );
assert( unusedEntry == 0 && "Error: Trying to ignore an index entry, which contains a non-zero value" );
}
indexPosFile0_.push_back( 0 );
} // ~while
indexPosFile0_.pop_back();
fclose( pIndexFile_ );
pIndexFile_ = NULL;
} // ~if
indexSize_ = indexPosBwt0_.size();
assert( indexSize_ == indexPosFile0_.size() );
assert( indexSize_ == indexCount0_.size() );
// rewindFile();
indexPosBwt_ = indexPosBwt0_.data();
indexPosFile_ = indexPosFile0_.data();
indexCount_ = indexCount0_.data();
// Save vectors to shared memory
if ( useSharedMemory && !indexPosBwt0_.empty() )
{
{
ofstream os( shmFilename1 );
if ( !os.good() )
{
cerr << "Error creating " << shmFilename1 << endl;
exit( -1 );
}
os.write( reinterpret_cast<const char *>( &indexSize_ ), sizeof( indexSize_ ) );
os.write( reinterpret_cast<const char *>( indexPosFile0_.data() ), indexSize_ * sizeof( indexPosFile0_[0] ) );
}
{
ofstream os( shmFilename2 );
os.write( reinterpret_cast<const char *>( &indexSize_ ), sizeof( indexSize_ ) );
os.write( reinterpret_cast<const char *>( indexCount0_.data() ), indexSize_ * sizeof( indexCount0_[0] ) );
}
{
ofstream os( shmFilename3 );
os.write( reinterpret_cast<const char *>( &indexSize_ ), sizeof( indexSize_ ) );
os.write( reinterpret_cast<const char *>( indexPosBwt0_.data() ), indexSize_ * sizeof( indexPosBwt0_[0] ) );
}
}
} // ~initIndex
// Index creation
void buildIndex( BwtReaderBase *reader0, FILE *pIndexFile, const int indexBinSize )
{
BwtReaderRunLengthBase *reader = dynamic_cast< BwtReaderRunLengthBase* >( reader0 );
const int runsPerChunk( indexBinSize );
int runsThisChunk( 0 );
LetterCount countsThisChunk;
LetterNumber runsSoFar( 0 ), chunksSoFar( 0 );
bool lastRun = false;
if (reader == NULL)
{
Logger::out() << "Warning: cannot index file " << reader0->filename_ << endl;
return;
}
reader->currentPos_ = 0;
// Write file header
assert( fwrite( indexV2Header.data(), indexV2Header.size(), 1, pIndexFile ) == 1 );
uint8_t sizeOfAlphabet = alphabetSize;
uint8_t sizeOfLetterNumber = sizeof( LetterNumber );
fwrite( &sizeOfAlphabet, sizeof( uint8_t ), 1, pIndexFile );
fwrite( &sizeOfLetterNumber, sizeof( uint8_t ), 1, pIndexFile );
while ( !lastRun )
{
lastRun = !reader->getRun();
if (!lastRun)
{
runsSoFar++;
runsThisChunk++;
countsThisChunk.count_[whichPile[reader->lastChar_]] += reader->runLength_;
assert( countsThisChunk.count_[whichPile[reader->lastChar_]] >= reader->runLength_ && "Error: Overflow in buildIndex" );
reader->currentPos_ += reader->runLength_;
}
if ( runsThisChunk == runsPerChunk || lastRun )
{
#ifdef DEBUG_RAC
cout << reader->currentPos_ << " " << runsSoFar << " " << countsThisChunk << endl;
#endif
// don't bother writing this as can deduce by summing countsThisChunk
// assert
// ( fwrite( &reader->currentPos_, sizeof( LetterNumber ), 1, pIndexFile ) == 1 );
LetterNumber posInFile = reader->tellg();
assert
( fwrite( &posInFile, sizeof( LetterNumber ), 1, pIndexFile ) == 1 );
// In index format v2, we write each LetterCount independently, encoding the number of bytes as first byte
for (int i=0; i<alphabetSize; ++i)
{
LetterNumber val = countsThisChunk.count_[i];
int bytesNeeded = 0;
while (val >> (8*bytesNeeded))
++bytesNeeded;
assert( fwrite( &bytesNeeded, 1, 1, pIndexFile ) == 1 );
if (bytesNeeded)
assert( fwrite( &val, bytesNeeded, 1, pIndexFile ) == 1 );
}
chunksSoFar++;
runsThisChunk = 0;
countsThisChunk.clear();
}
}
cout << "buildIndex: read " << reader->currentPos_ << " bases compressed into " << runsSoFar << " runs" << " over " << reader->tellg() << " bytes." << endl;
cout << "buildIndex: generated " << chunksSoFar << " index points." << endl;
} // ~buildIndex
// Explicit template instantiations
template class BwtReaderIndex<BwtReaderRunLength>;
template class BwtReaderIndex<BwtReaderRunLengthV3>;
| 40.158696
| 459
| 0.560494
|
ndaniel
|
3422fef3339e415cb49949b7f4aaa1d4da2b9efd
| 253
|
cpp
|
C++
|
Chapter7/Image/QtImageViewer/qtimageViewer.cpp
|
valeriyvan/LinuxProgrammingWithRaspberryPi
|
7c57afcf2cbfc8e0486c78aa75b361fd712a136f
|
[
"MIT"
] | 4
|
2020-03-11T13:38:25.000Z
|
2021-12-25T00:48:53.000Z
|
Chapter7/Image/QtImageViewer/qtimageViewer.cpp
|
valeriyvan/LinuxProgrammingWithRaspberryPi
|
7c57afcf2cbfc8e0486c78aa75b361fd712a136f
|
[
"MIT"
] | null | null | null |
Chapter7/Image/QtImageViewer/qtimageViewer.cpp
|
valeriyvan/LinuxProgrammingWithRaspberryPi
|
7c57afcf2cbfc8e0486c78aa75b361fd712a136f
|
[
"MIT"
] | 8
|
2020-07-10T22:02:05.000Z
|
2021-12-15T02:11:44.000Z
|
#include <QApplication>
#include <QLabel>
#include <QPixmap>
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QLabel* lb = new QLabel("", 0);
lb->setPixmap(QPixmap("mandrill.jpg"));
lb->show();
return app.exec();
}
| 16.866667
| 43
| 0.620553
|
valeriyvan
|
34279a67e3c5d16a5ea26423c28bc022e6bc97f0
| 2,575
|
cpp
|
C++
|
src/Timer.cpp
|
JuanDiegoMontoya/g
|
57a4f44ddea0299e6c6f056592e0b126a67ed8ec
|
[
"MIT"
] | 2
|
2022-02-04T10:14:49.000Z
|
2022-03-01T23:45:22.000Z
|
src/Timer.cpp
|
JuanDiegoMontoya/g
|
57a4f44ddea0299e6c6f056592e0b126a67ed8ec
|
[
"MIT"
] | null | null | null |
src/Timer.cpp
|
JuanDiegoMontoya/g
|
57a4f44ddea0299e6c6f056592e0b126a67ed8ec
|
[
"MIT"
] | null | null | null |
#include <fwog/Common.h>
#include <fwog/Timer.h>
#include <numeric>
namespace Fwog
{
TimerQuery::TimerQuery()
{
glGenQueries(2, queries);
glQueryCounter(queries[0], GL_TIMESTAMP);
}
TimerQuery::~TimerQuery()
{
glDeleteQueries(2, queries);
}
uint64_t TimerQuery::GetTimestamp()
{
int complete = 0;
glQueryCounter(queries[1], GL_TIMESTAMP);
while (!complete) glGetQueryObjectiv(queries[1], GL_QUERY_RESULT_AVAILABLE, &complete);
uint64_t startTime, endTime;
glGetQueryObjectui64v(queries[0], GL_QUERY_RESULT, &startTime);
glGetQueryObjectui64v(queries[1], GL_QUERY_RESULT, &endTime);
std::swap(queries[0], queries[1]);
return endTime - startTime;
}
TimerQueryAsync::TimerQueryAsync(uint32_t N)
: capacity_(N)
{
FWOG_ASSERT(capacity_ > 0);
queries = new uint32_t[capacity_ * 2];
glGenQueries(capacity_ * 2, queries);
}
TimerQueryAsync::~TimerQueryAsync()
{
glDeleteQueries(capacity_ * 2, queries);
delete[] queries;
}
void TimerQueryAsync::BeginZone()
{
// begin a query if there is at least one inactive
if (count_ < capacity_)
{
glQueryCounter(queries[start_], GL_TIMESTAMP);
}
}
void TimerQueryAsync::EndZone()
{
// end a query if there is at least one inactive
if (count_ < capacity_)
{
glQueryCounter(queries[start_ + capacity_], GL_TIMESTAMP);
start_ = (start_ + 1) % capacity_; // wrap
count_++;
}
}
std::optional<uint64_t> TimerQueryAsync::PopTimestamp()
{
// return nothing if there is no active query
if (count_ == 0)
{
return std::nullopt;
}
// get the index of the oldest query
uint32_t index = (start_ + capacity_ - count_) % capacity_;
// getting the start result is a sanity check
GLint startResultAvailable{};
GLint endResultAvailable{};
glGetQueryObjectiv(queries[index], GL_QUERY_RESULT_AVAILABLE, &startResultAvailable);
glGetQueryObjectiv(queries[index + capacity_], GL_QUERY_RESULT_AVAILABLE, &endResultAvailable);
// the oldest query's result is not available, abandon ship!
if (startResultAvailable == GL_FALSE || endResultAvailable == GL_FALSE)
{
return std::nullopt;
}
// pop oldest timing and retrieve result
count_--;
uint64_t startTimestamp{};
uint64_t endTimestamp{};
glGetQueryObjectui64v(queries[index], GL_QUERY_RESULT, &startTimestamp);
glGetQueryObjectui64v(queries[index + capacity_], GL_QUERY_RESULT, &endTimestamp);
return endTimestamp - startTimestamp;
}
}
| 27.105263
| 99
| 0.683495
|
JuanDiegoMontoya
|
342bcc038a2ca98c01e7e47922a5267283c40560
| 1,295
|
hpp
|
C++
|
Includes/Rosetta/PlayMode/Logs/PlayHistory.hpp
|
Hearthstonepp/Hearthstonepp
|
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
|
[
"MIT"
] | 62
|
2017-08-21T14:11:00.000Z
|
2018-04-23T16:09:02.000Z
|
Includes/Rosetta/PlayMode/Logs/PlayHistory.hpp
|
Hearthstonepp/Hearthstonepp
|
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
|
[
"MIT"
] | 37
|
2017-08-21T11:13:07.000Z
|
2018-04-30T08:58:41.000Z
|
Includes/Rosetta/PlayMode/Logs/PlayHistory.hpp
|
Hearthstonepp/Hearthstonepp
|
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
|
[
"MIT"
] | 10
|
2017-08-21T03:44:12.000Z
|
2018-01-10T22:29:10.000Z
|
// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#ifndef ROSETTASTONE_PLAYMODE_PLAY_HISTORY_HPP
#define ROSETTASTONE_PLAYMODE_PLAY_HISTORY_HPP
#include <Rosetta/PlayMode/Models/Playable.hpp>
namespace RosettaStone::PlayMode
{
//!
//! \brief PlayHistory struct.
//!
//! This struct holds all values for played card.
//!
struct PlayHistory
{
explicit PlayHistory(const Playable* source, const Playable* target,
int _turn, int _chooseOne)
{
sourcePlayer = source->player;
sourceCard = source->card;
sourceID = source->GetGameTag(GameTag::ENTITY_ID);
if (target)
{
targetPlayer = target->player;
targetCard = target->card;
}
turn = _turn;
chooseOne = _chooseOne;
}
Player* sourcePlayer = nullptr;
Player* targetPlayer = nullptr;
Card* sourceCard = nullptr;
Card* targetCard = nullptr;
int sourceID = -1;
int turn = -1;
int chooseOne = -1;
};
} // namespace RosettaStone::PlayMode
#endif // ROSETTASTONE_PLAYMODE_PLAY_HISTORY_HPP
| 26.979167
| 79
| 0.671815
|
Hearthstonepp
|
342bf1d0c337848387f546dbefaadabf6a466b8f
| 293
|
cpp
|
C++
|
BotPantela/Ball.cpp
|
djcvijic/BotPantela
|
174287e2b10cdd30d3217dd9c2ff766fcc93530d
|
[
"MIT"
] | null | null | null |
BotPantela/Ball.cpp
|
djcvijic/BotPantela
|
174287e2b10cdd30d3217dd9c2ff766fcc93530d
|
[
"MIT"
] | null | null | null |
BotPantela/Ball.cpp
|
djcvijic/BotPantela
|
174287e2b10cdd30d3217dd9c2ff766fcc93530d
|
[
"MIT"
] | null | null | null |
#include "Ball.h"
using namespace std;
void Ball::inputPos ()
{
double xPos;
double yPos;
cin >> xPos;
cin >> yPos;
setXPos(xPos);
setYPos(yPos);
}
void Ball::inputVel ()
{
double xVel;
double yVel;
cin >> xVel;
cin >> yVel;
setXVel(xVel);
setYVel(yVel);
}
| 12.73913
| 23
| 0.590444
|
djcvijic
|
342d610f2ded549890584ed91eed2c00fbd3e0dc
| 13,076
|
cpp
|
C++
|
hamonize-admin/plugins/remoteaccess/RemoteAccessWidget.cpp
|
bsairline/hamonize
|
6632d93b0149ed300d12c4eeb06cfc4fb01fce92
|
[
"Apache-2.0"
] | null | null | null |
hamonize-admin/plugins/remoteaccess/RemoteAccessWidget.cpp
|
bsairline/hamonize
|
6632d93b0149ed300d12c4eeb06cfc4fb01fce92
|
[
"Apache-2.0"
] | 1
|
2022-03-25T19:24:44.000Z
|
2022-03-25T19:24:44.000Z
|
hamonize-admin/plugins/remoteaccess/RemoteAccessWidget.cpp
|
gon1942/hamonize
|
0456d934569ad664e9f71c6355424426654caabf
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
/*
* RemoteAccessWidget.cpp - widget containing a VNC-view and controls for it
*
* Copyright (c) 2006-2021 Tobias Junghans <tobydox@veyon.io>
*
* This file is part of Veyon - https://veyon.io
*
* This 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 software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
#include <QBitmap>
#include <QLayout>
#include <QMenu>
#include <QPainter>
#include <QPaintEvent>
#include "rfb/keysym.h"
#include "RemoteAccessWidget.h"
#include "VncViewWidget.h"
#include "VeyonConfiguration.h"
#include "VeyonConnection.h"
#include "VeyonMasterInterface.h"
#include "Computer.h"
#include "ComputerControlInterface.h"
#include "PlatformCoreFunctions.h"
#include "ToolButton.h"
#include "Screenshot.h"
// toolbar for remote-control-widget
RemoteAccessWidgetToolBar::RemoteAccessWidgetToolBar( RemoteAccessWidget* parent,
bool startViewOnly, bool showViewOnlyToggleButton ) :
QWidget( parent ),
m_parent( parent ),
m_showHideTimeLine( ShowHideAnimationDuration, this ),
m_iconStateTimeLine( 0, this ),
m_connecting( false ),
m_viewOnlyButton( showViewOnlyToggleButton ? new ToolButton( QPixmap( QStringLiteral(":/remoteaccess/kmag.png") ), tr( "View only" ), tr( "Remote control" ) ) : nullptr ),
m_sendShortcutButton( new ToolButton( QPixmap( QStringLiteral(":/remoteaccess/preferences-desktop-keyboard.png") ), tr( "Send shortcut" ) ) ),
m_screenshotButton( new ToolButton( QPixmap( QStringLiteral(":/remoteaccess/camera-photo.png") ), tr( "Screenshot" ) ) ),
m_fullScreenButton( new ToolButton( QPixmap( QStringLiteral(":/remoteaccess/view-fullscreen.png") ), tr( "Fullscreen" ), tr( "Window" ) ) ),
m_exitButton( new ToolButton( QPixmap( QStringLiteral(":/remoteaccess/application-exit.png") ), tr( "Exit" ) ) )
{
QPalette pal = palette();
pal.setBrush( QPalette::Window, QPixmap( QStringLiteral(":/core/toolbar-background.png") ) );
setPalette( pal );
setAttribute( Qt::WA_NoSystemBackground, true );
move( 0, 0 );
show();
startConnection();
if( m_viewOnlyButton )
{
m_viewOnlyButton->setCheckable( true );
m_viewOnlyButton->setChecked( startViewOnly );
connect( m_viewOnlyButton, &ToolButton::toggled, this, &RemoteAccessWidgetToolBar::updateControls );
connect( m_viewOnlyButton, &QAbstractButton::toggled, parent, &RemoteAccessWidget::toggleViewOnly );
}
m_fullScreenButton->setCheckable( true );
m_fullScreenButton->setChecked( false );
connect( m_fullScreenButton, &QAbstractButton::toggled, parent, &RemoteAccessWidget::toggleFullScreen );
connect( m_screenshotButton, &QAbstractButton::clicked, parent, &RemoteAccessWidget::takeScreenshot );
connect( m_exitButton, &QAbstractButton::clicked, parent, &QWidget::close );
auto vncView = parent->vncView();
auto shortcutMenu = new QMenu();
#if QT_VERSION < 0x050600
#warning Building legacy compat code for unsupported version of Qt
connect( shortcutMenu->addAction( tr( "Ctrl+Alt+Del" ) ), &QAction::triggered,
vncView, [=]() { vncView->sendShortcut( VncView::ShortcutCtrlAltDel ); } );
connect( shortcutMenu->addAction( tr( "Ctrl+Esc" ) ), &QAction::triggered,
vncView, [=]() { vncView->sendShortcut( VncView::ShortcutCtrlEscape ); } );
connect( shortcutMenu->addAction( tr( "Alt+Tab" ) ), &QAction::triggered,
vncView, [=]() { vncView->sendShortcut( VncView::ShortcutAltTab ); } );
connect( shortcutMenu->addAction( tr( "Alt+F4" ) ), &QAction::triggered,
vncView, [=]() { vncView->sendShortcut( VncView::ShortcutAltF4 ); } );
connect( shortcutMenu->addAction( tr( "Win+Tab" ) ), &QAction::triggered,
vncView, [=]() { vncView->sendShortcut( VncView::ShortcutWinTab ); } );
connect( shortcutMenu->addAction( tr( "Win" ) ), &QAction::triggered,
vncView, [=]() { vncView->sendShortcut( VncView::ShortcutWin ); } );
connect( shortcutMenu->addAction( tr( "Menu" ) ), &QAction::triggered,
vncView, [=]() { vncView->sendShortcut( VncView::ShortcutMenu ); } );
connect( shortcutMenu->addAction( tr( "Alt+Ctrl+F1" ) ), &QAction::triggered,
vncView, [=]() { vncView->sendShortcut( VncView::ShortcutAltCtrlF1 ); } );
#else
shortcutMenu->addAction( tr( "Ctrl+Alt+Del" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutCtrlAltDel ); } );
shortcutMenu->addAction( tr( "Ctrl+Esc" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutCtrlEscape ); } );
shortcutMenu->addAction( tr( "Alt+Tab" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutAltTab ); } );
shortcutMenu->addAction( tr( "Alt+F4" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutAltF4 ); } );
shortcutMenu->addAction( tr( "Win+Tab" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutWinTab ); } );
shortcutMenu->addAction( tr( "Win" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutWin ); } );
shortcutMenu->addAction( tr( "Menu" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutMenu ); } );
shortcutMenu->addAction( tr( "Alt+Ctrl+F1" ), vncView, [=]() { vncView->sendShortcut( VncView::ShortcutAltCtrlF1 ); } );
#endif
m_sendShortcutButton->setMenu( shortcutMenu );
m_sendShortcutButton->setPopupMode( QToolButton::InstantPopup );
m_sendShortcutButton->setObjectName( QStringLiteral("shortcuts") );
auto layout = new QHBoxLayout( this );
layout->setContentsMargins( 1, 1, 1, 1 );
layout->setSpacing( 1 );
layout->addStretch( 0 );
layout->addWidget( m_sendShortcutButton );
if( m_viewOnlyButton )
{
layout->addWidget( m_viewOnlyButton );
}
layout->addWidget( m_screenshotButton );
layout->addWidget( m_fullScreenButton );
layout->addWidget( m_exitButton );
layout->addSpacing( 5 );
connect( vncView, &VncViewWidget::startConnection, this, &RemoteAccessWidgetToolBar::startConnection );
connect( vncView, &VncViewWidget::connectionEstablished, this, &RemoteAccessWidgetToolBar::connectionEstablished );
setFixedHeight( m_exitButton->height() );
connect( &m_showHideTimeLine, &QTimeLine::valueChanged, this, &RemoteAccessWidgetToolBar::updatePosition );
m_iconStateTimeLine.setFrameRange( 0, 100 );
m_iconStateTimeLine.setDuration( 1500 );
m_iconStateTimeLine.setUpdateInterval( 60 );
m_iconStateTimeLine.easingCurve().setType( QEasingCurve::SineCurve );
connect( &m_iconStateTimeLine, &QTimeLine::valueChanged, this, &RemoteAccessWidgetToolBar::updateConnectionAnimation );
connect( &m_iconStateTimeLine, &QTimeLine::finished, &m_iconStateTimeLine, &QTimeLine::start );
}
void RemoteAccessWidgetToolBar::appear()
{
m_showHideTimeLine.setDirection( QTimeLine::Backward );
if( m_showHideTimeLine.state() != QTimeLine::Running )
{
m_showHideTimeLine.resume();
}
}
void RemoteAccessWidgetToolBar::disappear()
{
if( !m_connecting && !rect().contains( mapFromGlobal( QCursor::pos() ) ) )
{
QTimer::singleShot( DisappearDelay, this, [this]() {
if( m_showHideTimeLine.state() != QTimeLine::Running )
{
m_showHideTimeLine.setDirection( QTimeLine::Forward );
m_showHideTimeLine.resume();
}
} );
}
}
void RemoteAccessWidgetToolBar::updateControls( bool viewOnly )
{
m_sendShortcutButton->setVisible( viewOnly == false );
}
void RemoteAccessWidgetToolBar::leaveEvent( QEvent *event )
{
disappear();
QWidget::leaveEvent( event );
}
void RemoteAccessWidgetToolBar::paintEvent( QPaintEvent *paintEv )
{
QPainter p( this );
QFont f = p.font();
p.setOpacity( 0.8-0.8*m_showHideTimeLine.currentValue() );
p.fillRect( paintEv->rect(), palette().brush( QPalette::Window ) );
p.setOpacity( 1 );
f.setPointSize( 12 );
f.setBold( true );
p.setFont( f );
//p.setPen( Qt::white );
//p.drawText( 64, 22, m_parent->windowTitle() );
p.setPen( QColor( 192, 192, 192 ) );
f.setPointSize( 10 );
p.setFont( f );
if( m_connecting )
{
QString dots;
for( int i = 0; i < ( m_iconStateTimeLine.currentTime() / 120 ) % 6; ++i )
{
dots += QLatin1Char('.');
}
p.drawText( 32, height() / 2 + fontMetrics().height(), tr( "Connecting %1" ).arg( dots ) );
}
else
{
p.drawText( 32, height() / 2 + fontMetrics().height(), tr( "Connected." ) );
}
}
void RemoteAccessWidgetToolBar::updateConnectionAnimation()
{
repaint();
}
void RemoteAccessWidgetToolBar::updatePosition()
{
const auto newY = static_cast<int>( m_showHideTimeLine.currentValue() * height() );
if( newY != -y() )
{
move( x(), qMax( -height(), -newY ) );
}
}
void RemoteAccessWidgetToolBar::startConnection()
{
m_connecting = true;
m_iconStateTimeLine.start();
appear();
update();
}
void RemoteAccessWidgetToolBar::connectionEstablished()
{
m_connecting = false;
m_iconStateTimeLine.stop();
disappear();
// within the next 1000ms the username should be known and therefore we update
QTimer::singleShot( 1000, this, QOverload<>::of( &RemoteAccessWidgetToolBar::update ) );
}
RemoteAccessWidget::RemoteAccessWidget( const ComputerControlInterface::Pointer& computerControlInterface,
bool startViewOnly, bool showViewOnlyToggleButton ) :
QWidget( nullptr ),
m_computerControlInterface( computerControlInterface ),
m_vncView( new VncViewWidget( computerControlInterface->computer().hostAddress(), -1, this, VncView::RemoteControlMode ) ),
m_toolBar( new RemoteAccessWidgetToolBar( this, startViewOnly, showViewOnlyToggleButton ) )
{
const auto openOnMasterScreen = VeyonCore::config().showFeatureWindowsOnSameScreen();
const auto master = VeyonCore::instance()->findChild<VeyonMasterInterface *>();
if( master && openOnMasterScreen )
{
const auto masterWindow = master->mainWindow();
move( masterWindow->x(), masterWindow->y() );
} else {
move( 0, 0 );
}
updateRemoteAccessTitle();
connect( m_computerControlInterface.data(), &ComputerControlInterface::userChanged, this, &RemoteAccessWidget::updateRemoteAccessTitle );
setWindowIcon( QPixmap( QStringLiteral(":/remoteaccess/kmag.png") ) );
setAttribute( Qt::WA_DeleteOnClose, true );
m_vncView->move( 0, 0 );
m_vncView->installEventFilter( this );
connect( m_vncView, &VncViewWidget::mouseAtBorder, m_toolBar, &RemoteAccessWidgetToolBar::appear );
connect( m_vncView, &VncViewWidget::sizeHintChanged, this, &RemoteAccessWidget::updateSize );
showMaximized();
VeyonCore::platform().coreFunctions().raiseWindow( this, false );
showNormal();
toggleViewOnly( startViewOnly );
}
RemoteAccessWidget::~RemoteAccessWidget()
{
delete m_vncView;
}
bool RemoteAccessWidget::eventFilter( QObject* object, QEvent* event )
{
if( event->type() == QEvent::KeyRelease &&
dynamic_cast<QKeyEvent *>( event )->key() == Qt::Key_Escape &&
m_vncView->connection()->isConnected() == false )
{
close();
return true;
}
if( object == m_vncView && event->type() == QEvent::FocusOut )
{
m_toolBar->disappear();
}
return QWidget::eventFilter( object, event );
}
void RemoteAccessWidget::enterEvent( QEvent* event )
{
m_toolBar->disappear();
QWidget::enterEvent( event );
}
void RemoteAccessWidget::leaveEvent( QEvent* event )
{
QTimer::singleShot( AppearDelay, this, [this]() {
if( underMouse() == false && window()->isActiveWindow() )
{
m_toolBar->appear();
}
} );
QWidget::leaveEvent( event );
}
void RemoteAccessWidget::resizeEvent( QResizeEvent* event )
{
m_vncView->resize( size() );
m_toolBar->setFixedSize( width(), m_toolBar->height() );
QWidget::resizeEvent( event );
}
void RemoteAccessWidget::updateSize()
{
if( !( windowState() & Qt::WindowFullScreen ) &&
m_vncView->sizeHint().isEmpty() == false )
{
resize( m_vncView->sizeHint() );
}
}
void RemoteAccessWidget::toggleFullScreen( bool _on )
{
if( _on )
{
setWindowState( windowState() | Qt::WindowFullScreen );
}
else
{
setWindowState( windowState() & ~Qt::WindowFullScreen );
}
}
void RemoteAccessWidget::toggleViewOnly( bool viewOnly )
{
m_vncView->setViewOnly( viewOnly );
m_toolBar->updateControls( viewOnly );
m_toolBar->update();
}
void RemoteAccessWidget::takeScreenshot()
{
Screenshot().take( m_computerControlInterface );
}
void RemoteAccessWidget::updateRemoteAccessTitle()
{
if ( m_computerControlInterface->userFullName().isEmpty() )
{
setWindowTitle( tr( "%1 - Hamonize Remote Access" ).arg( m_computerControlInterface->computer().name(),
VeyonCore::applicationName() ) );
} else
{
setWindowTitle( tr( "%1 - %2 - Hamonize Remote Access" ).arg( m_computerControlInterface->userFullName(),
m_computerControlInterface->computer().name(),
VeyonCore::applicationName() ) );
}
}
| 30.985782
| 172
| 0.712986
|
bsairline
|
3437e389a3bb554caa194c623883806e623cea07
| 6,641
|
cpp
|
C++
|
src/llvmsym/stanalysis/inputvariables.cpp
|
yaqwsx/SymDivine
|
5400fb2d2deaf00c745ab9f8e4f572c79d7e9caa
|
[
"MIT"
] | 6
|
2015-10-13T20:01:01.000Z
|
2017-04-05T04:00:17.000Z
|
src/llvmsym/stanalysis/inputvariables.cpp
|
yaqwsx/SymDivine
|
5400fb2d2deaf00c745ab9f8e4f572c79d7e9caa
|
[
"MIT"
] | 6
|
2015-10-12T09:30:34.000Z
|
2016-05-24T16:44:12.000Z
|
src/llvmsym/stanalysis/inputvariables.cpp
|
yaqwsx/SymDivine
|
5400fb2d2deaf00c745ab9f8e4f572c79d7e9caa
|
[
"MIT"
] | 3
|
2015-10-12T12:20:25.000Z
|
2017-04-05T04:06:06.000Z
|
#include <llvmsym/llvmwrap/Instructions.h>
#include <llvmsym/llvmwrap/Constants.h>
#include <llvmsym/stanalysis/inputvariables.h>
#include <llvmsym/cxa_abi/demangler.h>
namespace {
bool _is_nonconstant_pointer( const llvm::Value *val )
{
return ( val->getType()->isPointerTy() && !llvm::isa< llvm::Constant >( val ) )
|| llvm::isa< llvm::GlobalVariable >( val );
}
}
bool MultivalInfo::visit_value( const llvm::Value *val, const llvm::Function *parent )
{
bool change = false;
const llvm::User *v = llvm::dyn_cast< llvm::User >( val );
if ( !v )
return false;
for ( unsigned i = 0; i < v->getNumOperands(); ++i ) {
auto operand = v->getOperand( i );
if ( llvm::isa< llvm::ConstantExpr >( operand ) ) {
auto operand_expr = llvm::cast< llvm::ConstantExpr >( operand );
change = change || visit_value( operand_expr, parent );
}
}
if ( llvm::isa< llvm::Function >( val ) )
return change;
unsigned opcode;
if ( llvm::isa< llvm::Instruction >( v ) ) {
const llvm::Instruction *tmp_inst = llvm::cast< llvm::Instruction >( v );
opcode = tmp_inst->getOpcode();
} else {
const llvm::ConstantExpr *tmp_inst = llvm::cast< llvm::ConstantExpr >( v );
opcode = tmp_inst->getOpcode();
}
typedef llvm::Instruction LLVMInst;
switch ( opcode ) {
case LLVMInst::Ret: {
const llvm::Value* returned = llvm::cast< llvm::ReturnInst >( v )->getReturnValue();
if ( returned && isMultival( returned ) ) {
if ( !isMultival( parent ) ) {
setMultival( parent );
change = true;
}
} else if ( returned && _is_nonconstant_pointer( returned ) ) {
change = change || mergeRegionMultivalInfo( returned, parent );
}
return change;
} case LLVMInst::GetElementPtr: {
assert( v->getType()->isPointerTy() );
const llvm::Value *elem = v->getOperand( 0 );
const llvm::Type *elem_type = elem->getType()->getPointerElementType();
std::vector< int > indices;
if ( elem_type->isStructTy() ) {
llvm::Type *ty = elem->getType()->getPointerElementType();
for ( auto it = v->op_begin() + 2; ty->isStructTy() && it < v->op_end(); ++it ) {
assert( llvm::isa< llvm::ConstantInt >( it ) );
const llvm::ConstantInt *ci = llvm::cast< llvm::ConstantInt >( it );
int idx = ci->getLimitedValue();
indices.push_back( idx );
ty = ty->getContainedType( idx );
}
}
return mergeRegionMultivalInfoSubtype( elem, v, indices );
} case LLVMInst::ICmp:
case LLVMInst::FCmp: {
return change;
} case LLVMInst::Store: {
const llvm::Value *val_operand = llvm::cast< llvm::StoreInst >( v )->getValueOperand();
const llvm::Value *ptr = llvm::cast< llvm::StoreInst >( v )->getPointerOperand();
bool is_multival = isMultival( val_operand );
if ( is_multival && !isRegionMultival( ptr ) ) {
setRegionMultival( ptr );
change = true;
}
if ( _is_nonconstant_pointer( val_operand ) ) {
change = mergeRegionMultivalInfo( val_operand, ptr );
}
return change;
} case LLVMInst::Load: {
const llvm::Value *ptr = llvm::cast< llvm::LoadInst >( v )->getPointerOperand();
if ( !v->getType()->isPointerTy() && !isMultival( v ) ) {
if ( isRegionMultival( ptr ) ) {
setMultival( v );
change = true;
}
}
if ( v->getType()->isPointerTy() ) {
change = mergeRegionMultivalInfo( v, ptr );
}
return change;
} case LLVMInst::Call: {
const llvm::CallInst *ci = llvm::cast< llvm::CallInst >( v );
const llvm::Value *called_value = ci->getCalledFunction() ?
ci->getCalledFunction()
: ci->getCalledValue();
const llvm::Function *called_fun = ci->getCalledFunction();
if ( isMultival( called_value ) && !isMultival( v ) ) {
setMultival( v );
change = true;
} else if ( _is_nonconstant_pointer( v ) )
change = change || mergeRegionMultivalInfo( v, called_value );
if ( !called_fun )
return change;
auto arg = called_fun->arg_begin();
for ( unsigned arg_no = 0; arg_no < ci->getNumArgOperands(); ++arg_no, ++arg) {
const auto &operand = ci->getArgOperand( arg_no );
if ( isMultival( operand ) ) {
if ( !isMultival( arg ) ) {
setMultival( arg );
change = true;
}
}
if ( _is_nonconstant_pointer( operand ) ) {
change = mergeRegionMultivalInfo( operand, arg );
}
}
return change;
} case LLVMInst::ExtractValue: {
//TODO eventually
abort();
} case LLVMInst::InsertValue: {
//TODO eventually
abort();
}
}
for ( unsigned operand = 0; operand < v->getNumOperands(); ++operand ) {
if ( isMultival( v->getOperand( operand ) ) && !isMultival( v ) ) {
setMultival( v );
change = true;
break;
}
}
return change;
}
bool MultivalInfo::visit_function( const llvm::Function &function )
{
bool change = false;
for ( const llvm::Value *v : *llvm_sym::collectUsedValues( &function ) ) {
change = change || visit_value( v, &function );
}
return change;
}
void MultivalInfo::get_multivalues( const llvm::Module *module )
{
bool has_input = false;
for ( const llvm::Function &f : *module ) {
std::string fun_name = Demangler::demangle( f.getName() );
if ( llvm_sym::isFunctionInput( fun_name ) ) {
has_input = true;
setMultival( &f );
}
}
if ( !has_input )
return;
bool change = true;
while ( change ) {
change = false;
for ( const llvm::Function &function : *module ) {
change = change || visit_function( function );
}
}
}
| 35.513369
| 99
| 0.514983
|
yaqwsx
|
3438f017a59ebe1f52a4e23ee50c1de8ea272471
| 3,224
|
hpp
|
C++
|
src/modules/control_allocator/ActuatorEffectiveness/ActuatorEffectivenessHelicopter.hpp
|
uavosky/uavosky-px4
|
5793a7264a1400914521a077a7009dd227f9c766
|
[
"BSD-3-Clause"
] | 4,224
|
2015-01-02T11:51:02.000Z
|
2020-10-27T23:42:28.000Z
|
src/modules/control_allocator/ActuatorEffectiveness/ActuatorEffectivenessHelicopter.hpp
|
uavosky/uavosky-px4
|
5793a7264a1400914521a077a7009dd227f9c766
|
[
"BSD-3-Clause"
] | 11,736
|
2015-01-01T11:59:16.000Z
|
2020-10-28T17:13:38.000Z
|
src/modules/control_allocator/ActuatorEffectiveness/ActuatorEffectivenessHelicopter.hpp
|
uavosky/uavosky-px4
|
5793a7264a1400914521a077a7009dd227f9c766
|
[
"BSD-3-Clause"
] | 11,850
|
2015-01-02T14:54:47.000Z
|
2020-10-28T16:42:47.000Z
|
/****************************************************************************
*
* Copyright (c) 2022 PX4 Development Team. 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.
* 3. Neither the name PX4 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.
*
****************************************************************************/
#pragma once
#include "ActuatorEffectiveness.hpp"
#include <px4_platform_common/module_params.h>
class ActuatorEffectivenessHelicopter : public ModuleParams, public ActuatorEffectiveness
{
public:
static constexpr int NUM_SWASH_PLATE_SERVOS_MAX = 4;
static constexpr int NUM_CURVE_POINTS = 5;
struct SwashPlateGeometry {
float angle;
float arm_length;
};
struct Geometry {
SwashPlateGeometry swash_plate_servos[NUM_SWASH_PLATE_SERVOS_MAX];
int num_swash_plate_servos{0};
float throttle_curve[NUM_CURVE_POINTS];
float pitch_curve[NUM_CURVE_POINTS];
};
ActuatorEffectivenessHelicopter(ModuleParams *parent);
virtual ~ActuatorEffectivenessHelicopter() = default;
bool getEffectivenessMatrix(Configuration &configuration, EffectivenessUpdateReason external_update) override;
const char *name() const override { return "Helicopter"; }
const Geometry &geometry() const { return _geometry; }
void updateSetpoint(const matrix::Vector<float, NUM_AXES> &control_sp, int matrix_index,
ActuatorVector &actuator_sp) override;
private:
void updateParams() override;
struct ParamHandlesSwashPlate {
param_t angle;
param_t arm_length;
};
struct ParamHandles {
ParamHandlesSwashPlate swash_plate_servos[NUM_SWASH_PLATE_SERVOS_MAX];
param_t num_swash_plate_servos;
param_t throttle_curve[NUM_CURVE_POINTS];
param_t pitch_curve[NUM_CURVE_POINTS];
};
ParamHandles _param_handles{};
Geometry _geometry{};
int _first_swash_plate_servo_index{};
};
| 35.822222
| 111
| 0.743797
|
uavosky
|
343973ee233f02e5296e9d3f81ba60df5cdf46c0
| 2,604
|
cpp
|
C++
|
src/RawlogHelper.cpp
|
dzunigan/extrinsic_calib
|
aec3747aeb6baecc7bc6202fc0832a113a1bc528
|
[
"BSD-3-Clause"
] | 5
|
2018-10-24T02:14:54.000Z
|
2019-05-11T12:36:01.000Z
|
src/RawlogHelper.cpp
|
dzunigan/extrinsic_calib
|
aec3747aeb6baecc7bc6202fc0832a113a1bc528
|
[
"BSD-3-Clause"
] | null | null | null |
src/RawlogHelper.cpp
|
dzunigan/extrinsic_calib
|
aec3747aeb6baecc7bc6202fc0832a113a1bc528
|
[
"BSD-3-Clause"
] | 1
|
2021-06-30T01:12:49.000Z
|
2021-06-30T01:12:49.000Z
|
#include "RawlogHelper.hpp"
//MRPT redefinition so they work without using mrpt namepase (more general)
#ifndef CLASS_ID_
#define CLASS_ID_(class_name, space_name) static_cast<const mrpt::utils::TRuntimeClassId*>(&space_name::class_name::class##class_name)
#endif
#ifndef IS_CLASS_
#define IS_CLASS_( ptrObj, class_name, space_name ) ((ptrObj)->GetRuntimeClass()==CLASS_ID_(class_name, space_name))
#endif
//STL
#include <cmath>
//MRPT
#include <mrpt/system/datetime.h>
//Debug
#include <iostream>
RawlogHelper::RawlogHelper(const ParametersPtr ¶ms)
: n(0), m(0), last_obs() //last_obs is a null pointer (default constructor)
{
max_time_diff = params->max_time_diff;
verbose = params->verbose;
rawlog.loadFromRawLogFile(params->rawlog_file);
}
bool RawlogHelper::getNextObservation(mrpt::obs::CObservation3DRangeScanPtr &obs)
{
mrpt::obs::CObservationPtr observation;
while (!this->hasFinished())
{
//1. Get observation from rawlog
observation = rawlog.getAsObservation(n);
n++;
if (verbose)
std::cout << "RawlogHelper: entry " << n << " (" << rawlog.size()+1 << ")" << std::endl;
if(!observation || !IS_CLASS_(observation, CObservation3DRangeScan, mrpt::obs))
{
if (verbose)
std::cout << "Skipping rawlog entry " << (n-1) << "... (not valid CObservation3DRangeScan)" << std::endl;
continue;
}
obs = (mrpt::obs::CObservation3DRangeScanPtr) observation;
last_obs = obs;
return true;
}
return false;
}
bool RawlogHelper::getNextPair(ObservationPair &obs2)
{
//Handle first call
if (!last_obs)
if (!this->getNextObservation(last_obs)) return false;
do
{
obs2.first = last_obs;
if (!this->getNextObservation(obs2.second)) return false;
if (verbose)
{
std::cout << obs2.first->sensorLabel << ": " << obs2.first->timestamp << std::endl;
std::cout << obs2.second->sensorLabel << ": " << obs2.second->timestamp << std::endl;
}
if (obs2.first->sensorLabel.compare(obs2.second->sensorLabel) != 0)
m++;
} while ((obs2.first->sensorLabel.compare(obs2.second->sensorLabel) == 0) ||
(std::abs(mrpt::system::timeDifference(obs2.first->timestamp, obs2.second->timestamp))) > max_time_diff);
//abs shouldn't be needed, but it also doesn't harm...
if (verbose) std::cout << "Synch" << std::endl;
return true;
}
bool RawlogHelper::hasFinished()
{
return (n >= rawlog.size());
}
| 28
| 138
| 0.630184
|
dzunigan
|
343c15b6a0ac86e95b2432f6043483abcc50d90a
| 48
|
cc
|
C++
|
test/define/d3.cc
|
aytchell/cppclean
|
29ba7547a085f742585a74798cc5ad083bd0836f
|
[
"Apache-2.0"
] | 607
|
2015-01-02T12:37:18.000Z
|
2022-03-20T13:37:01.000Z
|
test/define/d3.cc
|
aytchell/cppclean
|
29ba7547a085f742585a74798cc5ad083bd0836f
|
[
"Apache-2.0"
] | 1,372
|
2019-11-14T09:22:21.000Z
|
2022-03-29T13:01:20.000Z
|
test/define/d3.cc
|
aytchell/cppclean
|
29ba7547a085f742585a74798cc5ad083bd0836f
|
[
"Apache-2.0"
] | 86
|
2019-11-14T04:47:23.000Z
|
2022-03-03T02:44:15.000Z
|
#include "d3.h"
void Namespace::Function() {}
| 9.6
| 29
| 0.645833
|
aytchell
|
343dd66fe901d165781aa02d49bb2f845c2d716d
| 475
|
cpp
|
C++
|
examples/rocketwar/src/shared/network/incommingPacket.cpp
|
AlexAUT/rocketWar
|
edea1c703755e198b1ad8909c82e5d8d56c443ef
|
[
"MIT"
] | null | null | null |
examples/rocketwar/src/shared/network/incommingPacket.cpp
|
AlexAUT/rocketWar
|
edea1c703755e198b1ad8909c82e5d8d56c443ef
|
[
"MIT"
] | null | null | null |
examples/rocketwar/src/shared/network/incommingPacket.cpp
|
AlexAUT/rocketWar
|
edea1c703755e198b1ad8909c82e5d8d56c443ef
|
[
"MIT"
] | null | null | null |
#include "incommingPacket.hpp"
#include <cassert>
namespace network
{
void IncommingPacket::reset()
{
assert(mHandled && "You are resetting a not handled packet!");
mPacket.clear();
mReadPos = 0;
mHandled = false;
}
aw::uint8* IncommingPacket::reserve(size_t bytes)
{
mPacket.clear();
mPacket.writeToPayload(nullptr, bytes);
return mPacket.payload().data();
}
void IncommingPacket::resize(size_t bytes)
{
mPacket.resize(bytes);
}
} // namespace network
| 16.37931
| 64
| 0.711579
|
AlexAUT
|
343f31dec15ad1b495e5e8c680c73fab57df1546
| 613
|
cpp
|
C++
|
Spoj/LASTDIG2_TheLastDigitRevisit.cpp
|
shiva92/Contests
|
720bb3699f774a6ea1f99e888e0cd784e63130c8
|
[
"Apache-2.0"
] | null | null | null |
Spoj/LASTDIG2_TheLastDigitRevisit.cpp
|
shiva92/Contests
|
720bb3699f774a6ea1f99e888e0cd784e63130c8
|
[
"Apache-2.0"
] | null | null | null |
Spoj/LASTDIG2_TheLastDigitRevisit.cpp
|
shiva92/Contests
|
720bb3699f774a6ea1f99e888e0cd784e63130c8
|
[
"Apache-2.0"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main() {
// #ifndef ONLINE_JUDGE
// freopen("/home/shiva/Learning/1.txt", "r", stdin);
// freopen("/home/shiva/Learning/2.txt", "w", stdout);
// #endif
int arr[10] = {0}; int t; cin >> t;
long long b;
string a;
for (int x = 0; x < t; x++) {
memset(arr, 0, sizeof arr);
cin >> a >> b;
if (b == 0) {cout << 1 << endl; continue;}
int aa = int(a[int(a.size()) - 1]) - 48;
int res = aa;
int c = 0;
vector<int> v;
while (!arr[res]) {
v.push_back(res); arr[res] = 1;
res = (res * aa) % 10;
c++;
}
cout << v[(b - 1) % c] << endl;
}
}
| 21.892857
| 55
| 0.51876
|
shiva92
|
343f9c7d95740fbbad670c65ce53c46bc304e826
| 1,084
|
cc
|
C++
|
components/ucloud_ai/src/model/aliyun-openapi/core/src/AlibabaCloud.cc
|
wstong999/AliOS-Things
|
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
|
[
"Apache-2.0"
] | 4,538
|
2017-10-20T05:19:03.000Z
|
2022-03-30T02:29:30.000Z
|
components/ucloud_ai/src/model/aliyun-openapi/core/src/AlibabaCloud.cc
|
wstong999/AliOS-Things
|
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
|
[
"Apache-2.0"
] | 1,088
|
2017-10-21T07:57:22.000Z
|
2022-03-31T08:15:49.000Z
|
components/ucloud_ai/src/model/aliyun-openapi/core/src/AlibabaCloud.cc
|
willianchanlovegithub/AliOS-Things
|
637c0802cab667b872d3b97a121e18c66f256eab
|
[
"Apache-2.0"
] | 1,860
|
2017-10-20T05:22:35.000Z
|
2022-03-27T10:54:14.000Z
|
/*
* Copyright 1999-2019 Alibaba Cloud 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 "Executor.h"
#include <alibabacloud/core/AlibabaCloud.h>
static AlibabaCloud::Executor *executor = nullptr;
void AlibabaCloud::InitializeSdk() {
if (IsSdkInitialized())
return;
executor = new Executor;
executor->start();
}
bool AlibabaCloud::IsSdkInitialized() { return executor != nullptr; }
void AlibabaCloud::ShutdownSdk() {
if (!IsSdkInitialized())
return;
executor->shutdown();
delete executor;
executor = nullptr;
}
| 27.1
| 75
| 0.72786
|
wstong999
|
343ff49b559c0f21635c590d49fe79a1fc4fa51a
| 984
|
hpp
|
C++
|
MazeSolver/Source/graph.hpp
|
Darhal/Maze-Solver
|
f8d46a6b3732a391efff63ed663ab47000b61388
|
[
"MIT"
] | null | null | null |
MazeSolver/Source/graph.hpp
|
Darhal/Maze-Solver
|
f8d46a6b3732a391efff63ed663ab47000b61388
|
[
"MIT"
] | null | null | null |
MazeSolver/Source/graph.hpp
|
Darhal/Maze-Solver
|
f8d46a6b3732a391efff63ed663ab47000b61388
|
[
"MIT"
] | null | null | null |
#pragma once
#include <vector>
#include <utility>
#include <stdint.h>
#include <limits.h>
class Graph
{
public:
Graph(uint32_t vertecies = 0) : graph(vertecies)
{
}
void SetVertex(uint32_t vertex, std::vector<std::pair<uint32_t, uint32_t>> next)
{
graph[vertex] = std::move(next);
}
void AddEdgeToVertex(uint32_t vertex, uint32_t next, uint32_t cost = 1)
{
graph[vertex].emplace_back(next, cost);
}
std::vector<std::pair<uint32_t, uint32_t>>& GetVertex(uint32_t vertex)
{
return graph[vertex];
}
bool IsNext(uint32_t vertex, uint32_t next)
{
for (std::pair<uint32_t, uint32_t> v : this->GetVertex(vertex)) {
if (v.first == next) {
return true;
}
}
return false;
}
uint32_t GetCost(uint32_t vertex, uint32_t next)
{
for (std::pair<uint32_t, uint32_t> v : this->GetVertex(vertex)) {
if (v.first == next) {
return v.second;
}
}
return UINT_MAX;
}
private:
std::vector<std::vector<std::pair<uint32_t, uint32_t>>> graph;
};
| 18.566038
| 81
| 0.668699
|
Darhal
|
34407b0deadf3a5daf2ecf83f8962faca98e3f7c
| 828
|
hpp
|
C++
|
01_src/compontents/components.hpp
|
gledr/SMT_MacroPlacer
|
b5b25f0ce9094553167ffd4985721f86414ceddc
|
[
"MIT"
] | 3
|
2020-06-05T15:33:30.000Z
|
2021-05-03T07:34:15.000Z
|
01_src/compontents/components.hpp
|
gledr/SMT_MacroPlacer
|
b5b25f0ce9094553167ffd4985721f86414ceddc
|
[
"MIT"
] | null | null | null |
01_src/compontents/components.hpp
|
gledr/SMT_MacroPlacer
|
b5b25f0ce9094553167ffd4985721f86414ceddc
|
[
"MIT"
] | 1
|
2021-05-03T07:34:17.000Z
|
2021-05-03T07:34:17.000Z
|
//==================================================================
// Author : Pointner Sebastian
// Company : Johannes Kepler University
// Name : SMT Macro Placer
// Workfile : components.hpp
//
// Date : 19. May 2020
// Compiler : gcc version 9.3.0 (GCC)
// Copyright : Johannes Kepler University
// Description : Include Header for all Components
//==================================================================
#ifndef COMPONENTS_HPP
#define COMPONENTS_HPP
#include <cell.hpp>
#include <component.hpp>
#include <macro.hpp>
#include <macro_definition.hpp>
#include <partition.hpp>
#include <pin.hpp>
#include <pin_definition.hpp>
#include <supplementmacro.hpp>
#include <supplementpin.hpp>
#include <terminal.hpp>
#include <terminal_definition.hpp>
#endif /* COMPONENTS_HPP */
| 29.571429
| 68
| 0.588164
|
gledr
|
34419f6dafb6189ebd9e5f5222f6a7701c2275ed
| 4,746
|
cc
|
C++
|
chromecast/device/bluetooth/le/le_scan_manager_impl.cc
|
zipated/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 2,151
|
2020-04-18T07:31:17.000Z
|
2022-03-31T08:39:18.000Z
|
chromecast/device/bluetooth/le/le_scan_manager_impl.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 395
|
2020-04-18T08:22:18.000Z
|
2021-12-08T13:04:49.000Z
|
chromecast/device/bluetooth/le/le_scan_manager_impl.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 338
|
2020-04-18T08:03:10.000Z
|
2022-03-29T12:33:22.000Z
|
// Copyright 2018 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 "chromecast/device/bluetooth/le/le_scan_manager_impl.h"
#include <algorithm>
#include <utility>
#include "base/stl_util.h"
#include "chromecast/base/bind_to_task_runner.h"
#include "chromecast/device/bluetooth/bluetooth_util.h"
#include "chromecast/public/cast_media_shlib.h"
#define RUN_ON_IO_THREAD(method, ...) \
io_task_runner_->PostTask( \
FROM_HERE, base::BindOnce(&LeScanManagerImpl::method, \
weak_factory_.GetWeakPtr(), ##__VA_ARGS__));
#define MAKE_SURE_IO_THREAD(method, ...) \
DCHECK(io_task_runner_); \
if (!io_task_runner_->BelongsToCurrentThread()) { \
RUN_ON_IO_THREAD(method, ##__VA_ARGS__) \
return; \
}
#define EXEC_CB_AND_RET(cb, ret, ...) \
do { \
if (cb) { \
std::move(cb).Run(ret, ##__VA_ARGS__); \
} \
return; \
} while (0)
namespace chromecast {
namespace bluetooth {
namespace {
const int kMaxMessagesInQueue = 5;
} // namespace
LeScanManagerImpl::LeScanManagerImpl(
bluetooth_v2_shlib::LeScannerImpl* le_scanner)
: le_scanner_(le_scanner),
observers_(new base::ObserverListThreadSafe<Observer>()),
weak_factory_(this) {}
LeScanManagerImpl::~LeScanManagerImpl() = default;
void LeScanManagerImpl::Initialize(
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner) {
io_task_runner_ = std::move(io_task_runner);
}
void LeScanManagerImpl::Finalize() {}
void LeScanManagerImpl::AddObserver(Observer* observer) {
observers_->AddObserver(observer);
}
void LeScanManagerImpl::RemoveObserver(Observer* observer) {
observers_->RemoveObserver(observer);
}
void LeScanManagerImpl::SetScanEnable(bool enable, SetScanEnableCallback cb) {
MAKE_SURE_IO_THREAD(SetScanEnable, enable,
BindToCurrentSequence(std::move(cb)));
bool success;
if (enable) {
success = le_scanner_->StartScan();
} else {
success = le_scanner_->StopScan();
}
if (!success) {
LOG(ERROR) << "Failed to " << (enable ? "enable" : "disable")
<< " ble scanning";
EXEC_CB_AND_RET(cb, false);
}
observers_->Notify(FROM_HERE, &Observer::OnScanEnableChanged, enable);
EXEC_CB_AND_RET(cb, true);
}
void LeScanManagerImpl::GetScanResults(GetScanResultsCallback cb,
base::Optional<ScanFilter> scan_filter) {
MAKE_SURE_IO_THREAD(GetScanResults, BindToCurrentSequence(std::move(cb)),
std::move(scan_filter));
std::move(cb).Run(GetScanResultsInternal(std::move(scan_filter)));
}
// Returns a list of all scan results. The results are sorted by RSSI.
std::vector<LeScanResult> LeScanManagerImpl::GetScanResultsInternal(
base::Optional<ScanFilter> scan_filter) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
std::vector<LeScanResult> results;
for (const auto& pair : addr_to_scan_results_) {
for (const auto& scan_result : pair.second) {
if (!scan_filter || scan_filter->Matches(scan_result)) {
results.push_back(scan_result);
}
}
}
std::sort(results.begin(), results.end(),
[](const LeScanResult& d1, const LeScanResult& d2) {
return d1.rssi > d2.rssi;
});
return results;
}
void LeScanManagerImpl::ClearScanResults() {
MAKE_SURE_IO_THREAD(ClearScanResults);
addr_to_scan_results_.clear();
}
void LeScanManagerImpl::OnScanResult(
const bluetooth_v2_shlib::LeScanner::ScanResult& scan_result_shlib) {
LeScanResult scan_result;
if (!scan_result.SetAdvData(scan_result_shlib.adv_data)) {
// Error logged.
return;
}
scan_result.addr = scan_result_shlib.addr;
scan_result.rssi = scan_result_shlib.rssi;
// Remove results with the same data as the current result to avoid duplicate
// messages in the queue
auto& previous_scan_results = addr_to_scan_results_[scan_result.addr];
previous_scan_results.remove_if([&scan_result](const auto& previous_result) {
return previous_result.adv_data == scan_result.adv_data;
});
previous_scan_results.push_front(scan_result);
if (previous_scan_results.size() > kMaxMessagesInQueue) {
previous_scan_results.pop_back();
}
// Update observers.
observers_->Notify(FROM_HERE, &Observer::OnNewScanResult, scan_result);
}
} // namespace bluetooth
} // namespace chromecast
| 32.067568
| 80
| 0.665402
|
zipated
|
3441a9435a11658516d1b142812b86ad399095eb
| 1,045
|
cpp
|
C++
|
vespalib/src/vespa/vespalib/datastore/unique_store_buffer_type.cpp
|
alexeyche/vespa
|
7585981b32937d2b13da1a8f94b42c8a0833a4c2
|
[
"Apache-2.0"
] | null | null | null |
vespalib/src/vespa/vespalib/datastore/unique_store_buffer_type.cpp
|
alexeyche/vespa
|
7585981b32937d2b13da1a8f94b42c8a0833a4c2
|
[
"Apache-2.0"
] | null | null | null |
vespalib/src/vespa/vespalib/datastore/unique_store_buffer_type.cpp
|
alexeyche/vespa
|
7585981b32937d2b13da1a8f94b42c8a0833a4c2
|
[
"Apache-2.0"
] | null | null | null |
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "unique_store_buffer_type.hpp"
#include "unique_store_entry.h"
namespace vespalib::datastore {
template class BufferType<UniqueStoreEntry<int8_t>>;
template class BufferType<UniqueStoreEntry<int16_t>>;
template class BufferType<UniqueStoreEntry<int32_t>>;
template class BufferType<UniqueStoreEntry<int64_t>>;
template class BufferType<UniqueStoreEntry<uint32_t>>;
template class BufferType<UniqueStoreEntry<float>>;
template class BufferType<UniqueStoreEntry<double>>;
template class UniqueStoreBufferType<UniqueStoreEntry<int8_t>>;
template class UniqueStoreBufferType<UniqueStoreEntry<int16_t>>;
template class UniqueStoreBufferType<UniqueStoreEntry<int32_t>>;
template class UniqueStoreBufferType<UniqueStoreEntry<int64_t>>;
template class UniqueStoreBufferType<UniqueStoreEntry<uint32_t>>;
template class UniqueStoreBufferType<UniqueStoreEntry<float>>;
template class UniqueStoreBufferType<UniqueStoreEntry<double>>;
};
| 40.192308
| 104
| 0.844019
|
alexeyche
|
45175a27e0afcdfbd6bdfa5d764209c195f5bc5c
| 2,411
|
hpp
|
C++
|
drtm-dst/src/rtx/batch_op_impl.hpp
|
SJTU-IPADS/dst
|
897b929a692642cbf295c105d9d6e64090abb673
|
[
"Apache-2.0"
] | 9
|
2020-12-17T01:59:13.000Z
|
2022-03-30T16:25:08.000Z
|
drtm-dst/src/rtx/batch_op_impl.hpp
|
SJTU-IPADS/dst
|
897b929a692642cbf295c105d9d6e64090abb673
|
[
"Apache-2.0"
] | 1
|
2021-07-30T12:06:33.000Z
|
2021-07-31T10:16:09.000Z
|
drtm-dst/src/rtx/batch_op_impl.hpp
|
SJTU-IPADS/dst
|
897b929a692642cbf295c105d9d6e64090abb673
|
[
"Apache-2.0"
] | 1
|
2021-08-01T13:47:07.000Z
|
2021-08-01T13:47:07.000Z
|
#include "msg_format.hpp"
namespace nocc {
using namespace nocc::util;
namespace rtx {
struct BatchOpCtrlBlock {
char *req_buf_;
char *req_buf_end_;
char *reply_buf_;
std::set<int> mac_set_;
int batch_size_;
inline BatchOpCtrlBlock(char *req_buf,char *res_buf) :
batch_size_(0),
req_buf_(req_buf),
reply_buf_(res_buf)
{
clear();
}
inline void add_mac(int pid) {
mac_set_.insert(pid);
}
inline void clear() {
mac_set_.clear();
req_buf_end_ = req_buf_ + sizeof(RTXRequestHeader);
batch_size_ = 0;
}
inline void clear_buf() {
req_buf_end_ = req_buf_ + sizeof(RTXRequestHeader);
batch_size_ = 0;
}
inline int batch_msg_size() {
return req_buf_end_ - req_buf_;
}
inline int send_batch_op(RRpc *rpc,int cid,int rpc_id,bool pa = false) {
if(batch_size_ > 0) {
((RTXRequestHeader *)req_buf_)->num = batch_size_;
if(!pa) {
rpc->prepare_multi_req(reply_buf_,mac_set_.size(),cid);
}
rpc->broadcast_to(req_buf_,rpc_id,
batch_msg_size(),
cid,RRpc::REQ,mac_set_);
}
return mac_set_.size();
}
};
inline __attribute__((always_inline))
void TXOpBase::start_batch_rpc_op(BatchOpCtrlBlock &ctrl) {
// no pending batch requests
ctrl.clear();
}
template <typename REQ,typename... _Args> // batch req
inline __attribute__((always_inline))
void TXOpBase::add_batch_entry(BatchOpCtrlBlock &ctrl,int pid, _Args&& ... args) {
ctrl.batch_size_ += 1;
// copy the entries
*((REQ *)ctrl.req_buf_end_) = REQ(std::forward<_Args>(args)...);
ctrl.req_buf_end_ += sizeof(REQ);
ctrl.mac_set_.insert(pid);
}
template <typename REQ,typename... _Args> // batch req
inline __attribute__((always_inline))
void TXOpBase::add_batch_entry_wo_mac(BatchOpCtrlBlock &ctrl,int pid, _Args&& ... args) {
ctrl.batch_size_ += 1;
// copy the entries
*((REQ *)ctrl.req_buf_end_) = REQ(std::forward<_Args>(args)...);
ctrl.req_buf_end_ += sizeof(REQ);
}
inline __attribute__((always_inline))
int TXOpBase::send_batch_rpc_op(BatchOpCtrlBlock &ctrl,int cid,int rpc_id,bool pa) {
return ctrl.send_batch_op(rpc_,cid,rpc_id,pa);
}
template <typename REPLY>
inline __attribute__((always_inline))
REPLY *TXOpBase::get_batch_res(BatchOpCtrlBlock &ctrl,int idx) {
return ((REPLY *)ctrl.reply_buf_ + idx);
}
}; // namespace rtx
}; // namespace nocc
| 24.11
| 89
| 0.676898
|
SJTU-IPADS
|
451a0e3f3980397b7f77b9c1b79f06c786ecbfe0
| 1,115
|
cpp
|
C++
|
tests/actor_behavior.cpp
|
zzxx-husky/ZAF
|
b9c37c758a2f8242aec0d70c467d718468d08fa5
|
[
"Apache-2.0"
] | 4
|
2021-07-29T12:49:09.000Z
|
2022-01-13T03:40:46.000Z
|
tests/actor_behavior.cpp
|
zzxx-husky/ZAF
|
b9c37c758a2f8242aec0d70c467d718468d08fa5
|
[
"Apache-2.0"
] | null | null | null |
tests/actor_behavior.cpp
|
zzxx-husky/ZAF
|
b9c37c758a2f8242aec0d70c467d718468d08fa5
|
[
"Apache-2.0"
] | null | null | null |
#include "zaf/actor_behavior.hpp"
#include "zaf/actor_system.hpp"
#include "gtest/gtest.h"
namespace zaf {
GTEST_TEST(ActorBehavior, Basic) {
ActorSystem actor_system;
ActorBehavior actor1;
actor1.initialize_actor(actor_system, actor_system);
ActorBehavior actor2;
actor2.initialize_actor(actor_system, actor_system);
actor1.send(actor2, 0, std::string("Hello World"));
actor2.receive_once({
Code{0} - [](const std::string& hw) {
EXPECT_EQ(hw, "Hello World");
}
});
}
GTEST_TEST(ActorBehavior, DelayedSendWithReceiveTimeout) {
ActorSystem actor_system;
auto a = actor_system.spawn([&](ActorBehavior& self) {
self.delayed_send(std::chrono::seconds{1}, self, Code{0});
bool received = false;
for (int i = 0; i < 4; i++) {
self.receive_once({
Code{0} - [&]() {
received = true;
}
}, std::chrono::milliseconds{200});
EXPECT_FALSE(received);
}
self.receive_once({
Code{0} - [&]() {
received = true;
}
}, std::chrono::milliseconds{210});
EXPECT_TRUE(received);
});
}
} // namespace zaf
| 23.723404
| 62
| 0.634978
|
zzxx-husky
|
451ec556f9b2d36764908afcb2fcad82f82ed0d8
| 4,619
|
cpp
|
C++
|
windows/cpp/samples/hw_enc_avc_intel_file/hw_enc_avc_intel_file.cpp
|
avblocks/avblocks-samples
|
7388111a27c8110a9f7222e86e912fe38f444543
|
[
"MIT"
] | 1
|
2022-02-28T04:12:09.000Z
|
2022-02-28T04:12:09.000Z
|
windows/cpp/samples/hw_enc_avc_intel_file/hw_enc_avc_intel_file.cpp
|
avblocks/avblocks-samples
|
7388111a27c8110a9f7222e86e912fe38f444543
|
[
"MIT"
] | null | null | null |
windows/cpp/samples/hw_enc_avc_intel_file/hw_enc_avc_intel_file.cpp
|
avblocks/avblocks-samples
|
7388111a27c8110a9f7222e86e912fe38f444543
|
[
"MIT"
] | 1
|
2022-02-28T02:43:24.000Z
|
2022-02-28T02:43:24.000Z
|
/*
* Copyright (c) 2016 Primo Software. 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.
*/
#include "stdafx.h"
#include "util.h"
#include "options.h"
using namespace primo::codecs;
using namespace primo::avblocks;
using namespace std;
class stdout_utf16
{
public:
stdout_utf16()
{
// change stdout to Unicode. Cyrillic and Ideographic characters will appear in the console (console font is unicode).
_setmode(_fileno(stdout), _O_U16TEXT);
}
~stdout_utf16()
{
// restore ANSI mode
_setmode(_fileno(stdout), _O_TEXT);
}
};
void printStatus(const wchar_t* action, const primo::error::ErrorInfo* e)
{
if (action)
{
wcout << action << L": ";
}
if (primo::error::ErrorFacility::Success == e->facility())
{
wcout << L"Success" << endl;
return;
}
if (e->message())
{
wcout << e->message() << L", ";
}
wcout << L"facility:" << e->facility() << L", error:" << e->code() << endl;
}
bool isHardwareEncoderAvailable(primo::codecs::HwVendor::Enum vendor, primo::codecs::HwCodecType::Enum type)
{
primo::ref<Hardware> hw(Library::createHardware());
hw->refresh();
for (int i = 0; i < hw->devices()->count(); ++i)
{
HwDevice* device = hw->devices()->at(i);
if (device->vendor() == vendor)
{
for (int j = 0; j < device->codecs()->count(); ++j)
{
if (device->codecs()->at(j)->type() == type)
return true;
}
}
}
return false;
}
primo::ref<MediaSocket> createInputSocket(Options& opt)
{
auto socket = primo::make_ref(Library::createMediaSocket());
socket->setStreamType(StreamType::UncompressedVideo);
socket->setFile(opt.yuv_file.c_str());
auto pin = primo::make_ref(Library::createMediaPin());
socket->pins()->add(pin.get());
auto vsi = primo::make_ref(Library::createVideoStreamInfo());
pin->setStreamInfo(vsi.get());
vsi->setStreamType(StreamType::UncompressedVideo);
vsi->setFrameWidth(opt.frame_size.width_);
vsi->setFrameHeight(opt.frame_size.height_);
vsi->setColorFormat(opt.yuv_color.Id);
vsi->setFrameRate(opt.fps);
vsi->setScanType(ScanType::Progressive);
return socket;
}
primo::ref<MediaSocket> createOutputSocket(Options& opt)
{
auto socket = primo::make_ref(Library::createMediaSocket());
socket->setFile(opt.h264_file.c_str());
socket->setStreamType(StreamType::H264);
socket->setStreamSubType(StreamSubType::AVC_Annex_B);
auto pin = primo::make_ref(Library::createMediaPin());
socket->pins()->add(pin.get());
auto vsi = primo::make_ref(Library::createVideoStreamInfo());
pin->setStreamInfo(vsi.get());
pin->params()->addInt(Param::HardwareEncoder, HardwareEncoder::Intel);
vsi->setStreamType(StreamType::H264);
vsi->setStreamSubType(StreamSubType::AVC_Annex_B);
return socket;
}
bool encode(Options& opt)
{
auto inSocket = createInputSocket(opt);
// create output socket
auto outSocket = createOutputSocket(opt);
// create transcoder
auto transcoder = primo::make_ref(Library::createTranscoder());
transcoder->setAllowDemoMode(TRUE);
transcoder->inputs()->add(inSocket.get());
transcoder->outputs()->add(outSocket.get());
// transcoder will fail if output exists (by design)
deleteFile(opt.h264_file.c_str());
bool_t res = transcoder->open();
printStatus(L"Transcoder open:", transcoder->error());
if(!res)
return false;
res = transcoder->run();
printStatus(L"Transcoder run:", transcoder->error());
if(!res)
return false;
transcoder->close();
printStatus(L"Transcoder close:", transcoder->error());
return true;
}
int wmain(int argc, wchar_t* argv[])
{
Options opt;
switch(prepareOptions( opt, argc, argv))
{
case Command: return 0;
case Error: return 1;
}
Library::initialize();
if (!isHardwareEncoderAvailable(primo::codecs::HwVendor::Intel, primo::codecs::HwCodecType::H264Encoder))
{
wcout << "Intel H.264 hardware encoder is not available on your system" << endl;
return 0;
}
bool result = encode(opt);
Library::shutdown();
return result ? 0 : 1;
}
| 26.394286
| 127
| 0.606841
|
avblocks
|
452178ec8ad3cabe4e642fbe06772ac6f04cd837
| 6,590
|
cpp
|
C++
|
sg/importer/Importer.cpp
|
ospray/ospray_studio
|
1549ac72c7c561b4aafdea976189bbe95bd32ff2
|
[
"Apache-2.0"
] | 52
|
2018-10-09T23:56:32.000Z
|
2022-03-25T09:27:40.000Z
|
sg/importer/Importer.cpp
|
ospray/ospray_studio
|
1549ac72c7c561b4aafdea976189bbe95bd32ff2
|
[
"Apache-2.0"
] | 11
|
2018-11-19T18:51:47.000Z
|
2022-03-28T14:03:57.000Z
|
sg/importer/Importer.cpp
|
ospray/ospray_studio
|
1549ac72c7c561b4aafdea976189bbe95bd32ff2
|
[
"Apache-2.0"
] | 8
|
2019-02-10T00:16:24.000Z
|
2022-02-17T19:50:15.000Z
|
// Copyright 2009-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "Importer.h"
#include "sg/visitors/PrintNodes.h"
#include "../JSONDefs.h"
namespace ospray {
namespace sg {
OSPSG_INTERFACE std::map<std::string, std::string> importerMap = {
{"obj", "importer_obj"},
{"gltf", "importer_gltf"},
{"glb", "importer_gltf"},
{"raw", "importer_raw"},
{"structured", "importer_raw"},
{"spherical", "importer_raw"},
{"vdb", "importer_vdb"},
{"pcd", "importer_pcd"},
{"pvol", "importer_pvol"}};
Importer::Importer() {}
NodeType Importer::type() const
{
return NodeType::IMPORTER;
}
void Importer::importScene() {
}
OSPSG_INTERFACE void importScene(
std::shared_ptr<StudioContext> context, rkcommon::FileName &sceneFileName)
{
std::cout << "Importing a scene" << std::endl;
context->filesToImport.clear();
std::ifstream sgFile(sceneFileName.str());
if (!sgFile) {
std::cerr << "Could not open " << sceneFileName << " for reading"
<< std::endl;
return;
}
JSON j;
sgFile >> j;
std::map<std::string, JSON> jImporters;
sg::NodePtr lights;
// If the sceneFile contains a world (importers and lights), parse it here
// (must happen before refreshScene)
if (j.contains("world")) {
auto &jWorld = j["world"];
for (auto &jChild : jWorld["children"]) {
// Import either the old-type enum directly, or the new-type enum STRING
NodeType nodeType = jChild["type"].is_string()
? NodeTypeFromString[jChild["type"]]
: jChild["type"].get<NodeType>();
switch (nodeType) {
case NodeType::IMPORTER: {
FileName fileName = std::string(jChild["filename"]);
// Try a couple different paths to find the file before giving up
std::vector<std::string> possibleFileNames = {fileName, // as imported
sceneFileName.path() + fileName.base(), // in scenefile directory
fileName.base(), // in local directory
""};
for (auto tryFile : possibleFileNames) {
if (tryFile != "") {
std::ifstream f(tryFile);
if (f.good()) {
context->filesToImport.push_back(tryFile);
jImporters[jChild["name"]] = jChild;
break;
}
} else
std::cerr << "Unable to find " << fileName << std::endl;
}
} break;
case NodeType::LIGHTS:
// Handle lights in either the (world) or the lightsManager
lights = createNodeFromJSON(jChild);
break;
default:
break;
}
}
}
// refreshScene imports all filesToImport
if (!context->filesToImport.empty())
context->refreshScene(true);
// Any lights in the scenefile World are added here
if (lights) {
for (auto &light : lights->children())
context->lightsManager->addLight(light.second);
}
// If the sceneFile contains a lightsManager, add those lights here
if (j.contains("lightsManager")) {
auto &jLights = j["lightsManager"];
for (auto &jLight : jLights["children"])
context->lightsManager->addLight(createNodeFromJSON(jLight));
}
// If the sceneFile contains materials, parse them here, after the model has
// loaded. These parameters will overwrite materials in the model file.
if (j.contains("materialRegistry")) {
sg::NodePtr materials = createNodeFromJSON(j["materialRegistry"]);
for (auto &mat : materials->children()) {
// XXX temporary workaround. Just set params on existing materials.
// Prevents loss of texture data. Will be fixed when textures can reload.
// Modify existing material or create new material
// (account for change of material type)
if (context->baseMaterialRegistry->hasChild(mat.first)
&& context->baseMaterialRegistry->child(mat.first).subType()
== mat.second->subType()) {
auto &bMat = context->baseMaterialRegistry->child(mat.first);
for (auto ¶m : mat.second->children()) {
auto &p = *param.second;
// This is a generated node value and can't be imported
if (param.first == "handles")
continue;
// Modify existing param or create new params
if (bMat.hasChild(param.first))
bMat[param.first] = p.value();
else
bMat.createChild(
param.first, p.subType(), p.description(), p.value());
}
} else
context->baseMaterialRegistry->add(mat.second);
}
// refreshScene imports all filesToImport and updates materials
context->refreshScene(true);
}
// If the sceneFile contains a camera location
// (must happen after refreshScene)
if (j.contains("camera")) {
CameraState cs = j["camera"];
context->setCameraState(cs);
context->updateCamera();
}
// after import, correctly apply transform import nodes
// (must happen after refreshScene)
auto world = context->frame->childNodeAs<sg::Node>("world");
for (auto &jImport : jImporters) {
// lamdba, find node by name
std::function<sg::NodePtr(const sg::NodePtr, const std::string &)>
findFirstChild = [&findFirstChild](const sg::NodePtr root,
const std::string &name) -> sg::NodePtr {
sg::NodePtr found = nullptr;
// Quick shallow top-level search first
for (auto child : root->children())
if (child.first == name)
return child.second;
// Next level, deeper search if not found
for (auto child : root->children()) {
found = findFirstChild(child.second, name);
if (found)
return found;
}
return found;
};
auto importNode = findFirstChild(world, jImport.first);
if (importNode) {
// should be associated xfm node
auto childName = jImport.second["children"][0]["name"];
Node &xfmNode = importNode->child(childName);
// XXX parse JSON to get RST transforms saved to sg file. This is
// temporary. We will want RST to be a first-class citizen node that gets
// handled correctly without this kind of hardcoded workaround
auto child = createNodeFromJSON(jImport.second["children"][0]);
if (child) {
xfmNode = child->value(); // assigns base affine3f value
xfmNode.add(child->child("rotation"));
xfmNode.add(child->child("translation"));
xfmNode.add(child->child("scale"));
}
}
}
}
// global assets catalogue
AssetsCatalogue cat;
} // namespace sg
} // namespace ospray
| 31.5311
| 80
| 0.619272
|
ospray
|
4522b88d3e7187d55aa1849d096e3394be564b19
| 639
|
cpp
|
C++
|
checker.cpp
|
Engin-Boot/vitals-simplification-cpp-Tanvi-Kale
|
67b5cdce6696caed510efcd1e82f619dadfd08e3
|
[
"MIT"
] | null | null | null |
checker.cpp
|
Engin-Boot/vitals-simplification-cpp-Tanvi-Kale
|
67b5cdce6696caed510efcd1e82f619dadfd08e3
|
[
"MIT"
] | null | null | null |
checker.cpp
|
Engin-Boot/vitals-simplification-cpp-Tanvi-Kale
|
67b5cdce6696caed510efcd1e82f619dadfd08e3
|
[
"MIT"
] | null | null | null |
#include <assert.h>
bool vitalsRangeIsOk(float value,int lowerLimit,int upperLimit)
{
return (value >= lowerLimit && value <= upperLimit);
}
bool vitalsAreOk(float bpm, float spo2, float respRate) {
return (vitalsRangeIsOk(bpm,70,150) && vitalsRangeIsOk(spo2,90,100) && vitalsRangeIsOk(respRate,30,95));
}
int main() {
assert(vitalsRangeIsOk(160,70,150) == false);
assert(vitalsRangeIsOk(20,70,150) == false);
assert(vitalsRangeIsOk(70,70,150) == true);
assert(vitalsRangeIsOk(90,70,150) == true);
assert(vitalsAreOk(80, 95, 60) == true);
assert(vitalsAreOk(60, 90, 40) == false);
return 0;
}
| 26.625
| 108
| 0.672926
|
Engin-Boot
|
452c2bc19dabb166d7962055bbbd3adb041b7e93
| 514
|
cpp
|
C++
|
uppdev/RichHtml/main.cpp
|
dreamsxin/ultimatepp
|
41d295d999f9ff1339b34b43c99ce279b9b3991c
|
[
"BSD-2-Clause"
] | 2
|
2016-04-07T07:54:26.000Z
|
2020-04-14T12:37:34.000Z
|
uppdev/RichHtml/main.cpp
|
dreamsxin/ultimatepp
|
41d295d999f9ff1339b34b43c99ce279b9b3991c
|
[
"BSD-2-Clause"
] | null | null | null |
uppdev/RichHtml/main.cpp
|
dreamsxin/ultimatepp
|
41d295d999f9ff1339b34b43c99ce279b9b3991c
|
[
"BSD-2-Clause"
] | null | null | null |
#include <CtrlLib/CtrlLib.h>
#include <RichText/RichText.h>
#include <Web/Web.h>
using namespace Upp;
#define TOPICFILE <RichHtml/tst.tpp/all.i>
#include <Core/topic_group.h>
GUI_APP_MAIN
{
Index<String> css;
VectorMap<String, String> links;
String qtf = GetTopic("topic://RichHtml/tst/Topic$en-us");
String html = EncodeHtml(ParseQTF(qtf), css, links, "e:\\xxx");
Htmls content =
HtmlHeader("Ultimate++", AsCss(css))
.BgColor(White)
/ html;
SaveFile(GetHomeDirFile("html.html"), content);
}
| 23.363636
| 64
| 0.702335
|
dreamsxin
|
452da6fe4e6d905249e89e7673f85c4a1a11cda2
| 774
|
cpp
|
C++
|
Miscellaneous/InterviewBit/Array/RotateImage.cpp
|
chirag-singhal/-Data-Structures-and-Algorithms
|
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
|
[
"MIT"
] | 24
|
2021-02-09T17:59:54.000Z
|
2022-03-11T07:30:38.000Z
|
Miscellaneous/InterviewBit/Array/RotateImage.cpp
|
chirag-singhal/-Data-Structures-and-Algorithms
|
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
|
[
"MIT"
] | null | null | null |
Miscellaneous/InterviewBit/Array/RotateImage.cpp
|
chirag-singhal/-Data-Structures-and-Algorithms
|
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
|
[
"MIT"
] | 3
|
2021-06-22T03:09:49.000Z
|
2022-03-09T18:25:14.000Z
|
#include <bits/stdc++.h>
void rotate(std::vector<std::vector<int> > &A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
for(int i = 0; i < A.size() / 2; i++) {
for(int j = i; j < A.size() - i - 1; j++) {
int temp = A[i][j];
A[i][j] = A[A.size() - 1 - j][i];
A[A.size() - j - 1][i] = A[A.size() - 1 - i][A.size() - j - 1];
A[A.size() - 1 - i][A.size() - j - 1] = A[j][A.size() - i - 1];
A[j][A.size() - i - 1] = temp;
}
}
}
| 35.181818
| 93
| 0.459948
|
chirag-singhal
|
452ee43e21aafb068418cfb57dfdab51a06eee65
| 2,784
|
cpp
|
C++
|
benchmark/demo_benchmark.cpp
|
Algorithms-and-Data-Structures-2021/semester-work-median
|
a3592c0af93f562ea8f60e2301e5f21d1edbda0e
|
[
"MIT"
] | null | null | null |
benchmark/demo_benchmark.cpp
|
Algorithms-and-Data-Structures-2021/semester-work-median
|
a3592c0af93f562ea8f60e2301e5f21d1edbda0e
|
[
"MIT"
] | null | null | null |
benchmark/demo_benchmark.cpp
|
Algorithms-and-Data-Structures-2021/semester-work-median
|
a3592c0af93f562ea8f60e2301e5f21d1edbda0e
|
[
"MIT"
] | null | null | null |
#include <fstream> // ifstream
#include <iostream> // cout
#include <string> // string, stoi
#include <string_view> // string_view
#include <chrono> // high_resolution_clock, duration_cast, nanoseconds
#include <sstream> // stringstream
#include <vector>
// подключаем алгоритм
#include "algorithm.hpp"
using namespace std;
// абсолютный путь до набора данных и папки проекта
static constexpr auto kDatasetPath = string_view{PROJECT_DATASET_DIR};
static constexpr auto kProjectPath = string_view{PROJECT_SOURCE_DIR};
//Путь к папке с наборами данных для заполнения
const string setsPath = "C:/Users/Admin/Desktop/sets";
// Сгенирировать наборы даннх : https://github.com/rthoor/generation.git
//укажите названия папок с наборами данных, если они есть
string folders[5] = {"/01/","/02/","/03/","/04/","/05/"};
//если их нет
//string folders[1] = {"/"};
//укажите названия файлов с наборами данных (без .csv)
string files[8] = {"11", "51", "101", "501", "1001", "5001", "10001", "50001"};
//Путь к папке, куда нужно выгрузить результаты
const string outputPath = "C:/Users/Admin/Desktop/results/";
// Ознакомтесь с директорией "results-path-example/results"
// в папке выгруза результатов нужно будет реализовать похожую структуру,
// опираясь на названия файлов в массиве files
// -----------------------------------
// запускать main() (в самом низу) |
// -----------------------------------
//Вывод результатов
void writeResults(string file, long time) {
// вывод результата
// не забудьте подготовить директорию
std::ofstream out(outputPath + file + "/results.txt", std::ios::app);
if (out.is_open()) {
out << time << std::endl;
}
out.close();
}
void goTest() {
for (auto file : files) {
for (auto folder : folders) {
for (int i = 0; i < 10; i++) { // i = сколько раз прогоняем один и тот же csv файл
auto input_file = ifstream(setsPath + folder + file + ".csv");
string line;
// Создание структуры
vector<int> array;
// добавление
while (getline(input_file, line, ',')) {
array.push_back(stoi(line));
}
auto time_point_before = chrono::steady_clock::now();
itis::quickselect(array);
auto time_point_after = chrono::steady_clock::now();
auto time_diff_insert = time_point_after - time_point_before;
long time = chrono::duration_cast<chrono::nanoseconds>(time_diff_insert).count();
array.clear();
// запись результатов
writeResults(file, time);
}
}
}
}
int main() {
goTest();
return 0;
}
| 32
| 97
| 0.600575
|
Algorithms-and-Data-Structures-2021
|
45310c3ba8f1aa569b5c663e734e95570828b415
| 2,128
|
cpp
|
C++
|
Shared Classes/Stats.cpp
|
Mertank/ToneArm
|
40c62b0de89ac506bea6674e43578bf4e2631f93
|
[
"Zlib",
"BSD-2-Clause"
] | null | null | null |
Shared Classes/Stats.cpp
|
Mertank/ToneArm
|
40c62b0de89ac506bea6674e43578bf4e2631f93
|
[
"Zlib",
"BSD-2-Clause"
] | null | null | null |
Shared Classes/Stats.cpp
|
Mertank/ToneArm
|
40c62b0de89ac506bea6674e43578bf4e2631f93
|
[
"Zlib",
"BSD-2-Clause"
] | null | null | null |
/*
------------------------------------------------------------------------------------------
Copyright (c) 2014 Vinyl Games Studio
Author: Mikhail Kutuzov
Date: 10/7/2014 5:45:48 PM
------------------------------------------------------------------------------------------
*/
#include "Stats.h"
#include "Effect.h"
using namespace merrymen;
//
// handles application of the effect
//
void Stats::ApplyEffect(const Effect& effect, vgs::GameObject* const author) {
Effect* appliedEffect = new Effect(effect);
// add the effect to the list of applied effects
AppliedEffects.insert(std::pair<Effect*, vgs::GameObject*>(appliedEffect, author));
}
//
// cancels one of the applied effects
//
void Stats::UnapplyEffect(Effect* const effect, vgs::GameObject* const author) {
// remove the effect from the list of applied effects
AppliedEffects.erase(effect);
delete effect;
}
//
// returns all of the effects applied to the stats which match the passed type
//
std::vector<Effect*> Stats::GetAppliedEffectsOfType(const SpecificEffectType& type) {
std::vector<Effect*> result;
for (auto effect : AppliedEffects) {
SpecificEffectType effectType = SpecificEffectType(effect.first->Type, effect.first->Reason);
if (effectType == type) {
result.push_back(effect.first);
}
}
return result;
}
//
// returns all of the effects of the same type as the passed effect, which are applied to the stats
//
std::vector<Effect*> Stats::GetSimilarAppliedEffects(const Effect& effect) {
std::vector<Effect*> result;
SpecificEffectType effectType = SpecificEffectType(effect.Type, effect.Reason);
for (auto appliedEffect : AppliedEffects) {
SpecificEffectType appliedEfectType = SpecificEffectType(appliedEffect.first->Type, appliedEffect.first->Reason);
if (effectType == appliedEfectType) {
result.push_back(appliedEffect.first);
}
}
return result;
}
//
// cound the number of effects of the same type as the passed effect, which are applied to the stats
//
int Stats::CountSimilarAppliedEffects(const Effect& effect) {
return GetSimilarAppliedEffects(effect).size();
}
| 25.035294
| 115
| 0.670583
|
Mertank
|
4531123f6dcce4fd01d694f2d37959abaadcdd44
| 9,191
|
cpp
|
C++
|
cpp/cppfind/src/FindSettings.cpp
|
clarkcb/xfind
|
fbe5d970d0a604e0d357a5c6d78eb26dbcd3294a
|
[
"MIT"
] | null | null | null |
cpp/cppfind/src/FindSettings.cpp
|
clarkcb/xfind
|
fbe5d970d0a604e0d357a5c6d78eb26dbcd3294a
|
[
"MIT"
] | null | null | null |
cpp/cppfind/src/FindSettings.cpp
|
clarkcb/xfind
|
fbe5d970d0a604e0d357a5c6d78eb26dbcd3294a
|
[
"MIT"
] | null | null | null |
#include "FileUtil.h"
#include "StringUtil.h"
#include "FindSettings.h"
namespace cppfind {
FindSettings::FindSettings() {
m_in_archiveextensions = {};
m_in_archivefilepatterns = {};
m_in_dirpatterns = {};
m_in_extensions = {};
m_in_filepatterns = {};
m_in_filetypes = {};
m_out_archiveextensions = {};
m_out_archivefilepatterns = {};
m_out_dirpatterns = {};
m_out_extensions = {};
m_out_filepatterns = {};
m_out_filetypes = {};
m_paths = {};
}
void FindSettings::add_pattern(const std::string& p, std::vector<FindPattern*>* ps) {
ps->push_back(new FindPattern(p));
}
void FindSettings::add_extensions(const std::string& exts, std::vector<std::string>* extensions) {
std::vector<std::string> xs = StringUtil::split_string(exts, ",");
for (const auto& x : xs) {
if (!x.empty()) {
extensions->push_back(x);
}
}
}
void FindSettings::add_in_archiveextension(const std::string& ext) {
add_extensions(ext, &m_in_archiveextensions);
}
void FindSettings::add_in_archivefilepattern(const std::string& p) {
add_pattern(p, &m_in_archivefilepatterns);
}
void FindSettings::add_in_dirpattern(const std::string& p) {
add_pattern(p, &m_in_dirpatterns);
}
void FindSettings::add_in_extension(const std::string& ext) {
add_extensions(ext, &m_in_extensions);
}
void FindSettings::add_in_filepattern(const std::string& p) {
add_pattern(p, &m_in_filepatterns);
}
void FindSettings::add_in_filetype(const FileType filetype) {
m_in_filetypes.push_back(filetype);
}
void FindSettings::add_out_archiveextension(const std::string& ext) {
add_extensions(ext, &m_out_archiveextensions);
}
void FindSettings::add_out_archivefilepattern(const std::string& p) {
add_pattern(p, &m_out_archivefilepatterns);
}
void FindSettings::add_out_dirpattern(const std::string& p) {
add_pattern(p, &m_out_dirpatterns);
}
void FindSettings::add_out_extension(const std::string& ext) {
add_extensions(ext, &m_out_extensions);
}
void FindSettings::add_out_filepattern(const std::string& p) {
add_pattern(p, &m_out_filepatterns);
}
void FindSettings::add_out_filetype(const FileType filetype) {
m_out_filetypes.push_back(filetype);
}
void FindSettings::add_path(const std::string& p) {
m_paths.push_back(p);
}
bool FindSettings::archivesonly() const {
return m_archivesonly;
}
bool FindSettings::debug() const {
return m_debug;
}
bool FindSettings::excludehidden() const {
return m_excludehidden;
}
bool FindSettings::includearchives() const {
return m_includearchives;
}
bool FindSettings::listdirs() const {
return m_listdirs;
}
bool FindSettings::listfiles() const {
return m_listfiles;
}
bool FindSettings::printusage() const {
return m_printusage;
}
bool FindSettings::printversion() const {
return m_printversion;
}
bool FindSettings::recursive() const {
return m_recursive;
}
std::vector<std::string>* FindSettings::in_archiveextensions() {
return &m_in_archiveextensions;
}
std::vector<FindPattern*>* FindSettings::in_archivefilepatterns() {
return &m_in_archivefilepatterns;
}
std::vector<FindPattern*>* FindSettings::in_dirpatterns() {
return &m_in_dirpatterns;
}
std::vector<std::string>* FindSettings::in_extensions() {
return &m_in_extensions;
}
std::vector<FindPattern*>* FindSettings::in_filepatterns() {
return &m_in_filepatterns;
}
std::vector<FileType>* FindSettings::in_filetypes() {
return &m_in_filetypes;
}
std::vector<std::string>* FindSettings::out_archiveextensions() {
return &m_out_archiveextensions;
}
std::vector<FindPattern*>* FindSettings::out_archivefilepatterns() {
return &m_out_archivefilepatterns;
}
std::vector<FindPattern*>* FindSettings::out_dirpatterns() {
return &m_out_dirpatterns;
}
std::vector<std::string>* FindSettings::out_extensions() {
return &m_out_extensions;
}
std::vector<FindPattern*>* FindSettings::out_filepatterns() {
return &m_out_filepatterns;
}
std::vector<FileType>* FindSettings::out_filetypes() {
return &m_out_filetypes;
}
std::vector<std::string>* FindSettings::paths() {
return &m_paths;
}
bool FindSettings::verbose() const {
return m_verbose;
}
void FindSettings::archivesonly(const bool b) {
m_archivesonly = b;
if (b) m_includearchives = b;
}
void FindSettings::debug(const bool b) {
m_debug = b;
if (b) m_verbose = b;
}
void FindSettings::excludehidden(const bool b) {
m_excludehidden = b;
}
void FindSettings::includearchives(const bool b) {
m_includearchives = b;
}
void FindSettings::listdirs(const bool b) {
m_listdirs = b;
}
void FindSettings::listfiles(const bool b) {
m_listfiles = b;
}
void FindSettings::printusage(const bool b) {
m_printusage = b;
}
void FindSettings::printversion(const bool b) {
m_printversion = b;
}
void FindSettings::recursive(const bool b) {
m_recursive = b;
}
void FindSettings::verbose(const bool b) {
m_verbose = b;
}
std::string FindSettings::bool_to_string(bool b) {
return b ? "true" : "false";
}
std::string FindSettings::string_vector_to_string(std::vector<std::string>* ss) {
std::string ss_string = "[";
int count = 0;
for (auto const& s : *ss) {
if (count > 0) {
ss_string.append(", ");
}
ss_string.append("\"").append(s).append("\"");
count++;
}
ss_string.append("]");
return ss_string;
}
std::string FindSettings::findpatterns_to_string(std::vector<FindPattern*>* ps) {
std::string ps_string = "[";
int count = 0;
for (auto const& p : *ps) {
if (count > 0) {
ps_string.append(", ");
}
ps_string.append("\"").append(p->pattern()).append("\"");
count++;
}
ps_string.append("]");
return ps_string;
}
std::string FindSettings::filetypes_to_string(std::vector<FileType>* ts) {
std::string ts_string = "[";
int count = 0;
for (auto const& t : *ts) {
if (count > 0) {
ts_string.append(", ");
}
ts_string.append("\"").append(FileTypes::to_name(t)).append("\"");
count++;
}
ts_string.append("]");
return ts_string;
}
std::string FindSettings::string() {
auto settings_str =
std::string("FindSettings(")
+ "archivesonly: " + bool_to_string(m_archivesonly)
+ ", debug: " + bool_to_string(m_debug)
+ ", excludehidden: " + bool_to_string(m_excludehidden)
+ ", in_archiveextensions: " + string_vector_to_string(&m_in_archiveextensions)
+ ", in_archivefilepatterns: " + findpatterns_to_string(&m_in_archivefilepatterns)
+ ", in_dirpatterns: " + findpatterns_to_string(&m_in_dirpatterns)
+ ", in_extensions: " + string_vector_to_string(&m_in_extensions)
+ ", in_filepatterns: " + findpatterns_to_string(&m_in_filepatterns)
+ ", in_filetypes: " + filetypes_to_string(&m_in_filetypes)
+ ", includearchives: " + bool_to_string(m_includearchives)
+ ", listdirs: " + bool_to_string(m_listdirs)
+ ", listfiles: " + bool_to_string(m_listfiles)
+ ", out_archiveextensions: " + string_vector_to_string(&m_out_archiveextensions)
+ ", out_archivefilepatterns: " + findpatterns_to_string(&m_out_archivefilepatterns)
+ ", out_dirpatterns: " + findpatterns_to_string(&m_out_dirpatterns)
+ ", out_extensions: " + string_vector_to_string(&m_out_extensions)
+ ", out_filepatterns: " + findpatterns_to_string(&m_out_filepatterns)
+ ", out_filetypes: " + filetypes_to_string(&m_out_filetypes)
+ ", paths: " + string_vector_to_string(&m_paths)
+ ", printusage: " + bool_to_string(m_printusage)
+ ", printversion: " + bool_to_string(m_printversion)
+ ", recursive: " + bool_to_string(m_recursive)
+ ", verbose: " + bool_to_string(m_verbose)
+ ")";
return settings_str;
}
std::ostream& operator<<(std::ostream& strm, FindSettings& settings) {
std::string settings_string = settings.string();
return strm << settings_string;
}
}
| 30.433775
| 102
| 0.598955
|
clarkcb
|
4536e307f42d425866f3d9ad9020706f0477068b
| 3,190
|
cpp
|
C++
|
vec3f.cpp
|
ei14/qecvec
|
e097d0a205889ec65362992c4171ae535bc113a5
|
[
"MIT"
] | null | null | null |
vec3f.cpp
|
ei14/qecvec
|
e097d0a205889ec65362992c4171ae535bc113a5
|
[
"MIT"
] | null | null | null |
vec3f.cpp
|
ei14/qecvec
|
e097d0a205889ec65362992c4171ae535bc113a5
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2021 Thomas Kaldahl
#include "qecvec.hpp"
// Constructors
Vec3f::Vec3f(
float x,
float y,
float z
) {
this->x = x;
this->y = y;
this->z = z;
}
Vec3f::Vec3f(float val) : Vec3f(val, val, val) {}
Vec3f::Vec3f() : Vec3f(0) {}
Vec3f::Vec3f(Vec2f v, float z) : Vec3f(v.x, v.y, z) {}
Vec3f::Vec3f(float x, Vec2f v) : Vec3f(x, v.x, v.y) {}
// Statics
Vec3f Vec3f::zero() {return Vec3f();}
Vec3f Vec3f::up() {return Vec3f( 0, 1, 0 );}
Vec3f Vec3f::down() {return Vec3f( 0, -1, 0 );}
Vec3f Vec3f::left() {return Vec3f( -1, 0, 0 );}
Vec3f Vec3f::right() {return Vec3f( 1, 0, 0 );}
Vec3f Vec3f::forward() {return Vec3f( 0, 0, 1 );}
Vec3f Vec3f::backward() {return Vec3f( 0, 0, -1 );}
//vec2f.cpp: Vec2f Vec2f::up() {return Vec2f( 0, 1 );}
//vec2f.cpp: Vec2f Vec2f::down() {return Vec2f( 0, -1 );}
//vec2f.cpp: Vec2f Vec2f::left() {return Vec2f( -1, 0 );}
//vec2f.cpp: Vec2f Vec2f::right() {return Vec2f( 1, 0 );}
//vec2f.cpp: Vec2f Vec2f::polar(float r, float theta) {
//vec2f.cpp: return Vec2f(r * cos(theta), r * sin(theta));
//vec2f.cpp: }
Vec3f Vec3f::randomUniform(float min, float max) {
float x = (max - min) * rand() / (float)RAND_MAX + min;
float y = (max - min) * rand() / (float)RAND_MAX + min;
float z = (max - min) * rand() / (float)RAND_MAX + min;
return Vec3f(x, y, z);
}
// Accessors
char *Vec3f::string() const {
char *res = (char*)malloc(64);
snprintf(res, 64, "< %0.3f, %0.3f, %0.3f >", x, y, z);
return res;
}
Vec2f Vec3f::xy() const {return Vec2f(x, y);}
Vec2f Vec3f::xz() const {return Vec2f(x, z);}
Vec2f Vec3f::yz() const {return Vec2f(y, z);}
// Technical methods
Vec3f Vec3f::copy() const {
return Vec3f(x, y, z);
}
// In-place operations
Vec3f Vec3f::operator*=(float scalar) {
x *= scalar;
y *= scalar;
z *= scalar;
return *this;
}
Vec3f Vec3f::operator/=(float divisor) {
x /= divisor;
y /= divisor;
z /= divisor;
return *this;
}
Vec3f Vec3f::operator+=(Vec3f addend) {
x += addend.x;
y += addend.y;
z += addend.z;
return *this;
}
Vec3f Vec3f::operator-=(Vec3f subtrahend) {
x -= subtrahend.x;
y -= subtrahend.y;
z -= subtrahend.z;
return *this;
}
Vec3f Vec3f::operator&=(Vec3f multiplier) {
x *= multiplier.x;
y *= multiplier.y;
z *= multiplier.z;
return *this;
}
Vec3f Vec3f::normalize() {
x /= norm();
y /= norm();
z /= norm();
return *this;
}
// Binary operations
Vec3f Vec3f::operator*(float scalar) const {return copy() *= scalar;}
Vec3f Vec3f::operator/(float divisor) const {return copy() /= divisor;}
float Vec3f::operator^(float exponent) const {return pow(norm(), exponent);}
Vec3f operator*(float scalar, Vec3f vector) {return vector * scalar;}
Vec3f Vec3f::operator+(Vec3f addend) const {return copy() += addend;}
Vec3f Vec3f::operator-(Vec3f subtrahend) const {return copy() -= subtrahend;}
Vec3f Vec3f::operator&(Vec3f multiplier) const {return copy() &= multiplier;}
float Vec3f::operator*(Vec3f multiplier) const {
return x * multiplier.x
+ y * multiplier.y
+ z * multiplier.z;
}
// Unary operations
Vec3f Vec3f::operator-() const {return -1 * *this;}
float Vec3f::norm() const {return sqrt(x*x + y*y + z*z);}
Vec3f Vec3f::normal() const {return *this / norm();}
| 25.52
| 77
| 0.630408
|
ei14
|
45382cb1d1d0ba807d163bc1cb1d314da6852610
| 3,806
|
cpp
|
C++
|
Source/10.0.18362.0/ucrt/mbstring/mbsdec.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | 2
|
2021-01-27T10:19:30.000Z
|
2021-02-09T06:24:30.000Z
|
Source/10.0.18362.0/ucrt/mbstring/mbsdec.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | null | null | null |
Source/10.0.18362.0/ucrt/mbstring/mbsdec.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | 1
|
2021-01-27T10:19:36.000Z
|
2021-01-27T10:19:36.000Z
|
/***
*mbsdec.c - Move MBCS string pointer backward one charcter.
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
* Move MBCS string pointer backward one character.
*
*******************************************************************************/
#ifndef _MBCS
#error This file should only be compiled with _MBCS defined
#endif
#include <corecrt_internal.h>
#include <corecrt_internal_mbstring.h>
#include <locale.h>
#include <stddef.h>
/***
*_mbsdec - Move MBCS string pointer backward one charcter.
*
*Purpose:
* Move the supplied string pointer backwards by one
* character. MBCS characters are handled correctly.
*
*Entry:
* const unsigned char *string = pointer to beginning of string
* const unsigned char *current = current char pointer (legal MBCS boundary)
*
*Exit:
* Returns pointer after moving it.
* Returns nullptr if string >= current.
*
*Exceptions:
* Input parameters are validated. Refer to the validation section of the function.
*
*******************************************************************************/
extern "C" unsigned char * __cdecl _mbsdec_l(
const unsigned char *string,
const unsigned char *current,
_locale_t plocinfo
)
{
const unsigned char *temp;
/* validation section */
_VALIDATE_RETURN(string != nullptr, EINVAL, nullptr);
_VALIDATE_RETURN(current != nullptr, EINVAL, nullptr);
if (string >= current)
return(nullptr);
_LocaleUpdate _loc_update(plocinfo);
if (_loc_update.GetLocaleT()->mbcinfo->ismbcodepage == 0)
return (unsigned char *)--current;
temp = current - 1;
/* There used to be an optimisation here:
*
* If (current-1) returns true from _ismbblead, it is a trail byte, because
* current is a known character start point, and so current-1 would have to be a
* legal single byte MBCS character, which a lead byte is not. Therefore, if so,
* return (current-2) because it must be the trailbyte's lead.
*
* if ( _ismbblead(*temp) )
* return (unsigned char *)(temp - 1);
*
* But this is not a valid optimisation if you want to cope correctly with an
* MBCS string which is terminated by a leadbyte and a 0 byte, when you are passed
* an initial position pointing to the \0 at the end of the string.
*
* This optimisation is also invalid if you are passed a pointer to half-way
* through an MBCS pair.
*
* Neither of these are truly valid input conditions, but to ensure predictably
* correct behaviour in the presence of these conditions, we have removed
* the optimisation.
*/
/*
* It is unknown whether (current - 1) is a single byte character or a
* trail. Now decrement temp until
* a) The beginning of the string is reached, or
* b) A non-lead byte (either single or trail) is found.
* The difference between (current-1) and temp is the number of non-single
* byte characters preceding (current-1). There are two cases for this:
* a) (current - temp) is odd, and
* b) (current - temp) is even.
* If odd, then there are an odd number of "lead bytes" preceding the
* single/trail byte (current - 1), indicating that it is a trail byte.
* If even, then there are an even number of "lead bytes" preceding the
* single/trail byte (current - 1), indicating a single byte character.
*/
while ( (string <= --temp) && (_ismbblead_l(*temp, _loc_update.GetLocaleT())) )
;
return (unsigned char *)(current - 1 - ((current - temp) & 0x01) );
}
extern "C" unsigned char * (__cdecl _mbsdec)(
const unsigned char *string,
const unsigned char *current
)
{
return _mbsdec_l(string, current, nullptr);
}
| 34.6
| 88
| 0.64083
|
825126369
|
4539f7f1d006ae249eb8f841b2f0a897d401f16e
| 1,678
|
cpp
|
C++
|
Heap.cpp
|
Aman-Chopra/DataStructure-Algorithms
|
fc5ed6ebe97032200b93c1ade783d4a5ed2fdd25
|
[
"MIT"
] | null | null | null |
Heap.cpp
|
Aman-Chopra/DataStructure-Algorithms
|
fc5ed6ebe97032200b93c1ade783d4a5ed2fdd25
|
[
"MIT"
] | 3
|
2016-06-09T07:46:15.000Z
|
2017-05-06T07:56:18.000Z
|
Heap.cpp
|
Aman-Chopra/DataStructure-Algorithms
|
fc5ed6ebe97032200b93c1ade783d4a5ed2fdd25
|
[
"MIT"
] | 4
|
2016-06-09T07:14:37.000Z
|
2021-05-21T22:07:20.000Z
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int smallest = 0;
int largest = 0;
void max_heapify(vector<int> &v, int i, int *n)
{
int left = 2*i;
int right = 2*i+1;
if(left <= *n && v[left] > v[i])
largest = left;
else
largest = i;
if(right <= *n && v[right] > v[largest])
largest = right;
if(largest != i)
{
swap(v[i],v[largest]);
max_heapify(v,largest,n);
}
}
void min_heapify(vector<int> &v, int i, int *n)
{
int left = 2*i;
int right = 2*i+1;
if(left <= *n && v[left] < v[i])
smallest = left;
else
smallest = i;
if(right <= *n && v[right] < v[smallest])
smallest = right;
if(smallest != i)
{
swap(v[i],v[smallest]);
min_heapify(v,smallest,n);
}
}
void build_minheap(vector<int> &v, int *size)
{
for(int i=(*size)/2;i>=1;i--)
{
min_heapify(v,i,size);
}
}
void build_maxheap(vector<int> &v, int *size)
{
for(int i = (*size)/2;i>=1;i--)
{
max_heapify(v,i,size);
}
}
void heap_sort(vector<int> &v, int *size)
{
int n = *size;
build_maxheap(v,size);
for(int i=n;i>=2;i--)
{
swap(v[1],v[i]);
n--;
max_heapify(v,1,&n);
}
}
int main()
{
cout<<"Enter the number of elements to store in the heap"<<endl;
int size;
cin>>size;
vector<int> heap(size+1);
for(int i=1;i<=size;i++)
{
cin>>heap[i];
}
cout<<"Heap Sort:"<<endl;
heap_sort(heap,&size);
for(int i=1;i<=size;i++)
{
cout<<heap[i]<<" ";
}
cout<<endl;
cout<<"Max Heap:"<<endl;
build_maxheap(heap, &size);
for(int i=1;i<=size;i++)
{
cout<<heap[i]<<" ";
}
cout<<endl;
cout<<"Min Heap:"<<endl;
build_minheap(heap, &size);
for(int i=1;i<=size;i++)
{
cout<<heap[i]<<" ";
}
cout<<endl;
return 0;
}
| 15.537037
| 65
| 0.573897
|
Aman-Chopra
|
453a1e6a515d4a67d7d37444149865b65fb7a952
| 4,785
|
cpp
|
C++
|
idlib-math/tests/idlib/tests/math/constants.cpp
|
egoboo/idlib
|
b27b9d3fe7357ecfe5f9dc71afe283a3d16b1ba8
|
[
"MIT"
] | 1
|
2021-07-30T14:02:43.000Z
|
2021-07-30T14:02:43.000Z
|
idlib-math/tests/idlib/tests/math/constants.cpp
|
egoboo/idlib
|
b27b9d3fe7357ecfe5f9dc71afe283a3d16b1ba8
|
[
"MIT"
] | null | null | null |
idlib-math/tests/idlib/tests/math/constants.cpp
|
egoboo/idlib
|
b27b9d3fe7357ecfe5f9dc71afe283a3d16b1ba8
|
[
"MIT"
] | 2
|
2017-01-27T16:53:08.000Z
|
2017-08-27T07:28:43.000Z
|
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// Idlib: A C++ utility library
// Copyright (C) 2017-2018 Michael Heilmann
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
///////////////////////////////////////////////////////////////////////////////////////////////////
#include "gtest/gtest.h"
#include "idlib/math.hpp"
namespace idlib::tests {
TEST(constants, pi_s)
{
auto x = idlib::pi<single>();
ASSERT_TRUE(!std::isnan(x));
ASSERT_TRUE(!std::isinf(x));
ASSERT_FLOAT_EQ(x, 3.1415926535897932384626433832795f);
}
TEST(constants, two_pi_s)
{
auto x = idlib::two_pi<single>();
ASSERT_TRUE(!std::isnan(x));
ASSERT_TRUE(!std::isinf(x));
ASSERT_FLOAT_EQ(x, 2.0f * 3.1415926535897932384626433832795f);
}
TEST(constants, inv_pi_s)
{
auto x = idlib::inv_pi<single>();
ASSERT_TRUE(!std::isnan(x));
ASSERT_TRUE(!std::isinf(x));
ASSERT_FLOAT_EQ(x, 1.0f / 3.1415926535897932384626433832795f); // GoogleTest tolerance is four ULP, ours was two ULP.
}
TEST(constants, inv_two_pi_s)
{
auto x = idlib::inv_two_pi<single>();
ASSERT_TRUE(!std::isnan(x));
ASSERT_TRUE(!std::isinf(x));
ASSERT_FLOAT_EQ(x, 1.0f / (2.0f * 3.1415926535897932384626433832795f));
}
TEST(constants, pi_over_two_s)
{
auto x = idlib::pi_over<single, 2>();
ASSERT_TRUE(!std::isnan(x));
ASSERT_TRUE(!std::isinf(x));
ASSERT_FLOAT_EQ(x, 3.1415926535897932384626433832795f / 2.0f);
}
TEST(constants, pi_over_four_s)
{
auto x = idlib::pi_over<single, 4>();
ASSERT_TRUE(!std::isnan(x));
ASSERT_TRUE(!std::isinf(x));
ASSERT_FLOAT_EQ(x, 3.1415926535897932384626433832795f / 4.0f);
}
TEST(constants, pi_d)
{
auto x = idlib::pi<double>();
ASSERT_TRUE(!std::isnan(x));
ASSERT_TRUE(!std::isinf(x));
ASSERT_FLOAT_EQ(x, 3.1415926535897932384626433832795);
}
TEST(constants, two_pi_d)
{
auto x = idlib::two_pi<double>();
ASSERT_TRUE(!std::isnan(x));
ASSERT_TRUE(!std::isinf(x));
ASSERT_FLOAT_EQ(x, 2.0 * 3.1415926535897932384626433832795);
}
TEST(constants, inv_pi_d)
{
auto x = idlib::inv_pi<double>();
ASSERT_TRUE(!std::isnan(x));
ASSERT_TRUE(!std::isinf(x));
ASSERT_FLOAT_EQ(x, 1.0 / 3.1415926535897932384626433832795);
}
TEST(constants, inv_two_pi_d)
{
auto x = idlib::inv_two_pi<double>();
ASSERT_TRUE(!std::isnan(x));
ASSERT_TRUE(!std::isinf(x));
ASSERT_FLOAT_EQ(x, 1.0 / (2.0 * 3.1415926535897932384626433832795));
}
TEST(constants, pi_over_two_d)
{
auto x = idlib::pi_over<double, 2>();
ASSERT_TRUE(!std::isnan(x));
ASSERT_TRUE(!std::isinf(x));
ASSERT_FLOAT_EQ(x, 3.1415926535897932384626433832795 / 2.0);
}
TEST(constants, pi_over_four_d)
{
auto x = idlib::pi_over<double, 4>();
ASSERT_TRUE(!std::isnan(x));
ASSERT_TRUE(!std::isinf(x));
ASSERT_FLOAT_EQ(x, 3.1415926535897932384626433832795 / 4.0);
}
TEST(constants, sqrt_two_s)
{
auto x = idlib::sqrt_two<single>();
ASSERT_TRUE(!std::isnan(x));
ASSERT_TRUE(!std::isinf(x));
ASSERT_FLOAT_EQ(x, std::sqrt(2.0f));
}
TEST(constants, inv_sqrt_two_s)
{
auto x = idlib::inv_sqrt_two<single>();
auto y = 1.0f / std::sqrt(2.0f);
ASSERT_TRUE(!std::isnan(x) && !std::isnan(y));
ASSERT_TRUE(!std::isinf(x) && !std::isinf(y));
ASSERT_TRUE(0.0 < x && 0.0 < y);
ASSERT_FLOAT_EQ(x, y);
}
TEST(constants, sqrt_two_d)
{
auto x = idlib::sqrt_two<double>();
auto y = std::sqrt(2.0);
ASSERT_TRUE(!std::isnan(x) && !std::isnan(y));
ASSERT_TRUE(!std::isinf(x) && !std::isinf(y));
ASSERT_TRUE(0.0 < x && 0.0 < y);
ASSERT_FLOAT_EQ(x, y);
}
TEST(constants, inv_sqrt_two_d)
{
double x = idlib::inv_sqrt_two<double>();
double y = 1.0 / std::sqrt(2.0);
ASSERT_TRUE(!std::isnan(x) && !std::isnan(y));
ASSERT_TRUE(!std::isinf(x) && !std::isinf(y));
ASSERT_TRUE(0.0 < x && 0.0 < y);
ASSERT_FLOAT_EQ(x, y);
}
} // namespace idlib::tests
| 29
| 121
| 0.63908
|
egoboo
|
453a2e4418602f71031fee4718f9682dd556d6c0
| 446
|
hpp
|
C++
|
include/lua_object.hpp
|
GhostInABottle/octopus_engine
|
50429e889493527bdc0e78b307937002e0f2c510
|
[
"BSD-2-Clause"
] | 3
|
2017-10-02T03:18:59.000Z
|
2020-11-01T09:21:28.000Z
|
include/lua_object.hpp
|
GhostInABottle/octopus_engine
|
50429e889493527bdc0e78b307937002e0f2c510
|
[
"BSD-2-Clause"
] | 2
|
2019-04-06T21:48:08.000Z
|
2020-05-22T23:38:54.000Z
|
include/lua_object.hpp
|
GhostInABottle/octopus_engine
|
50429e889493527bdc0e78b307937002e0f2c510
|
[
"BSD-2-Clause"
] | 1
|
2017-07-17T20:58:26.000Z
|
2017-07-17T20:58:26.000Z
|
#ifndef HPP_LUA_OBJECT
#define HPP_LUA_OBJECT
#include <string>
#include <memory>
#include "xd/vendor/sol/forward.hpp"
class Lua_Object {
public:
Lua_Object();
virtual ~Lua_Object();
void set_lua_property(const std::string& name, sol::stack_object value);
sol::main_object get_lua_property(const std::string& name);
private:
struct Impl;
friend struct Impl;
std::unique_ptr<Impl> pimpl;
};
#endif
| 22.3
| 77
| 0.690583
|
GhostInABottle
|
453a31f903a11270acdc2a5ad22af96280f0cdc3
| 838
|
cpp
|
C++
|
UVA/UVA11340.cpp
|
avillega/CompetitiveProgramming
|
f12c1a07417f8fc154ac5297889ca756b49f0f35
|
[
"Apache-2.0"
] | null | null | null |
UVA/UVA11340.cpp
|
avillega/CompetitiveProgramming
|
f12c1a07417f8fc154ac5297889ca756b49f0f35
|
[
"Apache-2.0"
] | null | null | null |
UVA/UVA11340.cpp
|
avillega/CompetitiveProgramming
|
f12c1a07417f8fc154ac5297889ca756b49f0f35
|
[
"Apache-2.0"
] | null | null | null |
#include <cstdio>
#include <string>
#include <map>
using namespace std;
typedef long long ll;
int main(){
map<char, int> charPrice;
char artLine[10100];
int T; scanf("%d\n", &T);
int N;
ll totalCents;
while(T--){
totalCents=0;
charPrice.clear();
scanf("%d\n", &N);
char c;
int val;
while(N--){
scanf("%c %d\n", &c, &val);
charPrice[c]=val;
}
scanf("%d\n", &N);
while(N--){
gets(artLine);
string line(artLine);
for(char c: line){
totalCents+=charPrice[c];
}
}
printf("%.2f$\n", totalCents/100.0 );
}
return 0;
}
| 23.942857
| 52
| 0.387828
|
avillega
|
453cb5d3bf24c54030f48b5001b55ae381b4d385
| 507
|
cc
|
C++
|
libcef/sqlite_diagnostics_stub.cc
|
svn2github/cef1
|
61d1537c697bec6265e02c9e9bb4c416b7b22db5
|
[
"BSD-3-Clause"
] | 18
|
2015-07-11T03:16:54.000Z
|
2019-01-19T12:10:38.000Z
|
libcef/sqlite_diagnostics_stub.cc
|
svn2github/cef
|
61d1537c697bec6265e02c9e9bb4c416b7b22db5
|
[
"BSD-3-Clause"
] | 2
|
2019-01-14T00:10:11.000Z
|
2019-02-03T08:19:11.000Z
|
libcef/sqlite_diagnostics_stub.cc
|
svn2github/cef1
|
61d1537c697bec6265e02c9e9bb4c416b7b22db5
|
[
"BSD-3-Clause"
] | 9
|
2015-01-08T01:07:25.000Z
|
2018-03-05T03:52:04.000Z
|
// Copyright (c) 2012 The Chromium Embedded Framework 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 "content/public/common/url_constants.h"
namespace chrome {
// Used by ClearOnExitPolicy
const char kHttpScheme[] = "http";
const char kHttpsScheme[] = "https";
} // namespace chrome
namespace content {
// Used by ClearOnExitPolicy
const char kStandardSchemeSeparator[] = "://";
} // namespace content
| 24.142857
| 80
| 0.737673
|
svn2github
|
453d0e2d0c29f82be0ecfb636cb3150dbe88e579
| 1,000
|
cpp
|
C++
|
tools/EncoderTemplate/Encoder.cpp
|
EmilianC/Jewel3D
|
ce11aa686ab35d4989f018c948b26abed6637d77
|
[
"MIT"
] | 30
|
2017-02-02T01:57:13.000Z
|
2020-07-04T04:38:20.000Z
|
tools/EncoderTemplate/Encoder.cpp
|
EmilianC/Jewel3D
|
ce11aa686ab35d4989f018c948b26abed6637d77
|
[
"MIT"
] | null | null | null |
tools/EncoderTemplate/Encoder.cpp
|
EmilianC/Jewel3D
|
ce11aa686ab35d4989f018c948b26abed6637d77
|
[
"MIT"
] | 10
|
2017-07-10T01:31:54.000Z
|
2020-01-13T20:38:57.000Z
|
#include "Encoder.h"
#define CURRENT_VERSION 1
Encoder::Encoder()
: gem::Encoder(CURRENT_VERSION)
{
}
gem::ConfigTable Encoder::GetDefault() const
{
gem::ConfigTable defaultConfig;
defaultConfig.SetValue("version", CURRENT_VERSION);
// Any default values for a new asset can be added to metadata here.
return defaultConfig;
}
bool Encoder::Validate(const gem::ConfigTable& metadata, unsigned loadedVersion) const
{
switch (loadedVersion)
{
case 1:
// Check the presence of your metadata fields here.
// Also ensure that they have correct values.
//...
if (metadata.GetSize() != 1)
{
gem::Error("Incorrect number of value entries.");
return false;
}
}
return true;
}
bool Encoder::Convert(std::string_view source, std::string_view destination, const gem::ConfigTable& metadata) const
{
// Load the source file and output the built data to the destination folder.
// The conversion should be done using the properties inside the metadata.
//...
return true;
}
| 21.276596
| 116
| 0.725
|
EmilianC
|
45423747d3b937f5418714dac6ac022f087f6b9e
| 3,742
|
cpp
|
C++
|
src/FEM/FEM1DApp.cpp
|
Jerry-Shen0527/Numerical
|
0bd6b630ac450caa0642029792ab348867d2390d
|
[
"MIT"
] | null | null | null |
src/FEM/FEM1DApp.cpp
|
Jerry-Shen0527/Numerical
|
0bd6b630ac450caa0642029792ab348867d2390d
|
[
"MIT"
] | null | null | null |
src/FEM/FEM1DApp.cpp
|
Jerry-Shen0527/Numerical
|
0bd6b630ac450caa0642029792ab348867d2390d
|
[
"MIT"
] | null | null | null |
#include <FEM/FEM1DApp.hpp>
Float StaticFEM1DApp::GradientSelfInnerProduct(int i, int j)
{
std::vector<int> i_id, j_id;
auto i_mesh = IdxToMesh(i, i_id);
auto j_mesh = IdxToMesh(j, j_id);
Float ret = 0;
for (int a = 0; a < i_mesh.size(); ++a)
{
for (int b = 0; b < j_mesh.size(); ++b)
{
if (i_mesh[a] == j_mesh[b])
{
auto sub_interval = interval.SubInterval(i_mesh[a]);
ret += WeightedL2InnerProduct(sub_interval.remap(ShapeFunctions[i_id[a]]),
sub_interval.remap(ShapeFunctionGradients[j_id[b]],
1.0 / sub_interval.length()), b_func, sub_interval);
}
}
}
return ret;
}
Float StaticFEM1DApp::GradientInnerProduct(int i, int j)
{
std::vector<int> i_id, j_id;
auto i_mesh = IdxToMesh(i, i_id);
auto j_mesh = IdxToMesh(j, j_id);
Float ret = 0;
for (int a = 0; a < i_mesh.size(); ++a)
{
for (int b = 0; b < j_mesh.size(); ++b)
{
if (i_mesh[a] == j_mesh[b])
{
auto sub_interval = interval.SubInterval(i_mesh[a]);
ret += WeightedL2InnerProduct(
sub_interval.remap(ShapeFunctionGradients[i_id[a]], 1.0 / sub_interval.length()),
sub_interval.remap(ShapeFunctionGradients[j_id[b]], 1.0 / sub_interval.length()), d_func,
sub_interval);
}
}
}
return ret;
}
Float StaticFEM1DApp::SelfInnerProduct(int i, int j)
{
std::vector<int> i_id, j_id;
auto i_mesh = IdxToMesh(i, i_id);
auto j_mesh = IdxToMesh(j, j_id);
Float ret = 0;
for (int a = 0; a < i_mesh.size(); ++a)
{
for (int b = 0; b < j_mesh.size(); ++b)
{
if (i_mesh[a] == j_mesh[b])
{
auto sub_interval = interval.SubInterval(i_mesh[a]);
ret += WeightedL2InnerProduct(sub_interval.remap(ShapeFunctions[i_id[a]]),
sub_interval.remap(ShapeFunctions[j_id[b]]), c_func, sub_interval);
}
}
}
return ret;
}
Float StaticFEM1DApp::RHSInnerProduct(int i)
{
std::vector<int> func_id;
auto i_mesh = IdxToMesh(i, func_id);
Float ret = 0;
for (int a = 0; a < func_id.size(); ++a)
{
auto sub_interval = interval.SubInterval(i_mesh[a]);
ret += L2InnerProduct(sub_interval.remap(ShapeFunctions[func_id[a]]), RHS_func, sub_interval);
}
return ret;
}
std::vector<int> StaticFEM1DApp::RelatedFuncIdx(int idx)
{
std::vector<int> ret;
std::vector<int> foo_id;
auto MeshIds = IdxToMesh(idx, foo_id);
std::set<int> set_ret;
for (auto mesh_id : MeshIds)
{
for (int i = 0; i < ShapeFunctions.size(); ++i)
{
int idx;
if (MeshToIdx(mesh_id, i, idx))
{
set_ret.emplace(idx);
}
}
}
ret.assign(set_ret.begin(), set_ret.end());
return ret;
}
Float StaticFEM1DApp::Value(Float x)
{
if (mat_size == 0)
{
return 0;
}
Float ret = 0;
for (int i = 0; i < interval.GetPartitionCount(); ++i)
{
auto sub_interval = interval.SubInterval(i);
if (sub_interval.Inside(x))
{
for (int j = 0; j < ShapeFunctions.size(); ++j)
{
int idx;
if (MeshToIdx(i, j, idx))
{
ret += sub_interval.remap(ShapeFunctions[j])(x) * rst(idx);
}
}
}
}
return ret;
}
std::function<Float(Float)> LagrangianBase(int N, int i)
{
std::vector<Point2d> points(N + 1);
Float h = 1.0 / N;
for (int i = 0; i <= N; ++i)
{
points[i] = Point2d(i * h, 0);
}
points[i] = Point2d(i * h, 1.0);
return LagrangianPolynomial(points);
}
std::function<Float(Float)> LagrangianBaseDerivative(int N, int i)
{
return [=](Float x)
{
Float ret = 0;
for (int missing = 0; missing <= N; ++missing)
{
if (missing != i)
{
std::vector<Point2d> points;
Float h = 1.0 / N;
for (int j = 0; j <= N; ++j)
if (j != missing)
if (j == i)
points.emplace_back(j * h, 1.0);
else
points.emplace_back(j * h, 0.0);
ret += LagrangianPolynomial(points)(x) / (h * (i - missing));
}
}
return ret;
};
}
| 21.022472
| 96
| 0.617584
|
Jerry-Shen0527
|
45462edbf1008c8ccc83843d664762d8e82e0909
| 2,396
|
cpp
|
C++
|
node_modules/lzz-gyp/lzz-source/smtc_PrintNsFuncDefn.cpp
|
SuperDizor/dizornator
|
9f57dbb3f6af80283b4d977612c95190a3d47900
|
[
"ISC"
] | 3
|
2019-09-18T16:44:33.000Z
|
2021-03-29T13:45:27.000Z
|
node_modules/lzz-gyp/lzz-source/smtc_PrintNsFuncDefn.cpp
|
SuperDizor/dizornator
|
9f57dbb3f6af80283b4d977612c95190a3d47900
|
[
"ISC"
] | null | null | null |
node_modules/lzz-gyp/lzz-source/smtc_PrintNsFuncDefn.cpp
|
SuperDizor/dizornator
|
9f57dbb3f6af80283b4d977612c95190a3d47900
|
[
"ISC"
] | 2
|
2019-03-29T01:06:38.000Z
|
2019-09-18T16:44:34.000Z
|
// smtc_PrintNsFuncDefn.cpp
//
#include "smtc_PrintNsFuncDefn.h"
// semantic
#include "smtc_FuncDefn.h"
#include "smtc_IsNameQual.h"
#include "smtc_IsNsEnclUnmd.h"
#include "smtc_Output.h"
#include "smtc_PrintFuncDefn.h"
// config
#include "conf_Config.h"
#define LZZ_INLINE inline
namespace
{
using namespace smtc;
}
namespace
{
struct Printer
{
FuncDefnPtr const & func_defn;
NsPtr const & ns;
bool is_decl;
void printDecl (FilePtr const & file);
void printDefn (FilePtr const & file, SectionKind skind = BODY_SECTION);
public:
explicit Printer (FuncDefnPtr const & func_defn, NsPtr const & ns);
~ Printer ();
};
}
namespace
{
void Printer::printDecl (FilePtr const & file)
{
PrintFuncDecl printer;
printer.is_decl = is_decl;
printer.not_inline = true;
printer.print (file, DECLARATION_SECTION, func_defn, ns);
is_decl = false;
}
}
namespace
{
void Printer::printDefn (FilePtr const & file, SectionKind skind)
{
PrintFuncDefn printer;
printer.is_decl = is_decl;
printer.print (file, skind, func_defn, ns);
}
}
namespace
{
LZZ_INLINE Printer::Printer (FuncDefnPtr const & func_defn, NsPtr const & ns)
: func_defn (func_defn), ns (ns), is_decl (true)
{}
}
namespace
{
Printer::~ Printer ()
{}
}
namespace smtc
{
void printNsFuncDefn (Output & out, FuncDefnPtr const & func_defn, NsPtr const & ns)
{
Printer printer (func_defn, ns);
bool is_qual = isNameQual (func_defn->getName ());
if (func_defn->isStatic () || isNsEnclUnmd (ns))
{
if (! is_qual)
{
printer.printDecl (out.getSrcFile ());
}
printer.printDefn (out.getSrcFile ());
}
else
{
if (! is_qual)
{
printer.printDecl (out.getHdrFile ());
}
if (func_defn->isInline ())
{
if (conf::getOptionValue (conf::opt_inl_inl))
{
printer.printDefn (out.getHdrFile (), INLINE_BODY_SECTION);
printer.printDefn (out.getSrcFile (), INLINE_BODY_SECTION);
}
else if (conf::getOptionValue (conf::opt_inl))
{
printer.printDefn (out.getInlFile ());
}
else
{
printer.printDefn (out.getHdrFile ());
}
}
else
{
printer.printDefn (out.getSrcFile ());
}
}
}
}
#undef LZZ_INLINE
| 22.185185
| 86
| 0.613523
|
SuperDizor
|
454d3b48038a9b52fc0dc94df440bdb4ea5d76e7
| 8,056
|
cpp
|
C++
|
src/Nodes/Default_Nodes/Generators/chaoticOscillator.cpp
|
PlaymodesStudio/ofxOceanode
|
400df6d49c4b29bc6916e4a045145e935beff4e0
|
[
"MIT"
] | 31
|
2018-04-20T13:47:38.000Z
|
2021-12-26T04:32:24.000Z
|
src/Nodes/Default_Nodes/Generators/chaoticOscillator.cpp
|
PlaymodesStudio/ofxOceanode
|
400df6d49c4b29bc6916e4a045145e935beff4e0
|
[
"MIT"
] | 25
|
2018-02-19T17:15:32.000Z
|
2020-01-05T01:51:00.000Z
|
src/Nodes/Default_Nodes/Generators/chaoticOscillator.cpp
|
PlaymodesStudio/ofxOceanode
|
400df6d49c4b29bc6916e4a045145e935beff4e0
|
[
"MIT"
] | 5
|
2018-09-25T18:37:23.000Z
|
2021-01-21T16:26:16.000Z
|
//
// chaoticOscillator.cpp
// example-basic
//
// Created by Eduard Frigola Bagué on 02/03/2020.
//
#include "chaoticOscillator.h"
void chaoticOscillator::setup(){
color = ofColor(0, 200, 255);
oldPhasor = vector<float>(1, 0);
seedChanged = vector<bool>(true);
baseChOsc.resize(1);
result.resize(1);
listeners.push(phaseOffset_Param.newListener([this](vector<float> &val){
if(val.size() != baseChOsc.size() && index_Param->size() == 1 && phasorIn->size() == 1){
resize(val.size());
}
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].phaseOffset_Param = getValueForPosition(val, i);
}
}));
listeners.push(randomAdd_Param.newListener([this](vector<float> &val){
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].randomAdd_Param = getValueForPosition(val, i);
}
}));
listeners.push(scale_Param.newListener([this](vector<float> &val){
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].scale_Param = getValueForPosition(val, i);
}
}));
listeners.push(offset_Param.newListener([this](vector<float> &val){
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].offset_Param = getValueForPosition(val, i);
}
}));
listeners.push(pow_Param.newListener([this](vector<float> &val){
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].pow_Param = getValueForPosition(val, i);
baseChOsc[i].modulateNewRandom();
}
}));
listeners.push(biPow_Param.newListener([this](vector<float> &val){
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].biPow_Param = getValueForPosition(val, i);
baseChOsc[i].modulateNewRandom();
}
}));
listeners.push(quant_Param.newListener([this](vector<int> &val){
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].quant_Param = getValueForPosition(val, i);
baseChOsc[i].modulateNewRandom();
}
}));
listeners.push(pulseWidth_Param.newListener([this](vector<float> &val){
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].pulseWidth_Param = getValueForPosition(val, i);
}
}));
listeners.push(skew_Param.newListener([this](vector<float> &val){
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].skew_Param = getValueForPosition(val, i);
}
}));
listeners.push(amplitude_Param.newListener([this](vector<float> &val){
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].amplitude_Param = getValueForPosition(val, i);
}
}));
listeners.push(invert_Param.newListener([this](vector<float> &val){
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].invert_Param = getValueForPosition(val, i);
}
}));
listeners.push(roundness_Param.newListener([this](vector<float> &val){
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].roundness_Param = getValueForPosition(val, i);
}
}));
listeners.push(index_Param.newListener([this](vector<float> &val){
if(val.size() != baseChOsc.size()){
resize(val.size());
}
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].setIndexNormalized(getValueForPosition(val, i));
}
seedChanged = vector<bool>(baseChOsc.size(), true);
}));
listeners.push(customDiscreteDistribution_Param.newListener([this](vector<float> &val){
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].customDiscreteDistribution = val;
}
}));
listeners.push(seed.newListener([this](vector<int> &val){
seedChanged = vector<bool>(baseChOsc.size(), true);
}));
listeners.push(length_Param.newListener([this](vector<float> &val){
for(int i = 0; i < baseChOsc.size(); i++){
baseChOsc[i].length_Param = getValueForPosition(val, i);
}
seedChanged = vector<bool>(baseChOsc.size(), true);
}));
addParameter(phasorIn.set("Phase", {0}, {0}, {1}));
addParameter(index_Param.set("Index", {0}, {0}, {1}));
addParameter(length_Param.set("Length", {1}, {0}, {100}));
addParameter(phaseOffset_Param.set("Ph.Off", {0}, {0}, {1}));
addParameter(roundness_Param.set("Round", {0.5}, {0}, {1}));
addParameter(pulseWidth_Param.set("PulseW", {.5}, {0}, {1}));
addParameter(skew_Param.set("Skew", {0}, {-1}, {1}));
addParameter(pow_Param.set("Pow", {0}, {-1}, {1}));
addParameter(biPow_Param.set("BiPow", {0}, {-1}, {1}));
addParameter(quant_Param.set("Quant", {255}, {2}, {255}));
addParameter(customDiscreteDistribution_Param.set("Dist" , {-1}, {0}, {1}));
addParameter(seed.set("Seed", {-1}, {(INT_MIN+1)/2}, {(INT_MAX-1)/2}));
addParameter(randomAdd_Param.set("Rnd Add", {0}, {-.5}, {.5}));
addParameter(scale_Param.set("Scale", {1}, {0}, {2}));
addParameter(offset_Param.set("Offset", {0}, {-1}, {1}));
addParameter(amplitude_Param.set("Fader", {1}, {0}, {1}));
addParameter(invert_Param.set("Invert", {0}, {0}, {1}));
addOutputParameter(output.set("Output", {0}, {0}, {1}));
listeners.push(phasorIn.newListener(this, &chaoticOscillator::phasorInListener));
desiredLength = 1;
}
void chaoticOscillator::resize(int newSize){
baseChOsc.resize(newSize);
result.resize(newSize);
phaseOffset_Param = phaseOffset_Param;
roundness_Param = roundness_Param;
pulseWidth_Param = pulseWidth_Param;
skew_Param = skew_Param;
randomAdd_Param = randomAdd_Param;
scale_Param = scale_Param;
offset_Param = offset_Param;
pow_Param = pow_Param;
biPow_Param = biPow_Param;
quant_Param = quant_Param;
amplitude_Param = amplitude_Param;
invert_Param = invert_Param;
customDiscreteDistribution_Param = customDiscreteDistribution_Param;
seed = seed;
seedChanged = vector<bool>(baseChOsc.size(), true);
length_Param.setMax({static_cast<float>(newSize)});
string name = length_Param.getName();
parameterChangedMinMax.notify(name);
if(length_Param->size() == 1){
if(desiredLength != -1 && desiredLength <= newSize){
length_Param = vector<float>(1, desiredLength);
desiredLength = -1;
}
else{
if(length_Param->at(0) > length_Param.getMax()[0]){
desiredLength = length_Param->at(0);
length_Param = vector<float>(1, length_Param.getMax()[0]);
}
length_Param = length_Param;
}
}
};
void chaoticOscillator::presetRecallBeforeSettingParameters(ofJson &json){
if(json.count("Length") == 1){
desiredLength = (json["Length"]);
}
}
void chaoticOscillator::phasorInListener(vector<float> &phasor){
if(phasor.size() != baseChOsc.size() && phasor.size() != 1 && index_Param->size() == 1){
resize(phasor.size());
}
if(accumulate(seedChanged.begin(), seedChanged.end(), 0) != 0){
for(int i = 0; i < baseChOsc.size(); i++){
if(seedChanged[i] && getValueForPosition(phasor, i) < getValueForPosition(oldPhasor, i)){
if(getValueForPosition(seed.get(), i) == 0){
baseChOsc[i].deactivateSeed();
}else{
if(seed->size() == 1 && seed->at(0) < 0){
baseChOsc[i].setSeed(seed->at(0) - (10*getValueForPosition(index_Param.get(), i)*baseChOsc.size()));
}else{
baseChOsc[i].setSeed(getValueForPosition(seed.get(), i));
baseChOsc[i].computeFunc(0);
}
}
seedChanged[i] = false;
}
}
}
for(int i = 0; i < baseChOsc.size(); i++){
result[i] = baseChOsc[i].computeFunc(getValueForPosition(phasor, i));
}
oldPhasor = phasor;
output = result;
}
| 39.881188
| 124
| 0.585775
|
PlaymodesStudio
|
4550737c359bb091ea8ee21f4d83027f6d7f4768
| 709
|
cpp
|
C++
|
main.cpp
|
rivergillis/sdl2-starter
|
cbfcb7249390a131b0cf2d0f49fe09e5e2f63eb2
|
[
"MIT"
] | null | null | null |
main.cpp
|
rivergillis/sdl2-starter
|
cbfcb7249390a131b0cf2d0f49fe09e5e2f63eb2
|
[
"MIT"
] | null | null | null |
main.cpp
|
rivergillis/sdl2-starter
|
cbfcb7249390a131b0cf2d0f49fe09e5e2f63eb2
|
[
"MIT"
] | null | null | null |
#include "common.h"
#include "sdl_viewer.h"
#include "image.h"
constexpr int w = 640;
constexpr int h = 480;
int main(void) {
SDLViewer viewer("Hello World", w, h);
Image img(w, h);
img.SetAll({248, 240, 227}); // Honda championship white background
bool quit = false;
int i = 0;
while (!quit) {
// Animate some colorful diagonal lines.
img.SetPixel(i % w, i % h, {static_cast<uint8_t>(i % 256),
static_cast<uint8_t>(i*2 % 256),
static_cast<uint8_t>(i*3 % 256)});
i++;
viewer.SetImage(img);
auto events = viewer.Update();
for (const auto& e : events) {
if (e.type == SDL_QUIT) {
quit = true;
break;
}
}
}
return 0;
}
| 20.852941
| 70
| 0.57969
|
rivergillis
|
45523fb4a50faa6e4e59570ed6c5b2e26dfd7279
| 3,757
|
hpp
|
C++
|
src/riscv_devices.hpp
|
msyksphinz/swimmer_riscv
|
065cf3e0dcdcd00cd9bd976285a307d371253ba9
|
[
"BSD-3-Clause"
] | 33
|
2015-08-23T02:45:07.000Z
|
2019-11-06T23:34:51.000Z
|
src/riscv_devices.hpp
|
msyksphinz-self/swimmer_riscv
|
065cf3e0dcdcd00cd9bd976285a307d371253ba9
|
[
"BSD-3-Clause"
] | 11
|
2015-10-11T15:52:42.000Z
|
2019-09-20T14:30:35.000Z
|
src/riscv_devices.hpp
|
msyksphinz/swimmer_riscv
|
065cf3e0dcdcd00cd9bd976285a307d371253ba9
|
[
"BSD-3-Clause"
] | 5
|
2015-02-14T10:07:44.000Z
|
2019-09-20T06:37:38.000Z
|
/*
* Copyright (c) 2015, msyksphinz
* 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 copyright holder 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 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.
*/
#pragma once
#include <vector>
#include "mem_body.hpp"
#include "riscv_pe_thread.hpp"
// static uint8_t DEVICE (uint64_t command) { return command >> 56; }
// static uint8_t COMMAND(uint64_t command) { return command >> 48; }
// static uint64_t PAYLOAD(uint64_t command) { return command << 16 >> 16; }
#define DEVICE(cmd) ((cmd >> 56) & 0xff)
#define COMMAND(cmd) ((cmd >> 48) & 0xff)
#define PAYLOAD(cmd) (cmd & 0xffffffffffffULL)
#define MAKE_COMMAND(dev, cmd, payload) (static_cast<uint64_t>(dev) << 56 | static_cast<uint64_t>(cmd) << 48 | static_cast<uint64_t>(payload) & 0x0ffff)
class RiscvDevice_t
{
uint32_t m_dev_id;
RiscvPeThread *m_pe_thread;
public:
virtual void HandleCommand (UDWord_t cmd) = 0;
virtual void Tick() = 0;
RiscvPeThread *GetPeThread() { return m_pe_thread; }
RiscvDevice_t (uint32_t dev_id, RiscvPeThread *pe_thread) :
m_dev_id(dev_id), m_pe_thread(pe_thread) {}
virtual ~RiscvDevice_t () {}
inline uint32_t GetDevId() { return m_dev_id; }
};
class RiscvMMDevice_t
{
private:
Addr_t m_base_addr;
Addr_t m_size;
public:
RiscvPeThread *m_pe_thread;
virtual MemResult Load (Addr_t addr, size_t len, Byte_t *data) = 0;
virtual MemResult Store (Addr_t addr, size_t size, Byte_t *data) = 0;
Addr_t GetBaseAddr () { return m_base_addr; }
Addr_t GetSize () { return m_size; }
RiscvMMDevice_t (RiscvPeThread *pe_thread, Addr_t base_addr, Addr_t size) {
m_pe_thread = pe_thread;
m_base_addr = base_addr;
m_size = size;
}
virtual ~RiscvMMDevice_t () {}
};
class RiscvDeviceList_t
{
private:
std::vector<RiscvDevice_t*> m_devices;
public:
void RegisterDevice (RiscvDevice_t* dev) {
m_devices.push_back(dev);
}
void HandleCommand (UDWord_t cmd) {
if (DEVICE(cmd) >= m_devices.size()) {
fprintf (stderr, "<Info: HandleCommand not found %ld>\n", DEVICE(cmd));
return;
}
m_devices[DEVICE(cmd)]->HandleCommand(cmd);
}
void Tick () {
for (RiscvDevice_t *device : m_devices) {
device->Tick();
}
}
~RiscvDeviceList_t ()
{
for (RiscvDevice_t *device : m_devices) {
delete device;
}
}
};
| 31.571429
| 152
| 0.711206
|
msyksphinz
|
4553d6ae9ba2a19514b48790bd32758952cea8fc
| 9,001
|
cpp
|
C++
|
platform_linux.cpp
|
Vector35/platform-linux
|
fd71fca50ba193517df0f7c828d824f57fbc158f
|
[
"Apache-2.0"
] | null | null | null |
platform_linux.cpp
|
Vector35/platform-linux
|
fd71fca50ba193517df0f7c828d824f57fbc158f
|
[
"Apache-2.0"
] | 1
|
2021-06-25T18:49:42.000Z
|
2021-06-25T18:49:42.000Z
|
platform_linux.cpp
|
Vector35/platform-linux
|
fd71fca50ba193517df0f7c828d824f57fbc158f
|
[
"Apache-2.0"
] | null | null | null |
#include "binaryninjaapi.h"
using namespace BinaryNinja;
using namespace std;
class LinuxX86Platform: public Platform
{
public:
LinuxX86Platform(Architecture* arch): Platform(arch, "linux-x86")
{
Ref<CallingConvention> cc;
cc = arch->GetCallingConventionByName("cdecl");
if (cc)
{
RegisterDefaultCallingConvention(cc);
RegisterCdeclCallingConvention(cc);
}
cc = arch->GetCallingConventionByName("regparm");
if (cc)
RegisterFastcallCallingConvention(cc);
cc = arch->GetCallingConventionByName("stdcall");
if (cc)
RegisterStdcallCallingConvention(cc);
cc = arch->GetCallingConventionByName("linux-syscall");
if (cc)
SetSystemCallConvention(cc);
}
};
class LinuxPpc32Platform: public Platform
{
public:
LinuxPpc32Platform(Architecture* arch, const std::string& name): Platform(arch, name)
{
Ref<CallingConvention> cc;
cc = arch->GetCallingConventionByName("svr4");
if (cc)
{
RegisterDefaultCallingConvention(cc);
}
cc = arch->GetCallingConventionByName("linux-syscall");
if (cc)
SetSystemCallConvention(cc);
}
};
class LinuxPpc64Platform: public Platform
{
public:
LinuxPpc64Platform(Architecture* arch, const std::string& name): Platform(arch, name)
{
Ref<CallingConvention> cc;
cc = arch->GetCallingConventionByName("svr4");
if (cc)
{
RegisterDefaultCallingConvention(cc);
}
cc = arch->GetCallingConventionByName("linux-syscall");
if (cc)
SetSystemCallConvention(cc);
}
};
class LinuxX64Platform: public Platform
{
public:
LinuxX64Platform(Architecture* arch): Platform(arch, "linux-x86_64")
{
Ref<CallingConvention> cc;
cc = arch->GetCallingConventionByName("sysv");
if (cc)
{
RegisterDefaultCallingConvention(cc);
RegisterCdeclCallingConvention(cc);
RegisterFastcallCallingConvention(cc);
RegisterStdcallCallingConvention(cc);
}
cc = arch->GetCallingConventionByName("linux-syscall");
if (cc)
SetSystemCallConvention(cc);
}
};
class LinuxArmv7Platform: public Platform
{
public:
LinuxArmv7Platform(Architecture* arch, const std::string& name): Platform(arch, name)
{
Ref<CallingConvention> cc;
cc = arch->GetCallingConventionByName("cdecl");
if (cc)
{
RegisterDefaultCallingConvention(cc);
RegisterCdeclCallingConvention(cc);
RegisterFastcallCallingConvention(cc);
RegisterStdcallCallingConvention(cc);
}
cc = arch->GetCallingConventionByName("linux-syscall");
if (cc)
SetSystemCallConvention(cc);
}
};
class LinuxArm64Platform: public Platform
{
public:
LinuxArm64Platform(Architecture* arch): Platform(arch, "linux-aarch64")
{
Ref<CallingConvention> cc;
cc = arch->GetCallingConventionByName("cdecl");
if (cc)
{
RegisterDefaultCallingConvention(cc);
RegisterCdeclCallingConvention(cc);
RegisterFastcallCallingConvention(cc);
RegisterStdcallCallingConvention(cc);
}
cc = arch->GetCallingConventionByName("linux-syscall");
if (cc)
SetSystemCallConvention(cc);
}
};
class LinuxMipsPlatform: public Platform
{
public:
LinuxMipsPlatform(Architecture* arch, const std::string& name): Platform(arch, name)
{
Ref<CallingConvention> cc;
cc = arch->GetCallingConventionByName("o32");
if (cc)
{
RegisterDefaultCallingConvention(cc);
RegisterCdeclCallingConvention(cc);
RegisterFastcallCallingConvention(cc);
RegisterStdcallCallingConvention(cc);
}
cc = arch->GetCallingConventionByName("linux-syscall");
if (cc)
SetSystemCallConvention(cc);
}
};
extern "C"
{
BN_DECLARE_CORE_ABI_VERSION
#ifndef DEMO_VERSION
BINARYNINJAPLUGIN void CorePluginDependencies()
{
AddOptionalPluginDependency("arch_x86");
AddOptionalPluginDependency("arch_armv7");
AddOptionalPluginDependency("arch_arm64");
AddOptionalPluginDependency("arch_mips");
AddOptionalPluginDependency("arch_ppc");
}
#endif
#ifdef DEMO_VERSION
bool LinuxPluginInit()
#else
BINARYNINJAPLUGIN bool CorePluginInit()
#endif
{
Ref<Architecture> x86 = Architecture::GetByName("x86");
if (x86)
{
Ref<Platform> platform;
platform = new LinuxX86Platform(x86);
Platform::Register("linux", platform);
// Linux binaries sometimes have an OS identifier of zero, even though 3 is the correct one
BinaryViewType::RegisterPlatform("ELF", 0, x86, platform);
BinaryViewType::RegisterPlatform("ELF", 3, x86, platform);
}
Ref<Architecture> x64 = Architecture::GetByName("x86_64");
if (x64)
{
Ref<Platform> platform;
platform = new LinuxX64Platform(x64);
Platform::Register("linux", platform);
// Linux binaries sometimes have an OS identifier of zero, even though 3 is the correct one
BinaryViewType::RegisterPlatform("ELF", 0, x64, platform);
BinaryViewType::RegisterPlatform("ELF", 3, x64, platform);
}
Ref<Architecture> armv7 = Architecture::GetByName("armv7");
Ref<Architecture> armv7eb = Architecture::GetByName("armv7eb");
Ref<Architecture> thumb2 = Architecture::GetByName("thumb2");
Ref<Architecture> thumb2eb = Architecture::GetByName("thumb2eb");
if (armv7 && armv7eb && thumb2 && thumb2eb)
{
Ref<Platform> armPlatform, armebPlatform, thumbPlatform, thumbebPlatform;
armPlatform = new LinuxArmv7Platform(armv7, "linux-armv7");
armebPlatform = new LinuxArmv7Platform(armv7eb, "linux-armv7eb");
thumbPlatform = new LinuxArmv7Platform(thumb2, "linux-thumb2");
thumbebPlatform = new LinuxArmv7Platform(thumb2eb, "linux-thumb2eb");
armPlatform->AddRelatedPlatform(thumb2, thumbPlatform);
armebPlatform->AddRelatedPlatform(thumb2eb, thumbebPlatform);
thumbPlatform->AddRelatedPlatform(armv7, armPlatform);
thumbebPlatform->AddRelatedPlatform(armv7eb, armebPlatform);
Platform::Register("linux", armPlatform);
Platform::Register("linux", thumbPlatform);
Platform::Register("linux", armebPlatform);
Platform::Register("linux", thumbebPlatform);
// Linux binaries sometimes have an OS identifier of zero, even though 3 is the correct one
BinaryViewType::RegisterPlatform("ELF", 0, armv7, armPlatform);
BinaryViewType::RegisterPlatform("ELF", 3, armv7, armPlatform);
BinaryViewType::RegisterPlatform("ELF", 0, armv7eb, armebPlatform);
BinaryViewType::RegisterPlatform("ELF", 3, armv7eb, armebPlatform);
}
Ref<Architecture> arm64 = Architecture::GetByName("aarch64");
if (arm64)
{
Ref<Platform> platform;
platform = new LinuxArm64Platform(arm64);
Platform::Register("linux", platform);
// Linux binaries sometimes have an OS identifier of zero, even though 3 is the correct one
BinaryViewType::RegisterPlatform("ELF", 0, arm64, platform);
BinaryViewType::RegisterPlatform("ELF", 3, arm64, platform);
}
Ref<Architecture> ppc = Architecture::GetByName("ppc");
Ref<Architecture> ppcle = Architecture::GetByName("ppc_le");
if (ppc && ppcle)
{
Ref<Platform> platform;
Ref<Platform> platformle;
platform = new LinuxPpc32Platform(ppc, "linux-ppc32");
platformle = new LinuxPpc32Platform(ppcle, "linux-ppc32_le");
Platform::Register("linux", platform);
Platform::Register("linux", platformle);
// Linux binaries sometimes have an OS identifier of zero, even though 3 is the correct one
BinaryViewType::RegisterPlatform("ELF", 0, ppc, platform);
BinaryViewType::RegisterPlatform("ELF", 3, ppc, platform);
BinaryViewType::RegisterPlatform("ELF", 0, ppcle, platformle);
BinaryViewType::RegisterPlatform("ELF", 3, ppcle, platformle);
}
Ref<Architecture> ppc64 = Architecture::GetByName("ppc64");
Ref<Architecture> ppc64le = Architecture::GetByName("ppc64_le");
if (ppc64 && ppc64le)
{
Ref<Platform> platform;
Ref<Platform> platformle;
platform = new LinuxPpc64Platform(ppc64, "linux-ppc64");
platformle = new LinuxPpc64Platform(ppc64le, "linux-ppc64_le");
Platform::Register("linux", platform);
Platform::Register("linux", platformle);
// Linux binaries sometimes have an OS identifier of zero, even though 3 is the correct one
BinaryViewType::RegisterPlatform("ELF", 0, ppc64, platform);
BinaryViewType::RegisterPlatform("ELF", 3, ppc64, platform);
BinaryViewType::RegisterPlatform("ELF", 0, ppc64le, platformle);
BinaryViewType::RegisterPlatform("ELF", 3, ppc64le, platformle);
}
Ref<Architecture> mipsel = Architecture::GetByName("mipsel32");
Ref<Architecture> mipseb = Architecture::GetByName("mips32");
if (mipsel && mipseb)
{
Ref<Platform> platformLE, platformBE;
platformLE = new LinuxMipsPlatform(mipsel, "linux-mipsel");
platformBE = new LinuxMipsPlatform(mipseb, "linux-mips");
Platform::Register("linux", platformLE);
Platform::Register("linux", platformBE);
// Linux binaries sometimes have an OS identifier of zero, even though 3 is the correct one
BinaryViewType::RegisterPlatform("ELF", 0, mipsel, platformLE);
BinaryViewType::RegisterPlatform("ELF", 0, mipseb, platformBE);
BinaryViewType::RegisterPlatform("ELF", 3, mipsel, platformLE);
BinaryViewType::RegisterPlatform("ELF", 3, mipseb, platformBE);
}
return true;
}
}
| 29.511475
| 94
| 0.736363
|
Vector35
|
4555a728416e55f68c46303cbf1c1a6c81eb918c
| 593
|
cpp
|
C++
|
SET & MAP/basic problem/Count-of-pairs-between-two-arrays-such-that-the-sums-are-distinct.cpp
|
Shiv-sharma-111/jubilant-sniffle
|
4cd1ce6fe08f8749f16e569b3a78f3b5576ebe17
|
[
"MIT"
] | null | null | null |
SET & MAP/basic problem/Count-of-pairs-between-two-arrays-such-that-the-sums-are-distinct.cpp
|
Shiv-sharma-111/jubilant-sniffle
|
4cd1ce6fe08f8749f16e569b3a78f3b5576ebe17
|
[
"MIT"
] | null | null | null |
SET & MAP/basic problem/Count-of-pairs-between-two-arrays-such-that-the-sums-are-distinct.cpp
|
Shiv-sharma-111/jubilant-sniffle
|
4cd1ce6fe08f8749f16e569b3a78f3b5576ebe17
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int T;
cin>>T;
while(T--)
{
int n1,n2;
cin>>n1>>n2;
int arr1[n1],arr2[n2];
for(int i=0;i<n1;i++)
{
cin>>arr1[i];
}
for(int i=0;i<n2;i++)
{
cin>>arr2[i];
}
int count=0,sum;
unordered_set<int> mp;
for(int i=0;i<n1;i++)
{
for(int j=0;j<n2;j++)
{
sum = arr1[i]+arr2[j];
mp.insert(sum);
}
}
//int k = mp.size();
cout<<mp.size()<<"\n";
}
return 0;
}
| 16.027027
| 35
| 0.468803
|
Shiv-sharma-111
|
455680b9155630f3e6d96be1a8de3c27928d49c0
| 517
|
hpp
|
C++
|
src/Exceptions/Exception.hpp
|
pokorj54/Command-line-calendar
|
de2c8a89917bd4cb69547427a6ec1bced218c5ad
|
[
"MIT"
] | null | null | null |
src/Exceptions/Exception.hpp
|
pokorj54/Command-line-calendar
|
de2c8a89917bd4cb69547427a6ec1bced218c5ad
|
[
"MIT"
] | null | null | null |
src/Exceptions/Exception.hpp
|
pokorj54/Command-line-calendar
|
de2c8a89917bd4cb69547427a6ec1bced218c5ad
|
[
"MIT"
] | null | null | null |
#ifndef Exception_785a62ec3213411cb4e442ee734c00cb
#define Exception_785a62ec3213411cb4e442ee734c00cb
#include <iostream>
/**
* @brief Abstract class providing genereal interface to exceptions
*
*/
class Exception: public std::exception
{
public:
/**
* @brief Message that can be printed to the end user
*
* @param[out] o here it will be printed
*/
virtual void Message(std::ostream & o) const = 0;
};
#endif //Exception_785a62ec3213411cb4e442ee734c00cb
| 24.619048
| 67
| 0.686654
|
pokorj54
|
4558774323aa65b0256e5a57988556294f5c1ef0
| 2,982
|
cxx
|
C++
|
src/Cxx/Visualization/ProjectSphere.cxx
|
ajpmaclean/vtk-examples
|
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
|
[
"Apache-2.0"
] | 81
|
2020-08-10T01:44:30.000Z
|
2022-03-23T06:46:36.000Z
|
src/Cxx/Visualization/ProjectSphere.cxx
|
ajpmaclean/vtk-examples
|
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
|
[
"Apache-2.0"
] | 2
|
2020-09-12T17:33:52.000Z
|
2021-04-15T17:33:09.000Z
|
src/Cxx/Visualization/ProjectSphere.cxx
|
ajpmaclean/vtk-examples
|
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
|
[
"Apache-2.0"
] | 27
|
2020-08-17T07:09:30.000Z
|
2022-02-15T03:44:58.000Z
|
#include <vtkActor.h>
#include <vtkCamera.h>
#include <vtkElevationFilter.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkParametricFunctionSource.h>
#include <vtkParametricSuperEllipsoid.h>
#include <vtkPointData.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkProjectSphereFilter.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
int main(int, char*[])
{
vtkNew<vtkNamedColors> colors;
vtkNew<vtkParametricSuperEllipsoid> surface;
surface->SetN1(2.0);
surface->SetN2(0.5);
vtkNew<vtkParametricFunctionSource> source;
source->SetParametricFunction(surface);
vtkNew<vtkElevationFilter> elevationFilter;
elevationFilter->SetInputConnection(source->GetOutputPort());
elevationFilter->SetLowPoint(0.0, 0.0, -4.0);
elevationFilter->SetHighPoint(0.0, 0.0, 4.0);
elevationFilter->Update();
// Deep copy the point data since in some versions of VTK,
// the ProjectSphereFilter modifies the input point data
vtkNew<vtkPolyData> pd1;
pd1->DeepCopy(elevationFilter->GetOutput());
vtkNew<vtkProjectSphereFilter> sphereProject1;
sphereProject1->SetInputConnection(elevationFilter->GetOutputPort());
sphereProject1->Update();
vtkNew<vtkPolyDataMapper> mapper1;
mapper1->SetInputConnection(sphereProject1->GetOutputPort());
mapper1->SetScalarRange(
sphereProject1->GetOutput()->GetPointData()->GetScalars()->GetRange());
vtkNew<vtkActor> actor1;
actor1->SetMapper(mapper1);
vtkNew<vtkPolyDataMapper> mapper2;
mapper2->SetInputData(pd1);
mapper2->SetScalarRange(pd1->GetPointData()->GetScalars()->GetRange());
vtkNew<vtkActor> actor2;
actor2->SetMapper(mapper2);
// A render window
vtkNew<vtkRenderWindow> renderWindow;
// Define viewport ranges
// (xmin, ymin, xmax, ymax)
double leftViewport[4] = {0.0, 0.0, 0.5, 1.0};
double rightViewport[4] = {0.5, 0.0, 1.0, 1.0};
// Setup both renderers
vtkNew<vtkRenderer> leftRenderer;
renderWindow->AddRenderer(leftRenderer);
leftRenderer->SetViewport(leftViewport);
leftRenderer->SetBackground(colors->GetColor3d("RosyBrown").GetData());
vtkNew<vtkRenderer> rightRenderer;
renderWindow->AddRenderer(rightRenderer);
rightRenderer->SetViewport(rightViewport);
rightRenderer->SetBackground(colors->GetColor3d("CadetBlue").GetData());
leftRenderer->AddActor(actor2);
rightRenderer->AddActor(actor1);
// An interactor
vtkNew<vtkRenderWindowInteractor> renderWindowInteractor;
renderWindowInteractor->SetRenderWindow(renderWindow);
leftRenderer->GetActiveCamera()->Azimuth(30);
leftRenderer->GetActiveCamera()->Elevation(-30);
leftRenderer->ResetCamera();
// Render an image (lights and cameras are created automatically)
renderWindow->SetSize(640, 480);
renderWindow->SetWindowName("ProjectSphere");
renderWindow->Render();
// Begin mouse interaction
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
| 30.742268
| 77
| 0.757881
|
ajpmaclean
|
455878b48a2ef154a4e5242dc0e51a7aee92a867
| 898
|
cpp
|
C++
|
src/util/TexShare.cpp
|
pharpend/Oscilloscope
|
e2598c559302bd91747b73a251d614eeb4dea663
|
[
"MIT"
] | 460
|
2015-03-18T18:59:49.000Z
|
2022-03-19T19:11:09.000Z
|
src/util/TexShare.cpp
|
pharpend/Oscilloscope
|
e2598c559302bd91747b73a251d614eeb4dea663
|
[
"MIT"
] | 78
|
2015-05-10T07:23:55.000Z
|
2022-03-09T13:58:51.000Z
|
src/util/TexShare.cpp
|
pharpend/Oscilloscope
|
e2598c559302bd91747b73a251d614eeb4dea663
|
[
"MIT"
] | 64
|
2015-06-13T01:45:54.000Z
|
2022-01-14T17:38:19.000Z
|
//
// SharedTex.cpp
// Oscilloscope
//
// Created by Hansi on 27/06/19.
//
//
#include "TexShare.h"
#include "ofMain.h"
#ifdef TARGET_OSX
#include "ofxSyphon.h"
class TexShareImpl{
public:
ofxSyphonServer server;
void setup(string name){
server.setName(name);
}
void update(ofTexture &tex){
server.publishTexture(&tex);
}
};
#elif defined TARGET_WIN32
#include "ofxSpout.h"
class TexShareImpl{
public:
ofxSpout::Sender spoutSender;
void setup(string name){
spoutSender.init(name);
}
void update(ofTexture &tex){
spoutSender.send(tex);
}
};
#else
class TexShareImpl{
public:
void setup(string name){}
void update(ofTexture & tex){};
};
#endif
TexShare::TexShare(){
impl = make_unique<TexShareImpl>();
}
TexShare::~TexShare() = default;
void TexShare::setup(string name){
impl->setup(name);
}
void TexShare::update(ofTexture &tex){
impl->update(tex);
}
| 14.483871
| 38
| 0.690423
|
pharpend
|
455a9f22c0c56eeceee8a943903882aa281ccc0d
| 20,389
|
hxx
|
C++
|
main/writerfilter/source/ooxml/OOXMLFastContextHandler.hxx
|
Grosskopf/openoffice
|
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
|
[
"Apache-2.0"
] | 679
|
2015-01-06T06:34:58.000Z
|
2022-03-30T01:06:03.000Z
|
main/writerfilter/source/ooxml/OOXMLFastContextHandler.hxx
|
Grosskopf/openoffice
|
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
|
[
"Apache-2.0"
] | 102
|
2017-11-07T08:51:31.000Z
|
2022-03-17T12:13:49.000Z
|
main/writerfilter/source/ooxml/OOXMLFastContextHandler.hxx
|
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.
*
*************************************************************/
#ifndef INCLUDED_OOXML_FAST_CONTEXT_HANDLER_HXX
#define INCLUDED_OOXML_FAST_CONTEXT_HANDLER_HXX
#include <com/sun/star/xml/sax/XFastShapeContextHandler.hpp>
#include <string>
#include <set>
#include "sal/config.h"
#include "com/sun/star/uno/XComponentContext.hpp"
#include "cppuhelper/implbase1.hxx"
#include "com/sun/star/xml/sax/XFastContextHandler.hpp"
#include "OOXMLParserState.hxx"
#include "OOXMLPropertySetImpl.hxx"
#include "OOXMLDocumentImpl.hxx"
#include "RefAndPointer.hxx"
#include <ooxml/OOXMLFastTokens.hxx>
namespace writerfilter {
namespace ooxml
{
using namespace ::std;
using namespace ::com::sun::star;
using namespace ::com::sun::star::xml::sax;
typedef boost::shared_ptr<Stream> StreamPointer_t;
class OOXMLFastContextHandler:
public ::cppu::WeakImplHelper1<
xml::sax::XFastContextHandler>
{
public:
typedef RefAndPointer<XFastContextHandler, OOXMLFastContextHandler>
RefAndPointer_t;
typedef boost::shared_ptr<OOXMLFastContextHandler> Pointer_t;
enum ResourceEnum_t { UNKNOWN, STREAM, PROPERTIES, TABLE, SHAPE };
OOXMLFastContextHandler();
explicit OOXMLFastContextHandler(
uno::Reference< uno::XComponentContext > const & context );
explicit OOXMLFastContextHandler(
OOXMLFastContextHandler * pContext );
virtual ~OOXMLFastContextHandler();
// ::com::sun::star::xml::sax::XFastContextHandler:
virtual void SAL_CALL startFastElement
(sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void SAL_CALL startUnknownElement
(const ::rtl::OUString & Namespace,
const ::rtl::OUString & Name,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void SAL_CALL endFastElement(sal_Int32 Element)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void SAL_CALL endUnknownElement
(const ::rtl::OUString & Namespace, const ::rtl::OUString & Name)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual uno::Reference< xml::sax::XFastContextHandler > SAL_CALL
createFastChildContext
(sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual uno::Reference< xml::sax::XFastContextHandler > SAL_CALL
createUnknownChildContext
(const ::rtl::OUString & Namespace,
const ::rtl::OUString & Name,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void SAL_CALL characters(const ::rtl::OUString & aChars)
throw (uno::RuntimeException, xml::sax::SAXException);
static const uno::Sequence< sal_Int8 > & getUnoTunnelId();
virtual sal_Int64 SAL_CALL getSomething(const uno::Sequence<sal_Int8> & rId)
throw (uno::RuntimeException);
// local
void setStream(Stream * pStream);
/**
Return value of this context(element).
@return the value
*/
virtual OOXMLValue::Pointer_t getValue() const;
/**
Returns a string describing the type of the context.
This is the name of the define normally.
@return type string
*/
virtual string getType() const { return "??"; }
virtual ResourceEnum_t getResource() const { return STREAM; }
virtual void attributes
(const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void newProperty(const Id & rId, OOXMLValue::Pointer_t pVal);
virtual void setPropertySet(OOXMLPropertySet::Pointer_t pPropertySet);
virtual OOXMLPropertySet::Pointer_t getPropertySet() const;
virtual void setToken(Token_t nToken);
virtual Token_t getToken() const;
void mark(const Id & rId, OOXMLValue::Pointer_t pVal);
void resolveFootnote( const sal_Int32 nIDForXNoteStream );
void resolveEndnote( const sal_Int32 nIDForXNoteStream );
void resolveComment( const sal_Int32 nIDForXNoteStream );
void resolvePicture(const rtl::OUString & rId);
void resolveHeader(const sal_Int32 type,
const rtl::OUString & rId);
void resolveFooter(const sal_Int32 type,
const rtl::OUString & rId);
void resolveOLE(const rtl::OUString & rId);
::rtl::OUString getTargetForId(const ::rtl::OUString & rId);
uno::Reference < xml::sax::XFastContextHandler >
createFromStart
(sal_uInt32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs);
void setDocument(OOXMLDocument * pDocument);
OOXMLDocument * getDocument();
void setIDForXNoteStream(OOXMLValue::Pointer_t pValue);
void setForwardEvents(bool bForwardEvents);
bool isForwardEvents() const;
virtual void setParent(OOXMLFastContextHandler * pParent);
virtual void setId(Id nId);
virtual Id getId() const;
void setDefine(Id nDefine);
Id getDefine() const;
OOXMLParserState::Pointer_t getParserState() const;
void sendTableDepth() const;
void setHandle();
void startSectionGroup();
void setLastParagraphInSection();
void endSectionGroup();
void startParagraphGroup();
void endParagraphGroup();
void startCharacterGroup();
void endCharacterGroup();
void startField();
void fieldSeparator();
void endField();
void ftnednref();
void ftnedncont();
void ftnednsep();
void pgNum();
void tab();
void cr();
void noBreakHyphen();
void softHyphen();
void handleLastParagraphInSection();
void endOfParagraph();
void text(const ::rtl::OUString & sText);
virtual void propagateCharacterProperties();
virtual void propagateCharacterPropertiesAsSet(const Id & rId);
virtual void propagateTableProperties();
virtual void propagateRowProperties();
virtual void propagateCellProperties();
virtual bool propagatesProperties() const;
void sendPropertiesWithId(const Id & rId);
void sendPropertiesToParent();
void sendCellProperties();
void sendRowProperties();
void sendTableProperties();
void clearTableProps();
void clearProps();
virtual void setDefaultBooleanValue();
virtual void setDefaultIntegerValue();
virtual void setDefaultHexValue();
virtual void setDefaultStringValue();
void sendPropertyToParent();
#ifdef DEBUG
static XMLTag::Pointer_t toPropertiesTag(OOXMLPropertySet::Pointer_t);
virtual XMLTag::Pointer_t toTag() const;
virtual string toString() const;
#endif
protected:
OOXMLFastContextHandler * mpParent;
Id mId;
Id mnDefine;
Token_t mnToken;
// the stream to send the stream events to.
Stream * mpStream;
// the current global parser state
OOXMLParserState::Pointer_t mpParserState;
// the table depth of this context
unsigned int mnTableDepth;
virtual void lcl_startFastElement
(sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void lcl_endFastElement(sal_Int32 Element)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual uno::Reference< xml::sax::XFastContextHandler >
lcl_createFastChildContext
(sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void lcl_characters(const ::rtl::OUString & aChars)
throw (uno::RuntimeException, xml::sax::SAXException);
void startAction(sal_Int32 Element);
virtual void lcl_startAction(sal_Int32 Element);
void endAction(sal_Int32 Element);
virtual void lcl_endAction(sal_Int32 Element);
// Returns string for resource of this context. (debug)
string getResourceString() const;
virtual OOXMLPropertySet * getPicturePropSet
(const ::rtl::OUString & rId);
virtual void resolvePropertySetAttrs();
uno::Reference< uno::XComponentContext > getComponentContext();
sal_uInt32 mnInstanceNumber;
sal_uInt32 mnRefCount;
private:
void operator =(OOXMLFastContextHandler &); // not defined
uno::Reference< uno::XComponentContext > m_xContext;
static sal_uInt32 mnInstanceCount;
};
class OOXMLFastContextHandlerStream : public OOXMLFastContextHandler
{
public:
OOXMLFastContextHandlerStream(OOXMLFastContextHandler * pContext);
virtual ~OOXMLFastContextHandlerStream();
virtual ResourceEnum_t getResource() const { return STREAM; }
OOXMLPropertySet::Pointer_t getPropertySetAttrs() const;
virtual void newProperty(const Id & rId, OOXMLValue::Pointer_t pVal);
virtual void sendProperty(Id nId);
virtual OOXMLPropertySet::Pointer_t getPropertySet() const;
void handleHyperlink();
protected:
virtual void resolvePropertySetAttrs();
private:
mutable OOXMLPropertySet::Pointer_t mpPropertySetAttrs;
};
class OOXMLFastContextHandlerProperties : public OOXMLFastContextHandler
{
public:
OOXMLFastContextHandlerProperties(OOXMLFastContextHandler * pContext);
virtual ~OOXMLFastContextHandlerProperties();
virtual OOXMLValue::Pointer_t getValue() const;
virtual ResourceEnum_t getResource() const { return PROPERTIES; }
virtual void newProperty(const Id & nId, OOXMLValue::Pointer_t pVal);
void handleXNotes();
void handleHdrFtr();
void handleComment();
void handlePicture();
void handleBreak();
void handleOLE();
virtual void setPropertySet(OOXMLPropertySet::Pointer_t pPropertySet);
virtual OOXMLPropertySet::Pointer_t getPropertySet() const;
#ifdef DEBUG
virtual XMLTag::Pointer_t toTag() const;
#endif
protected:
/// the properties
OOXMLPropertySet::Pointer_t mpPropertySet;
virtual void lcl_endFastElement(sal_Int32 Element)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void setParent(OOXMLFastContextHandler * pParent);
private:
bool mbResolve;
};
class OOXMLFastContextHandlerPropertyTable :
public OOXMLFastContextHandlerProperties
{
public:
OOXMLFastContextHandlerPropertyTable(OOXMLFastContextHandler * pContext);
virtual ~OOXMLFastContextHandlerPropertyTable();
protected:
OOXMLTableImpl mTable;
virtual void lcl_endFastElement(sal_Int32 Element)
throw (uno::RuntimeException, xml::sax::SAXException);
};
class OOXMLFastContextHandlerValue :
public OOXMLFastContextHandler
{
public:
OOXMLFastContextHandlerValue
(OOXMLFastContextHandler * pContext);
virtual ~OOXMLFastContextHandlerValue();
virtual void setValue(OOXMLValue::Pointer_t pValue);
virtual OOXMLValue::Pointer_t getValue() const;
virtual void lcl_endFastElement(sal_Int32 Element)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual string getType() const { return "Value"; }
virtual void setDefaultBooleanValue();
virtual void setDefaultIntegerValue();
virtual void setDefaultHexValue();
virtual void setDefaultStringValue();
protected:
OOXMLValue::Pointer_t mpValue;
};
class OOXMLFastContextHandlerTable : public OOXMLFastContextHandler
{
public:
OOXMLFastContextHandlerTable(OOXMLFastContextHandler * pContext);
virtual ~OOXMLFastContextHandlerTable();
virtual uno::Reference< xml::sax::XFastContextHandler > SAL_CALL
createFastChildContext
(sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void newPropertySet(OOXMLPropertySet::Pointer_t pPropertySet);
protected:
OOXMLTableImpl mTable;
RefAndPointer_t mCurrentChild;
virtual void lcl_endFastElement(sal_Int32 Element)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual ResourceEnum_t getResource() const { return TABLE; }
virtual string getType() const { return "Table"; }
void addCurrentChild();
};
class OOXMLFastContextHandlerXNote : public OOXMLFastContextHandlerProperties
{
public:
OOXMLFastContextHandlerXNote(OOXMLFastContextHandler * pContext);
virtual ~OOXMLFastContextHandlerXNote();
void checkId(OOXMLValue::Pointer_t pValue);
virtual string getType() const { return "XNote"; }
private:
bool mbForwardEventsSaved;
sal_Int32 mnMyXNoteId;
virtual void lcl_startFastElement
(sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void lcl_endFastElement(sal_Int32 Element)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual ResourceEnum_t getResource() const { return STREAM; }
};
class OOXMLFastContextHandlerTextTableCell : public OOXMLFastContextHandler
{
public:
OOXMLFastContextHandlerTextTableCell
(OOXMLFastContextHandler * pContext);
virtual ~OOXMLFastContextHandlerTextTableCell();
virtual string getType() const { return "TextTableCell"; }
void startCell();
void endCell();
};
class OOXMLFastContextHandlerTextTableRow : public OOXMLFastContextHandler
{
public:
OOXMLFastContextHandlerTextTableRow
(OOXMLFastContextHandler * pContext);
virtual ~OOXMLFastContextHandlerTextTableRow();
virtual string getType() const { return "TextTableRow"; }
void startRow();
void endRow();
};
class OOXMLFastContextHandlerTextTable : public OOXMLFastContextHandler
{
public:
OOXMLFastContextHandlerTextTable
(OOXMLFastContextHandler * pContext);
virtual ~OOXMLFastContextHandlerTextTable();
virtual string getType() const { return "TextTable"; }
protected:
virtual void lcl_startFastElement
(sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void lcl_endFastElement(sal_Int32 Element)
throw (uno::RuntimeException, xml::sax::SAXException);
};
class OOXMLFastContextHandlerShape: public OOXMLFastContextHandlerProperties
{
private:
bool m_bShapeSent;
bool m_bShapeStarted;
public:
explicit OOXMLFastContextHandlerShape
(OOXMLFastContextHandler * pContext);
virtual ~OOXMLFastContextHandlerShape();
virtual string getType() const { return "Shape"; }
// ::com::sun::star::xml::sax::XFastContextHandler:
virtual void SAL_CALL startUnknownElement
(const ::rtl::OUString & Namespace,
const ::rtl::OUString & Name,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void SAL_CALL endUnknownElement
(const ::rtl::OUString & Namespace,
const ::rtl::OUString & Name)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual uno::Reference< xml::sax::XFastContextHandler > SAL_CALL
createUnknownChildContext
(const ::rtl::OUString & Namespace,
const ::rtl::OUString & Name,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void setToken(Token_t nToken);
virtual ResourceEnum_t getResource() const { return SHAPE; }
void sendShape( Token_t Element );
protected:
typedef uno::Reference<XFastShapeContextHandler> ShapeContextRef;
ShapeContextRef mrShapeContext;
virtual void lcl_startFastElement
(sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void lcl_endFastElement(sal_Int32 Element)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual uno::Reference< xml::sax::XFastContextHandler >
lcl_createFastChildContext
(sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void lcl_characters(const ::rtl::OUString & aChars)
throw (uno::RuntimeException, xml::sax::SAXException);
};
/**
OOXMLFastContextHandlerWrapper wraps an OOXMLFastContextHandler.
The method calls for the interface
::com::sun::star::xml::sax::XFastContextHandler are forwarded to the wrapped
OOXMLFastContextHandler.
*/
class OOXMLFastContextHandlerWrapper : public OOXMLFastContextHandler
{
public:
explicit OOXMLFastContextHandlerWrapper
(OOXMLFastContextHandler * pParent,
uno::Reference<XFastContextHandler> xContext);
virtual ~OOXMLFastContextHandlerWrapper();
// ::com::sun::star::xml::sax::XFastContextHandler:
virtual void SAL_CALL startUnknownElement
(const ::rtl::OUString & Namespace,
const ::rtl::OUString & Name,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void SAL_CALL endUnknownElement
(const ::rtl::OUString & Namespace,
const ::rtl::OUString & Name)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual uno::Reference< xml::sax::XFastContextHandler > SAL_CALL
createUnknownChildContext
(const ::rtl::OUString & Namespace,
const ::rtl::OUString & Name,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void attributes
(const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual ResourceEnum_t getResource() const;
void addNamespace(const Id & nId);
void addToken( Token_t Element );
virtual void newProperty(const Id & rId, OOXMLValue::Pointer_t pVal);
virtual void setPropertySet(OOXMLPropertySet::Pointer_t pPropertySet);
virtual OOXMLPropertySet::Pointer_t getPropertySet() const;
virtual string getType() const;
protected:
virtual void lcl_startFastElement
(sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void lcl_endFastElement(sal_Int32 Element)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual uno::Reference< xml::sax::XFastContextHandler >
lcl_createFastChildContext
(sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void lcl_characters(const ::rtl::OUString & aChars)
throw (uno::RuntimeException, xml::sax::SAXException);
virtual void setId(Id nId);
virtual Id getId() const;
virtual void setToken(Token_t nToken);
virtual Token_t getToken() const;
private:
uno::Reference<XFastContextHandler> mxContext;
set<Id> mMyNamespaces;
set<Token_t> mMyTokens;
OOXMLPropertySet::Pointer_t mpPropertySet;
OOXMLFastContextHandler * getFastContextHandler() const;
};
}}
#endif // INCLUDED_OOXML_FAST_CONTEXT_HANDLER_HXX
| 32.261076
| 80
| 0.71568
|
Grosskopf
|
4568b8382c54da544c4c3ba3095eb7ec6c41ecac
| 4,872
|
cpp
|
C++
|
convertxml/native_module_convertxml.cpp
|
openharmony-gitee-mirror/js_api_module
|
2c3d4cf53a81d4b68933cdeec74e4c3e3da7f46d
|
[
"Apache-2.0"
] | null | null | null |
convertxml/native_module_convertxml.cpp
|
openharmony-gitee-mirror/js_api_module
|
2c3d4cf53a81d4b68933cdeec74e4c3e3da7f46d
|
[
"Apache-2.0"
] | null | null | null |
convertxml/native_module_convertxml.cpp
|
openharmony-gitee-mirror/js_api_module
|
2c3d4cf53a81d4b68933cdeec74e4c3e3da7f46d
|
[
"Apache-2.0"
] | 1
|
2021-09-13T11:21:19.000Z
|
2021-09-13T11:21:19.000Z
|
/*
* Copyright (c) 2021 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 "utils/log.h"
#include "js_convertxml.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
extern const char _binary_js_convertxml_js_start[];
extern const char _binary_js_convertxml_js_end[];
extern const char _binary_convertxml_abc_start[];
extern const char _binary_convertxml_abc_end[];
namespace OHOS::Xml {
static napi_value ConvertXmlConstructor(napi_env env, napi_callback_info info)
{
napi_value thisVar = nullptr;
void *data = nullptr;
napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, &data);
auto objectInfo = new ConvertXml(env);
napi_wrap(
env, thisVar, objectInfo,
[](napi_env env, void *data, void *hint) {
auto obj = (ConvertXml*)data;
if (obj != nullptr) {
delete obj;
}
},
nullptr, nullptr);
return thisVar;
}
static napi_value Convert(napi_env env, napi_callback_info info)
{
napi_value thisVar = nullptr;
size_t requireMaxArgc = 2; // 2:MaxArgc
size_t requireMinArgc = 1;
size_t argc = 2;
napi_value args[2] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr));
NAPI_ASSERT(env, argc <= requireMaxArgc, "Wrong number of arguments(Over)");
NAPI_ASSERT(env, argc >= requireMinArgc, "Wrong number of arguments(Less)");
std::string strXml;
napi_valuetype valuetype;
ConvertXml *object = nullptr;
NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast<void**>(&object)));
if (args[0] == nullptr) {
NAPI_CALL(env, napi_throw_error(env, "", "parameter is empty"));
} else {
NAPI_CALL(env, napi_typeof(env, args[0], &valuetype));
NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument typr. String expected.");
object->DealNapiStrValue(args[0], strXml);
}
if (args[1] != nullptr) {
object->DealOptions(args[1]);
}
napi_value result = object->Convert(strXml);
return result;
}
static napi_value ConvertXmlInit(napi_env env, napi_value exports)
{
const char *convertXmlClassName = "ConvertXml";
napi_value convertXmlClass = nullptr;
static napi_property_descriptor convertXmlDesc[] = {
DECLARE_NAPI_FUNCTION("convert", Convert)
};
NAPI_CALL(env, napi_define_class(env, convertXmlClassName, strlen(convertXmlClassName), ConvertXmlConstructor,
nullptr, sizeof(convertXmlDesc) / sizeof(convertXmlDesc[0]), convertXmlDesc,
&convertXmlClass));
static napi_property_descriptor desc[] = {
DECLARE_NAPI_PROPERTY("ConvertXml", convertXmlClass)
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
return exports;
}
extern "C"
__attribute__((visibility("default"))) void NAPI_convertxml_GetJSCode(const char **buf, int *bufLen)
{
if (buf != nullptr) {
*buf = _binary_js_convertxml_js_start;
}
if (bufLen != nullptr) {
*bufLen = _binary_js_convertxml_js_end - _binary_js_convertxml_js_start;
}
}
extern "C"
__attribute__((visibility("default"))) void NAPI_convertxml_GetABCCode(const char** buf, int* buflen)
{
if (buf != nullptr) {
*buf = _binary_convertxml_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_convertxml_abc_end - _binary_convertxml_abc_start;
}
}
static napi_module convertXmlModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = ConvertXmlInit,
.nm_modname = "ConvertXML",
.nm_priv = ((void*)0),
.reserved = { 0 },
};
extern "C" __attribute__ ((constructor)) void RegisterModule()
{
napi_module_register(&convertXmlModule);
}
} // namespace
| 38.362205
| 119
| 0.609811
|
openharmony-gitee-mirror
|
456984dafd290502cd6b7fbbd63266164f802149
| 202
|
cpp
|
C++
|
Backbone/UserManager/XMLManager/main.cpp
|
ed-quiroga-2103/OdisseyC
|
cf7ec95c574bfd4b2581f9af092dae50803dcebb
|
[
"Apache-2.0"
] | null | null | null |
Backbone/UserManager/XMLManager/main.cpp
|
ed-quiroga-2103/OdisseyC
|
cf7ec95c574bfd4b2581f9af092dae50803dcebb
|
[
"Apache-2.0"
] | null | null | null |
Backbone/UserManager/XMLManager/main.cpp
|
ed-quiroga-2103/OdisseyC
|
cf7ec95c574bfd4b2581f9af092dae50803dcebb
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include "pugixml.hpp"
#include "string"
#include "XMLParts.h"
#include "XMLManager.h"
using document = pugi::xml_document;
using string = std::string;
int main() {
return 0;
}
| 16.833333
| 36
| 0.70297
|
ed-quiroga-2103
|
456ce2aad5fd617a5ed86fc8916b091e371316e3
| 423
|
cpp
|
C++
|
cph/modbus/mbqueue.cpp
|
Loggi-pro/cph-lib
|
4109dd1d3cc780c9f76aa54c2322bbdcbfdfea67
|
[
"MIT"
] | null | null | null |
cph/modbus/mbqueue.cpp
|
Loggi-pro/cph-lib
|
4109dd1d3cc780c9f76aa54c2322bbdcbfdfea67
|
[
"MIT"
] | null | null | null |
cph/modbus/mbqueue.cpp
|
Loggi-pro/cph-lib
|
4109dd1d3cc780c9f76aa54c2322bbdcbfdfea67
|
[
"MIT"
] | null | null | null |
#include "mbqueue.h"
void ModbusEventQueue::init() {
_isEventInQueue = false;
}
bool ModbusEventQueue::postEvent(MBEventType eEvent) {
_isEventInQueue = true;
_queuedEvent = eEvent;
return true;
}
bool ModbusEventQueue::getEvent(MBEventType* eEvent) {
bool isEventHappened = false;
if (_isEventInQueue) {
*eEvent = _queuedEvent;
_isEventInQueue = false;
isEventHappened = true;
}
return isEventHappened;
}
| 19.227273
| 54
| 0.747045
|
Loggi-pro
|
456cee28cc1d1ab23a90b671f5ab734025642346
| 1,778
|
cpp
|
C++
|
examples/HelloWorld/HelloWorld.cpp
|
SteveDeFacto/ovgl
|
879899f63f0dc399e2823dd84bb715fda3aafb78
|
[
"Apache-2.0"
] | 3
|
2019-02-24T23:17:49.000Z
|
2020-05-03T09:05:49.000Z
|
examples/HelloWorld/HelloWorld.cpp
|
SteveDeFacto/ovgl
|
879899f63f0dc399e2823dd84bb715fda3aafb78
|
[
"Apache-2.0"
] | null | null | null |
examples/HelloWorld/HelloWorld.cpp
|
SteveDeFacto/ovgl
|
879899f63f0dc399e2823dd84bb715fda3aafb78
|
[
"Apache-2.0"
] | null | null | null |
/**
* @file HelloWorld.cpp
* Copyright 2011 Steven Batchelor
*
* 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.
* @brief None.
*/
#include <Ovgl.h>
Ovgl::Context* context;
Ovgl::RenderTarget* render_target;
Ovgl::Window* window;
Ovgl::ResourceManager* resources;
Ovgl::Texture* texture1;
Ovgl::Interface* interface1;
Ovgl::Font* font1;
int main()
{
// Create Main Context
context = new Ovgl::Context( 0 );
// Create Window
window = new Ovgl::Window( context, "Hello World!", 320, 240);
// Create Render Target
render_target = new Ovgl::RenderTarget( context, window, Ovgl::URect( 0.0f, 0.0f, 1.0f, 1.0f ), 0 );
// Create Resource Manager
resources = new Ovgl::ResourceManager(context, "");
// Create an interface
interface1 = new Ovgl::Interface( render_target, Ovgl::URect( 0.0f, 0.0f, 1.0f, 1.0f ) );
// Load a font
font1 = new Ovgl::Font(resources, "../../media/fonts/ArchitectsDaughter.ttf", 48);
// Set interface font
interface1->font = font1;
// Set the interface text
interface1->setText("Hello World!");
// Start main loop
context->start();
// Release all
delete context;
// No errors happend so return zero
return 0;
}
| 27.78125
| 105
| 0.663105
|
SteveDeFacto
|
456d9b8f021d8459aaea5b9c07ffd93e2d8a506f
| 738
|
hpp
|
C++
|
src/cpp/iir-filter-node.hpp
|
node-3d/waa-raub
|
e458d76f290b1e12ef2a0adc063b521816337f04
|
[
"MIT"
] | 17
|
2018-10-03T00:44:33.000Z
|
2022-03-17T06:40:15.000Z
|
src/cpp/iir-filter-node.hpp
|
raub/node-waa
|
e458d76f290b1e12ef2a0adc063b521816337f04
|
[
"MIT"
] | 7
|
2019-07-16T08:22:31.000Z
|
2021-11-29T21:45:06.000Z
|
src/cpp/iir-filter-node.hpp
|
raub/node-waa
|
e458d76f290b1e12ef2a0adc063b521816337f04
|
[
"MIT"
] | 2
|
2019-08-05T20:00:42.000Z
|
2020-03-15T13:25:41.000Z
|
#ifndef _IIR_FILTER_NODE_HPP_
#define _IIR_FILTER_NODE_HPP_
#include "common.hpp"
class IIRFilterNode : public CommonNode {
DECLARE_ES5_CLASS(IIRFilterNode, IIRFilterNode);
public:
~IIRFilterNode();
explicit IIRFilterNode(const Napi::CallbackInfo &info);
static void init(Napi::Env env, Napi::Object exports);
static bool isIIRFilterNode(Napi::Object obj);
// Destroy an instance from C++ land
void _destroy();
protected:
IIRFilterNode();
static Napi::FunctionReference _constructor;
bool _isDestroyed;
private:
JS_DECLARE_METHOD(IIRFilterNode, destroy);
JS_DECLARE_GETTER(IIRFilterNode, isDestroyed);
JS_DECLARE_METHOD(IIRFilterNode, getFrequencyResponse);
};
#endif // _IIR_FILTER_NODE_HPP_
| 17.571429
| 56
| 0.768293
|
node-3d
|
456fba303c64e745bee06e191b15a89f770516b4
| 15,915
|
cpp
|
C++
|
Lambda-Lib-C++/LambdaCalc_SampleExec.cpp
|
jrandleman/Lambda-Calc-Compilation
|
488c6d1fbc92d00429aa7eb772df3fd6e0dd92c5
|
[
"MIT"
] | 1
|
2020-09-14T19:47:13.000Z
|
2020-09-14T19:47:13.000Z
|
Lambda-Lib-C++/LambdaCalc_SampleExec.cpp
|
jrandleman/Lambda-Calc-Compiler
|
488c6d1fbc92d00429aa7eb772df3fd6e0dd92c5
|
[
"MIT"
] | null | null | null |
Lambda-Lib-C++/LambdaCalc_SampleExec.cpp
|
jrandleman/Lambda-Calc-Compiler
|
488c6d1fbc92d00429aa7eb772df3fd6e0dd92c5
|
[
"MIT"
] | null | null | null |
// Author: Jordan Randleman -- LambdaCalc_SampleExec.cpp
// => Demo File to Illustrate LambdaCalc.hpp's Capabilities
#include <iostream>
#include "LambdaCalc.hpp"
/**
* -:- NAMESPACE LambdaCalc LAMBDAS -:-
* => ALL DATA IS IMMUTABLE (CONST)
* => ALL LAMBDAS ARE CURRIED ( IE Add(ox1, ox2) => Add(ox1)(ox2) )
* => CAPTURE SCOPE BY _VALUE_ (using [=]) FOR INNER - CURRIED! - LAMBDAS
*
* !!!!! GENERATE A LIST OF ARBITRARY LENGTH W/O MEMORY ALLOCATION (Push) !!!!!
*
* NOTATION:
* => let N = Church Numeral, B = Fcnal Bool, F1 = Unary Fcn, F2 = Binary Fcn,
* F = arbitrary fcn, X = arbitrary data,
* L = Fcnal List Data Structure (See More Below)
*
* ----------------------------------------------------------------------------
* - VISUALIZATION:
* ----------------------------------------------------------------------------
*
* show(X) => print arbitrary data x to screen + newline
* print(X) => print arbitrary data x to screen
*
* bshow(B) => print fcnal boolean as boolean boolean + newline
* bprint(B) => print fcnal boolean as boolean boolean
*
* nshow(N) => print church numeral as unsigned long long + newline
* nprint(N) => print church numeral as unsigned long long
*
* ----------------------------------------------------------------------------
* - FCNAL BOOLEANS:
* ----------------------------------------------------------------------------
*
* EXPLANATION:
* Fcnal Booleans are Binary Fcns, acting like C++'s Ternary '?:' operator:
* => Fcnal 'True' chooses arg1, 'False' chooses arg2
*
* BOOLEANS:
* => True
* => False
*
* BOOLEAN OPERATIONS:
* => Not (B)
* => And (B1)(B2)
* => Or (B1)(B2)
* => Xor (B1)(B2)
* => Beq (B1)(B2) => 'B'oolean 'eq'uality, ie xnor
*
* ----------------------------------------------------------------------------
* - CHURCH-NUMERAL NUMERIC FCNS:
* ----------------------------------------------------------------------------
*
* EXPLANATION:
* N-Fold Compositions of a Fcn (!!! ALL >= Zero Integers !!!):
* => IE Zero = a, Once = f(a), Twice = f(f(a)), Thrice = f(f(f(a))), etc
*
* NUMERALS:
* => Zero, Once, Twice, Thrice, Fourfold, Fivefold
* => ox0,ox1,ox2,ox3,ox4,ox5,ox6,ox7,ox8,ox9,oxa,oxb,oxc,oxd,oxe,oxf
*
* COMPARATIVE BOOLEANS:
* => Is0 (N) => Equal to 'Zero'
*
* => Eq (N1)(N2) => Equal-to
* => Lt (N1)(N2) => Less Than
* => Gt (N1)(N2) => Greater Than
* => Leq (N1)(N2) => Less Than Or Equal-to
* => Geq (N1)(N2) => Greater Than Or Equal-to
*
* => IsFactor (N1)(N2) => N1 is a factor of N2
* => Evenp (N) => N is even
* => Oddp (N) => N is odd
*
* ARITHMETIC:
* => Add (N1)(N2) => N1 + N2
* => Sub (N1)(N2) => N1 - N2
* => Mult (N1)(N2) => N1 * N2
* => Pow (N1)(N2) => N1 ** N2
* => Div (N1)(N2) => N1 / N2
* => Log (N1)(N2) => log N1 (N2)
*
* => Succ (N) => Succesor of N, N+1
* => Pred (N) => Predecessor of N, N-1
*
* => Factorial (N) => N! (w/o Loops, Recursion, or Mutability!!!)
* => NumericSum (N) => Sum (0,N)
* => NumericSumRange (N1)(N2) => Sum (N1,N2)
*
* ----------------------------------------------------------------------------
* - PURELY-FCNAL LIST DATA-STRUCTURE FCNS:
* ----------------------------------------------------------------------------
*
* CONSTRUCTION (Given List Size):
* => ListN(N) (N1) (N2) (N3) (NN) => Returns List size N of the trailing elts
*
* BASIC ANALYSIS:
* => Length (L) => Returns length of L
* => Nullp (L) => "Null" 'p'redicate: List is EMPTY
* => Pairp (L) => "Pair" 'p'redicate: List is __NOT__ EMPTY
*
* GETTERS:
* => Head (L) => Return L's 1st cell value
* => Last (L) => Return L's last cell value
* => Nth (N)(L) => Returns L's 'N'th elt (starting from 'ox1')
*
* SETTERS:
* => Insert (N)(X)(L) => Returns List w/ X inserted in L AFTER nth position
* => Erase (N)(L) => Returns List w/ L's nth value erased
* => Push (X)(L) => Returns List w/ X in front of L
* => Pop (L) => Returns List w/o L's Head
* => NOTE: "_back" versions may be self-implemented via "Backward" fcn (More Below)
*
* FILTER/MAP/VOIDMAP:
* => Filter (F1)(L) => Returns List having filtered out elts from L __NOT__ passing F1
* => Map (F1)(L) => Returns List having mapped F1 across all of L's elts
* => VoidMap (F1)(L) => Returns Void & F1 Must be void => Applie Fcn to each elt in L
* (useful for passing a "printer" fcn (ie nshow) to print each elt)
*
* REVERSED LIST & FCN APPLICATION:
* => Reverse (L) => Returns List of L in reverse
* => FlipArgs (F2) => Flips args for a Binary Fcn
* => Backward (F1)(L) => Returns List having applied F on Reverse(L)
* => BackwardAtomic (F1)(L) => Returns Atom (ie Non-List Fcn, such as a
* Church Numeral) having applied F on Reverse(L)
* ACCUMULATORS:
* => Foldl (F2)(X)(L) => Applies F2 on L from 'l'eft to right,
* starting w/ 'X' & Head(L)
* => Foldr (F2)(X)(L) => Applies F2 on L from 'r'ight to left,
* starting w/ 'X' & Last(L)
* MAX/MIN:
* => Max (L) => Returns Greatest value in List
* => Min (L) => Returns Smallest value in List
*
* LISP-STYLE ACCESS:
* => car (L) => Returns Current Cell Value ( IE Head(L) )
* => cdr (L) => Returns Next Cell ( IE Pop(L) )
* => cadr (L) => Head(Pop(L))
* => caddr (L) => Head(Pop(Pop(L)))
* => cadddr (L) => Head(Pop(Pop(Pop(L))))
* => ANY combo of 1-4 'a's & 'd's btwn 'c' & 'r' for nested list access!
*
* ----------------------------------------------------------------------------
* - IF YOU'VE GOTTEN THIS FAR ...
* ----------------------------------------------------------------------------
*
* You may genuinely enjoy the 2 JS Lambda Calculus videos below, found at:
* => Part 1: https://www.youtube.com/watch?v=3VQ382QG-y4&feature=youtu.be
* => Part 2: https://www.youtube.com/watch?v=pAnLQ9jwN-E
*
* In Summary:
* => Identity/Once, Idiot: I := \a.a
* => First/True/Const, Kestrel: K := \ab.a
* => Flip/LogicalNot, Cardinal: C := \fab.fba
* => Unary Compose, Bluebird: B := \fga.f(ga)
*
* => Self-Replication, Mockingbird M := \f.f(f) => IMPOSSIBLE IN HASKELL (Infinite Data Struct)
*
* => Second/False/Zero, Kite: KI := \ab.b = K I = C K
* => Binary Compose, Blackbird: B1 := \fgab.f(gab) = B B B
* => Hold An Arg, Thrush: Th := \af.fa = C I
* => Hold Arg Pair, Vireo: V := \abf.fab = B C Th = B C (C I)
*/
/******************************************************************************
* CURRIED FUNCTIONS & LAMBDA CALCULUS EXECUTION C++
******************************************************************************/
int main() {
using namespace LambdaCalc;
show("\nUsing Fcnal Booleans:");
print(" => Not(True): ");
bshow(Not(True));
print(" => Not(False): ");
bshow(Not(False));
print(" => And(True)(False): ");
bshow(And(True)(False));
print(" => And(True)(True): ");
bshow(And(True)(True));
print(" => And(False)(False): ");
bshow(And(False)(False));
print(" => Or(True)(False): ");
bshow(Or(True)(False));
print(" => Or(False)(False): ");
bshow(Or(False)(False));
print(" => Or(True)(True): ");
bshow(Or(True)(True));
print(" => Xor(False)(True): ");
bshow(Xor(False)(True));
print(" => Xor(True)(True): ");
bshow(Xor(True)(True));
print(" => Xor(False)(False): ");
bshow(Xor(False)(False));
print(" => Beq(True)(False): ");
bshow(Beq(True)(False));
print(" => Beq(True)(True): ");
bshow(Beq(True)(True));
print(" => Beq(False)(False): ");
bshow(Beq(False)(False));
show("\n\n\nUsing Church Numerals (0-15 shown as Hex w/ 'o' prefix):");
print(" => Is0(ox5): ");
bshow(Is0(ox5));
print(" => Is0(ox0): ");
bshow(Is0(ox0));
show("");
print(" => Eq(ox2)(ox8): ");
bshow(Eq(ox2)(ox8));
print(" => Eq(ox2)(ox2): ");
bshow(Eq(ox2)(ox2));
print(" => Lt(ox2)(ox8): ");
bshow(Lt(ox2)(ox8));
print(" => Lt(ox8)(ox2): ");
bshow(Lt(ox8)(ox2));
print(" => Lt(ox8)(ox8): ");
bshow(Lt(ox8)(ox8));
print(" => Gt(ox2)(ox8): ");
bshow(Gt(ox2)(ox8));
print(" => Gt(ox8)(ox2): ");
bshow(Gt(ox8)(ox2));
print(" => Gt(ox8)(ox8): ");
bshow(Gt(ox8)(ox8));
print(" => Leq(ox2)(ox8): ");
bshow(Leq(ox2)(ox8));
print(" => Leq(ox8)(ox2): ");
bshow(Leq(ox8)(ox2));
print(" => Leq(ox8)(ox8): ");
bshow(Leq(ox8)(ox8));
print(" => Geq(ox2)(ox8): ");
bshow(Geq(ox2)(ox8));
print(" => Geq(ox8)(ox2): ");
bshow(Geq(ox8)(ox2));
print(" => Geq(ox8)(ox8): ");
bshow(Geq(ox8)(ox8));
show("");
print(" => IsFactor(ox3)(oxc): ");
bshow(IsFactor(ox2)(ox4));
print(" => IsFactor(ox3)(oxd): ");
bshow(IsFactor(ox2)(ox7));
print(" => Evenp(ox6): ");
bshow(Evenp(ox6));
print(" => Evenp(ox9): ");
bshow(Evenp(ox9));
print(" => Oddp(ox6): ");
bshow(Oddp(ox6));
print(" => Oddp(ox9): ");
bshow(Oddp(ox9));
show("");
print(" => Add(oxf)(oxa): ");
nshow(Add(oxf)(oxa));
print(" => Sub(oxb)(ox6): ");
nshow(Sub(oxb)(ox6));
print(" => Mult(ox3)(ox7): ");
nshow(Mult(ox3)(ox7));
print(" => Pow(ox2)(ox5): ");
nshow(Pow(ox2)(ox5));
print(" => Div(Mult(ox2)(oxa))(ox4): ");
nshow(Div(Mult(ox2)(oxa))(ox4));
print(" => Log(ox2)(ox8): ");
nshow(Log(ox2)(ox8));
show("");
print(" => Succ(ox8): ");
nshow(Succ(ox8));
print(" => Pred(ox8): ");
nshow(Pred(ox8));
show("");
print(" => Factorial(ox5): ");
nshow(Factorial(ox5));
print(" => NumericSum(oxa): ");
nshow(NumericSum(oxa));
print(" => NumericSumRange(ox5)(oxa): ");
nshow(NumericSumRange(ox5)(oxa));
show("\n\n\nUsing The Purely-Fcnal \"ListN\" Data Structure:");
show(" => We have defined 2 lists:");
show(" (1) List of 5 Church Numerals:");
show(" List1 = ListN(ox5) (ox9) (ox4) (ox7) (ox3) (oxa);");
const auto List1 = ListN(ox5) (ox9) (ox4) (ox7) (ox3) (oxa);
show(" (2) Empty List:");
show(" List2 = ListN(ox0);");
const auto List2 = ListN(ox0);
show("\nBASIC ANALYSIS:");
print(" => Length(List1): ");
nshow(Length(List1));
print(" => Length(List2): ");
nshow(Length(List2));
show(" => Whether list IS or IS NOT empty:");
print(" - Nullp(List1): ");
bshow(Nullp(List1));
print(" - Nullp(List2): ");
bshow(Nullp(List2));
print(" - Pairp(List1): ");
bshow(Pairp(List1));
print(" - Pairp(List2): ");
bshow(Pairp(List2));
show("\nGETTERS:");
print(" => Head(List1): ");
nshow(Head(List1));
print(" => Last(List1): ");
nshow(Last(List1));
print(" => Nth(ox1)(List1): ");
nshow(Nth(ox1)(List1));
print(" => Nth(ox2)(List1): ");
nshow(Nth(ox2)(List1));
print(" => Nth(ox3)(List1): ");
nshow(Nth(ox3)(List1));
print(" => Nth(ox4)(List1): ");
nshow(Nth(ox4)(List1));
print(" => Nth(ox5)(List1): ");
nshow(Nth(ox5)(List1));
show("\nSETTERS:");
print(" => Length(Push(oxd)(List1)): ");
nshow(Length(Push(oxd)(List1)));
print(" => Head(Push(oxd)(List1)): ");
nshow(Head(Push(oxd)(List1)));
print(" => Length(Pop(List1)): ");
nshow(Length(Pop(List1)));
print(" => Head(Pop(List1)): ");
nshow(Head(Pop(List1)));
print(" => Length(Push(oxf)(List2)): ");
nshow(Length(Push(oxf)(List2)));
print(" => Head(Push(oxf)(List2)): ");
nshow(Head(Push(oxf)(List2)));
print(" => Length(Pop(Push(oxf)(List2))): ");
nshow(Length(Pop(Push(oxf)(List2))));
print(" => Erase(ox3)(List1) = ");
VoidMap(nprint)(Erase(ox3)(List1));
print("\n => Insert(ox3)(oxc)(List1) = ");
VoidMap(nprint)(Insert(ox3)(oxc)(List1));
show("");
show("\nFILTER/MAP/VOIDMAP:");
show(" => We have defined more 2 lists:");
show(" (1) List of odd Church Numerals from List1:");
show(" OnlyOdds = Filter(Oddp)(List1);");
const auto OnlyOdds = Filter(Oddp)(List1);
show(" (2) List of 2 raised to each value in List1:");
show(" PowersOf2 = Map(Pow(ox2))(List1);\n");
const auto PowersOf2 = Map(Pow(ox2))(List1);
show(" => Using \"VoidMap\" to map a Void printer fcn across these Lists:");
show(" (*) NOTE: \"nprint()\" = void lambda to print Church Numerals as ints!");
print(" (1) VoidMap(nprint)(OnlyOdds) = ");
VoidMap(nprint)(OnlyOdds);
show("");
print(" (2) VoidMap(nprint)(PowersOf2) = ");
VoidMap(nprint)(PowersOf2);
show("\n\nREVERSED LIST & REVERSED FCN APPLICATION:");
print(" => List1 = ");
VoidMap(nprint)(List1);
print("\n => Reverse(List1) = ");
VoidMap(nprint)(Reverse(List1));
print("\n => Pow(ox2)(ox3) = ");
nshow(Pow(ox2)(ox3));
print(" => FlipArgs(Pow)(ox2)(ox3) = ");
nshow(FlipArgs(Pow)(ox2)(ox3));
print(" => Push(oxf)(List1) = ");
VoidMap(nprint)(Push(oxf)(List1));
print("\n => Backward(Push(oxf))(List1) = ");
VoidMap(nprint)(Backward(Push(oxf))(List1));
show("\n => We have defined 1 more List: List3 = ListN(ox2) (ox2)(ox3);");
const auto List3 = ListN(ox2) (ox2)(ox3);
print(" -> Foldl(Pow)(ox1)(List3) = ");
nprint(Foldl(Pow)(ox1)(List3));
print("\n -> BackwardAtomic(Foldl(Pow)(ox1))(List3) = ");
nshow(BackwardAtomic(Foldl(Pow)(ox1))(List3));
show("\nACCUMULATORS:");
show(" => Both Accumulators have already been shown, 1 more subtly so:");
print(" -> Foldl(Pow)(ox1)(List3) = ");
nshow(Foldl(Pow)(ox1)(List3));
print(" -> Foldr(Pow)(ox1)(List3) = ");
nprint(Foldr(Pow)(ox1)(List3));
show(" // \"Foldr\" = \"BackwardAtomic\" . \"Foldl\"!");
show("\nMAX/MIN:");
print(" => Max(List1) = ");
nshow(Max(List1));
print(" => Min(List1) = ");
nshow(Min(List1));
show("\nLISP-STYLE ACCESS:");
print(" => List1 = ");
VoidMap(nprint)(List1);
print("\n => car(List1) = ");
nshow(car(List1));
print(" => cdr(List1) = ");
VoidMap(nprint)(cdr(List1));
print("\n => cadr(List1) = ");
nshow(cadr(List1));
print(" => caddr(List1) = ");
nshow(caddr(List1));
print(" => cadddr(List1) = ");
nshow(cadddr(List1));
show("\nLISTS OF LISTS:");
const auto SuperList1 = ListN(ox3) (ListN(ox2) (ox4) (ox5)) (ListN(ox3) (oxa) (ox2) (ox3)) (ListN(ox1) (ox8));
show(" => We have defined a list of 3 lists:");
show(" (*) // SuperList1 = [ [4, 5], [10, 2, 3], [8] ]");
show(" (0) SuperList1 = ListN(ox3) (ListN(ox2) (ox4) (ox5)) (ListN(ox3) (oxa) (ox2) (ox3)) (ListN(ox1) (ox8));\n");
print(" => Head(Head(SuperList1)) = ");
nshow(Head(Head(SuperList1)));
print(" => Last(Last(SuperList1)) = ");
nshow(Last(Last(SuperList1)));
print(" => Nth(ox1)(Nth(ox2)(SuperList1)) = ");
nshow(Nth(ox1)(Nth(ox2)(SuperList1)));
show(" => Using LISP Notation:");
print(" -> caar(SuperList1) = ");
nshow(caar(SuperList1));
print(" -> caaddr(SuperList1) = ");
nshow(caaddr(SuperList1));
print(" -> caadr(SuperList1) = ");
nshow(caadr(SuperList1));
show("\nLIST OF MULTIPLE-TYPED ELTS:");
show(" => We have defined a list w/ a float, String, & Church Numeral:");
show(" (0) multi_type_list = ListN(ox3) (3.14159) (\"Talk about dynamic!\") (oxd);");
const auto multi_type_list = ListN(ox3) (3.14159) ("Talk about dynamic!") (oxd);
print("\n => car(multi_type_list) = ");
show(car(multi_type_list));
print(" => cadr(multi_type_list) = ");
show(cadr(multi_type_list));
print(" => caddr(multi_type_list) = ");
nshow(caddr(multi_type_list));
show("\nBye!\n");
return 0;
}
| 35.13245
| 121
| 0.507823
|
jrandleman
|
45774a243eba9339b1d84de55198c4399b64d3f2
| 954
|
hpp
|
C++
|
main/inou_rand_api.hpp
|
tamim-asif/lgraph-private
|
733bbcd9e14a9850580b51c011e33785ab758b9d
|
[
"BSD-3-Clause"
] | null | null | null |
main/inou_rand_api.hpp
|
tamim-asif/lgraph-private
|
733bbcd9e14a9850580b51c011e33785ab758b9d
|
[
"BSD-3-Clause"
] | null | null | null |
main/inou_rand_api.hpp
|
tamim-asif/lgraph-private
|
733bbcd9e14a9850580b51c011e33785ab758b9d
|
[
"BSD-3-Clause"
] | null | null | null |
#include "inou_rand.hpp"
#include "main_api.hpp"
class Inou_rand_api {
protected:
static void tolg(Eprp_var &var) {
Inou_rand rand;
for(const auto &l:var.dict) {
rand.set(l.first,l.second);
}
std::vector<LGraph *> lgs = rand.tolg();
if (lgs.empty()) {
Main_api::warn(fmt::format("inou.rand could not create a random {} lgraph in {} path", var.get("name"), var.get("path")));
}else{
assert(lgs.size()==1); // rand only generated one graph at a time
var.add(lgs[0]);
}
}
public:
static void setup(Eprp &eprp) {
Eprp_method m1("inou.rand", "generate a random lgraph", &Inou_rand_api::tolg);
m1.add_label_optional("path","lgraph path");
m1.add_label_required("name","lgraph name");
m1.add_label_optional("seed","random seed");
m1.add_label_optional("size","lgraph size");
m1.add_label_optional("eratio","edge ratio for random");
eprp.register_method(m1);
}
};
| 24.461538
| 128
| 0.638365
|
tamim-asif
|
457799f6c60e7d7a5d1685b8781ec801a174ca43
| 3,127
|
hpp
|
C++
|
GameEngine/Systems/ButtonSystem.hpp
|
Epitech-Tek2/superBonobros2
|
525ab414215f5b67829bf200797c2055141cb7b9
|
[
"MIT"
] | null | null | null |
GameEngine/Systems/ButtonSystem.hpp
|
Epitech-Tek2/superBonobros2
|
525ab414215f5b67829bf200797c2055141cb7b9
|
[
"MIT"
] | null | null | null |
GameEngine/Systems/ButtonSystem.hpp
|
Epitech-Tek2/superBonobros2
|
525ab414215f5b67829bf200797c2055141cb7b9
|
[
"MIT"
] | null | null | null |
/*
** EPITECH PROJECT, 2020
** B-CPP-501-STG-5-1-rtype-romuald1.soultan
** File description:
** ButtonSystem
*/
#ifndef BUTTONSYSTEM_HPP_
#define BUTTONSYSTEM_HPP_
#include "ASystem.hpp"
#include "ECS.hpp"
#include "AScene.hpp"
#include "AGame.hpp"
#include "ASystem.hpp"
#include "ClickableComponent.hpp"
#include "ShapeComponent.hpp"
#include "Transform2DComponent.hpp"
#include "BaseColorComponent.hpp"
#include "TextureComponent.hpp"
#include "ButtonActionComponent.hpp"
namespace gameEngine {
class ButtonSystem : public gameEngine::ASystem {
public:
ButtonSystem(gameEngine::ECS *ecs) : gameEngine::ASystem(ecs) {}
void init(gameEngine::ECS *ecs)
{
ecs->systemAddDependances<gameEngine::ClickableComponent>(this);
ecs->systemAddDependances<gameEngine::TextureComponent>(this);
ecs->systemAddDependances<gameEngine::ShapeComponent>(this);
ecs->systemAddDependances<gameEngine::Transform2DComponent>(this);
ecs->systemAddDependances<gameEngine::BaseColorComponent>(this);
ecs->systemAddDependances<gameEngine::ButtonActionComponent>(this);
}
~ButtonSystem(void) = default;
private:
void action(std::shared_ptr<gameEngine::AEntity> entity, float)
{
Color const &baseColor = _ecs->getEntityComponent<gameEngine::BaseColorComponent>(entity)._color;
Color &color = _ecs->getEntityComponent<gameEngine::TextureComponent>(entity)._color;
ClickableComponent::MouseState const state = _ecs->getEntityComponent<gameEngine::ClickableComponent>(entity).state;
ButtonActionComponent &action = _ecs->getEntityComponent<gameEngine::ButtonActionComponent>(entity);
short red = 0;
short green = 0;
short blue = 0;
switch (state) {
case ClickableComponent::MouseState::OnButton:
red = baseColor.red - 30;
green = baseColor.green - 30;
blue = baseColor.blue - 30;
color.red = (red < 0 ? 0:red);
color.green = (green < 0 ? 0:green);
color.blue = (blue < 0 ? 0:blue);
break;
case ClickableComponent::MouseState::HoldClick:
red = baseColor.red - 60;
green = baseColor.green - 60;
blue = baseColor.blue - 60;
color.red = (red < 0 ? 0:red);
color.green = (green < 0 ? 0:green);
color.blue = (blue < 0 ? 0:blue);
break;
case ClickableComponent::MouseState::Released:
action._action();
break;
default:
color = baseColor;
break;
}
}
};
}
#endif /* !BUTTONSYSTEM_HPP_ */
| 39.582278
| 132
| 0.549089
|
Epitech-Tek2
|
4577c52083767b5b1ed8420cedc7326e012220ed
| 875
|
cpp
|
C++
|
coast/modules/Renderer/SubStringRenderer.cpp
|
zer0infinity/CuteForCoast
|
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
|
[
"BSD-3-Clause"
] | null | null | null |
coast/modules/Renderer/SubStringRenderer.cpp
|
zer0infinity/CuteForCoast
|
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
|
[
"BSD-3-Clause"
] | null | null | null |
coast/modules/Renderer/SubStringRenderer.cpp
|
zer0infinity/CuteForCoast
|
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
#include "SubStringRenderer.h"
RegisterRenderer(SubStringRenderer);
void SubStringRenderer::RenderAll(std::ostream &reply, Context &ctx, const ROAnything &config) {
StartTrace(SubStringRenderer.RenderAll);
String str;
Renderer::RenderOnString(str, ctx, config["String"]);
if (str.Length()) {
long start = RenderToString(ctx, config["Start"]).AsLong(0L);
long len = RenderToString(ctx, config["Length"]).AsLong(-1L);
String ret(str.SubString(start, len));
Trace("SubString(" << start << "," << len << ")-->" << ret);
reply << ret;
}
}
| 38.043478
| 102
| 0.718857
|
zer0infinity
|
4578b38a6b3f01fa80365cd43053e30c3d4c7513
| 65
|
cpp
|
C++
|
cpp_data_structure_and_algorithm/day9/IndexMaxHeap.cpp
|
xcyi2017/Agorithm
|
bae9918b0758624ecd1f94a3ca1692050c193a29
|
[
"Apache-2.0"
] | 1
|
2020-11-15T09:40:47.000Z
|
2020-11-15T09:40:47.000Z
|
cpp_data_structure_and_algorithm/day9/IndexMaxHeap.cpp
|
xcyi2017/Agorithm
|
bae9918b0758624ecd1f94a3ca1692050c193a29
|
[
"Apache-2.0"
] | null | null | null |
cpp_data_structure_and_algorithm/day9/IndexMaxHeap.cpp
|
xcyi2017/Agorithm
|
bae9918b0758624ecd1f94a3ca1692050c193a29
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by xcy on 2020/10/5.
//
#include "IndexMaxHeap.h"
| 10.833333
| 31
| 0.630769
|
xcyi2017
|
457bc8521fdebe0808d93f1cd867ad9f31f5b80e
| 835
|
cpp
|
C++
|
CameraShake/MyCameraShake.cpp
|
H4DC0R3/unrealcpp
|
b0f5667cb20711d740a6fb0cb5064efc6873c948
|
[
"MIT"
] | 765
|
2018-01-03T14:58:37.000Z
|
2022-03-29T16:03:13.000Z
|
CameraShake/MyCameraShake.cpp
|
shyaZhou/unrealcpp
|
e998d89ce6c8d5484c084f395d2eca5e247b88bf
|
[
"MIT"
] | 1
|
2019-09-26T09:33:50.000Z
|
2020-12-11T05:17:13.000Z
|
CameraShake/MyCameraShake.cpp
|
shyaZhou/unrealcpp
|
e998d89ce6c8d5484c084f395d2eca5e247b88bf
|
[
"MIT"
] | 166
|
2018-02-20T07:36:12.000Z
|
2022-03-25T07:49:03.000Z
|
// Harrison McGuire
// UE4 Version 4.20.2
// https://github.com/Harrison1/unrealcpp
// https://severallevels.io
// https://harrisonmcguire.com
#include "MyCameraShake.h"
// Helpful Links
// http://api.unrealengine.com/INT/API/Runtime/Engine/Camera/UCameraShake/index.html
//
// Great explanation of camera shake values
// https://www.youtube.com/watch?v=Oice8gdpX6s
#include "MyCameraShake.h"
// Sets default values
UMyCameraShake::UMyCameraShake()
{
OscillationDuration = 0.25f;
OscillationBlendInTime = 0.05f;
OscillationBlendOutTime = 0.05f;
RotOscillation.Pitch.Amplitude = FMath::RandRange(5.0f, 10.0f);
RotOscillation.Pitch.Frequency = FMath::RandRange(25.0f, 35.0f);
RotOscillation.Yaw.Amplitude = FMath::RandRange(5.0f, 10.0f);
RotOscillation.Yaw.Frequency = FMath::RandRange(25.0f, 35.0f);
}
| 27.833333
| 84
| 0.731737
|
H4DC0R3
|
4584d9705bc128ecf32ee9da4ab82849fdd83607
| 2,241
|
hpp
|
C++
|
falcon/mpl/placeholders.hpp
|
jonathanpoelen/falcon
|
5b60a39787eedf15b801d83384193a05efd41a89
|
[
"MIT"
] | 2
|
2018-02-02T14:19:59.000Z
|
2018-05-13T02:48:24.000Z
|
falcon/mpl/placeholders.hpp
|
jonathanpoelen/falcon
|
5b60a39787eedf15b801d83384193a05efd41a89
|
[
"MIT"
] | null | null | null |
falcon/mpl/placeholders.hpp
|
jonathanpoelen/falcon
|
5b60a39787eedf15b801d83384193a05efd41a89
|
[
"MIT"
] | null | null | null |
#ifndef FALCON_MPL_PLACEHOLDERS_HPP
#define FALCON_MPL_PLACEHOLDERS_HPP
#include <falcon/mpl/arg.hpp>
namespace falcon {
namespace mpl {
namespace placeholders {
using _1 = arg<1>;
using _2 = arg<2>;
using _3 = arg<3>;
using _4 = arg<4>;
using _5 = arg<5>;
using _6 = arg<6>;
using _7 = arg<7>;
using _8 = arg<8>;
using _9 = arg<9>;
using _10 = arg<10>;
using _11 = arg<11>;
using _12 = arg<12>;
using _13 = arg<13>;
using _14 = arg<14>;
using _15 = arg<15>;
using _16 = arg<16>;
using _17 = arg<17>;
using _18 = arg<18>;
using _19 = arg<19>;
using _20 = arg<20>;
using _21 = arg<21>;
using _22 = arg<22>;
using _23 = arg<23>;
using _24 = arg<24>;
using _25 = arg<25>;
using _26 = arg<26>;
using _27 = arg<27>;
using _28 = arg<28>;
using _29 = arg<29>;
using _30 = arg<30>;
using _31 = arg<31>;
using _32 = arg<32>;
using _33 = arg<33>;
using _34 = arg<34>;
using _35 = arg<35>;
using _36 = arg<36>;
using _37 = arg<37>;
using _38 = arg<38>;
using _39 = arg<39>;
using _40 = arg<40>;
using _41 = arg<41>;
using _42 = arg<42>;
using _43 = arg<43>;
using _44 = arg<44>;
using _45 = arg<45>;
using _46 = arg<46>;
using _47 = arg<47>;
using _48 = arg<48>;
using _49 = arg<49>;
using _50 = arg<50>;
using _51 = arg<51>;
using _52 = arg<52>;
using _53 = arg<53>;
using _54 = arg<54>;
using _55 = arg<55>;
using _56 = arg<56>;
using _57 = arg<57>;
using _58 = arg<58>;
using _59 = arg<59>;
using _60 = arg<60>;
using _61 = arg<61>;
using _62 = arg<62>;
using _63 = arg<63>;
using _64 = arg<64>;
using _65 = arg<65>;
using _66 = arg<66>;
using _67 = arg<67>;
using _68 = arg<68>;
using _69 = arg<69>;
using _70 = arg<70>;
using _71 = arg<71>;
using _72 = arg<72>;
using _73 = arg<73>;
using _74 = arg<74>;
using _75 = arg<75>;
using _76 = arg<76>;
using _77 = arg<77>;
using _78 = arg<78>;
using _79 = arg<79>;
using _80 = arg<80>;
using _81 = arg<81>;
using _82 = arg<82>;
using _83 = arg<83>;
using _84 = arg<84>;
using _85 = arg<85>;
using _86 = arg<86>;
using _87 = arg<87>;
using _88 = arg<88>;
using _89 = arg<89>;
using _90 = arg<90>;
using _91 = arg<91>;
using _92 = arg<92>;
using _93 = arg<93>;
using _94 = arg<94>;
using _95 = arg<95>;
using _96 = arg<96>;
using _97 = arg<97>;
using _98 = arg<98>;
using _99 = arg<99>;
}
}
}
#endif
| 19.486957
| 35
| 0.629183
|
jonathanpoelen
|
4586a2f0f7b631495373c018c934fe3720aeba6d
| 2,998
|
cc
|
C++
|
sieve2015/src/presieved_primes.cc
|
mhdeleglise/Gh
|
21a0b9bd53ae9de17f8b99040cac95cd6e1897e4
|
[
"MIT"
] | null | null | null |
sieve2015/src/presieved_primes.cc
|
mhdeleglise/Gh
|
21a0b9bd53ae9de17f8b99040cac95cd6e1897e4
|
[
"MIT"
] | null | null | null |
sieve2015/src/presieved_primes.cc
|
mhdeleglise/Gh
|
21a0b9bd53ae9de17f8b99040cac95cd6e1897e4
|
[
"MIT"
] | null | null | null |
#include<mylib.h>
namespace presieved_primes{
long32 presieve_base;
long32 number_of_presieve_primes;
long32 sum_of_presieve_primes;
long32 small_primes[5] = {2, 3, 5, 7, 11};
int primes_initialized = 0;
long* Sp;
void init_presieve(int nbps) {
switch (nbps) {
case 2:
presieve_base = 6;
number_of_presieve_primes = 2;
sum_of_presieve_primes = 5;
number_of_presieve_primes = 2;
break;
case 3:
presieve_base = 30;
number_of_presieve_primes = 3;
sum_of_presieve_primes = 10;
number_of_presieve_primes = 3;
break;
case 4:
presieve_base = 210;
number_of_presieve_primes = 4;
sum_of_presieve_primes = 17;
number_of_presieve_primes = 4;
break;
case 5:
presieve_base = 2310;
number_of_presieve_primes = 5;
sum_of_presieve_primes = 28;
number_of_presieve_primes = 5;
break;
}
}
prime_table<sieve_by_slice<bit_table_cnte, long> > T;
long32
prime(long32 i) { return T.prime(i);}
long32
piB(long32 i) { return T.piB(i); }
long32
number_of_primes() { return T.get_number_of_primes(); }
long32
max_prime() {return prime(T.get_number_of_primes());}
long32
index_of_first_prime_bigger_than(long32 x)
{
return T.index_of_first_prime_bigger_than(x);
}
void
init_prime_table(long32 upto, int nbps)
{
if (nbps > 5) {
cout << "init_prime_table error called with upto = " << upto << " and nbps = " << nbps << endl\
<< "nbps, the number_of_presieved primes must be less or equal to 5\n";
error();
}
init_presieve(nbps);
//cout << "init_prime_table : presieve_base set to " << presieved_primes::presieve_base << endl;
T.create(upto, presieved_primes::presieve_base);
primes_initialized = 1;
#ifdef DEBUG_PRIMES
cout << "\nprime_table::is_created first non presieved prime = " << presieved_primes::prime(1) << endl;;
cout << "presieved_primes::number_of_primes() = " << presieved_primes::number_of_primes() << endl;
cout << "presieved_primes::max_prime() = " << presieved_primes::max_prime() << endl << endl;
#endif
}
void display() {
cout << "\nPrime_table created\n";
cout << " number of presieved primes = " << presieved_primes::number_of_presieve_primes << endl;
cout << " first non presieved prime = " << presieved_primes::prime(1) << endl;;
cout << " presieved_primes::number_of_primes() = " << presieved_primes::number_of_primes() << endl;
cout << " presieved_primes::max_prime() = " << presieved_primes::max_prime() << endl << endl;
}
void
display_prime_table() { T.display();}
void init_sum_primes() {
Sp= new long[1+number_of_primes()];
long sum=0;
for (int i=1; i <= number_of_primes(); i++) {
sum+=T.prime(i);
Sp[i]=sum;
}
}
}
| 29.106796
| 110
| 0.616077
|
mhdeleglise
|
4586e007716ddb33e39503120febcfcd9f469dcd
| 2,706
|
cpp
|
C++
|
checks/rng.cpp
|
vster/OpenCL
|
fb29aead4e6345e23f3f7ba5fb038fa1fd217e10
|
[
"BSD-2-Clause"
] | 46
|
2015-12-04T17:12:58.000Z
|
2022-03-11T04:30:49.000Z
|
checks/rng.cpp
|
vster/OpenCL
|
fb29aead4e6345e23f3f7ba5fb038fa1fd217e10
|
[
"BSD-2-Clause"
] | null | null | null |
checks/rng.cpp
|
vster/OpenCL
|
fb29aead4e6345e23f3f7ba5fb038fa1fd217e10
|
[
"BSD-2-Clause"
] | 23
|
2016-10-24T09:18:14.000Z
|
2022-02-25T02:11:35.000Z
|
/* This file is in the public domain */
#include <string>
#include <opencl/filters.h>
#include <opencl/square.h>
#include <opencl/randpool.h>
#include <opencl/x917.h>
#if defined(OPENCL_EXT_ENTROPY_SRC_DEVRANDOM)
#include <opencl/devrand.h>
#endif
#if defined(OPENCL_EXT_ENTROPY_SRC_PTHREAD)
#include <opencl/pthr_ent.h>
#endif
using namespace OpenCL;
/*************************************************/
/*
This is the global RNG used in various spots. Seems to make most sense to
declare it here.
*/
OpenCL::X917<OpenCL::Square> local_rng;
OpenCL::RandomNumberGenerator& rng = local_rng;
/*************************************************/
/* Not too useful generally; just dumps random bits */
template<typename R>
class RNG_Filter : public Filter
{
public:
void write(const byte[], u32bit);
private:
static const u32bit BUFFERSIZE = OpenCL::DEFAULT_BUFFERSIZE;
R rng;
SecureBuffer<byte, BUFFERSIZE> buffer;
u32bit position;
};
template<typename B>
void RNG_Filter<B>::write(const byte input[], u32bit length)
{
buffer.copy(position, input, length);
if(position + length >= BUFFERSIZE)
{
rng.randomize(buffer, BUFFERSIZE);
send(buffer, BUFFERSIZE);
input += (BUFFERSIZE - position);
length -= (BUFFERSIZE - position);
while(length >= BUFFERSIZE)
{
/* This actually totally ignores the input, but it doesn't matter,
because this is only for benchmark purposes and we just want to
test speed. Anyway, if the RNG is good you can't tell the diff */
rng.randomize(buffer, BUFFERSIZE);
send(buffer, BUFFERSIZE);
input += BUFFERSIZE;
length -= BUFFERSIZE;
}
buffer.copy(input, length);
position = 0;
}
position += length;
}
/* A wrappr class to convert an EntropySource into a psudoe-RNG */
template<typename E>
class ES_TO_RNG
{
public:
void randomize(byte buf[], u32bit size)
{
u32bit need = size;
while(need) need -= es.slow_poll(buf + size - need, need);
}
private:
E es;
};
Filter* lookup_rng(const std::string& algname)
{
if(algname == "X917<Square>")
return new RNG_Filter< X917<Square> >;
else if(algname == "Randpool")
return new RNG_Filter<Randpool>;
#if defined(OPENCL_EXT_ENTROPY_SRC_DEVRANDOM)
else if(algname == "EntropySrc_DevRandom")
return new RNG_Filter< ES_TO_RNG<DevRandom_EntropySource> >;
#endif
#if defined(OPENCL_EXT_ENTROPY_SRC_PTHREAD)
else if(algname == "EntropySrc_Pthread")
return new RNG_Filter< ES_TO_RNG<Pthread_EntropySource> >;
#endif
else return 0;
}
| 26.271845
| 77
| 0.636364
|
vster
|
4588b724efd0ce0f13cef267f2da3c49f709e55c
| 8,657
|
cpp
|
C++
|
intro/messageworld/messageworld.cpp
|
return/BeOSSampleCode
|
ca5a319fecf425a69e944f3c928a85011563a932
|
[
"BSD-3-Clause"
] | 5
|
2018-09-09T21:01:57.000Z
|
2022-03-27T10:01:27.000Z
|
intro/messageworld/messageworld.cpp
|
return/BeOSSampleCode
|
ca5a319fecf425a69e944f3c928a85011563a932
|
[
"BSD-3-Clause"
] | null | null | null |
intro/messageworld/messageworld.cpp
|
return/BeOSSampleCode
|
ca5a319fecf425a69e944f3c928a85011563a932
|
[
"BSD-3-Clause"
] | 5
|
2018-04-03T01:45:23.000Z
|
2021-05-14T08:23:01.000Z
|
//
// Menu World
//
// A sample program demonstrating the basics of using
// the BMessage and BMessenger classes.
//
// Written by: Eric Shepherd
//
/*
Copyright 1999, Be Incorporated. All Rights Reserved.
This file may be used under the terms of the Be Sample Code License.
*/
#include <Application.h>
#include <Messenger.h>
#include <Message.h>
#include <Roster.h>
#include <Window.h>
#include <View.h>
#include <MenuBar.h>
#include <Menu.h>
#include <MenuItem.h>
#include <string.h>
#include <stdio.h>
// Application's signature
const char *APP_SIGNATURE = "application/x-vnd.Be-MessageWorld";
// Messages for window registry with application
const uint32 WINDOW_REGISTRY_ADD = 'WRad';
const uint32 WINDOW_REGISTRY_SUB = 'WRsb';
const uint32 WINDOW_REGISTRY_ADDED = 'WRdd';
// Messages for menu commands
const uint32 MENU_FILE_NEW = 'MFnw';
const uint32 MENU_FILE_OPEN = 'MFop';
const uint32 MENU_FILE_CLOSE = 'MFcl';
const uint32 MENU_FILE_SAVE = 'MFsv';
const uint32 MENU_FILE_SAVEAS = 'MFsa';
const uint32 MENU_FILE_PAGESETUP = 'MFps';
const uint32 MENU_FILE_PRINT = 'MFpr';
const uint32 MENU_FILE_QUIT = 'MFqu';
const uint32 MENU_OPT_HELLO = 'MOhl';
const char *STRING_HELLO = "Hello World!";
const char *STRING_GOODBYE = "Goodbye World!";
//
// HelloView class
//
// This class defines the view in which the "Hello World"
// message will be drawn.
//
class HelloView : public BView {
public:
HelloView(BRect frame);
virtual void Draw(BRect updateRect);
void SetString(const char *s);
private:
char message[128];
};
//
// HelloView::HelloView
//
// Constructs the view we'll be drawing in.
// As you see, it doesn't do much.
//
HelloView::HelloView(BRect frame)
: BView(frame, "HelloView", B_FOLLOW_ALL_SIDES, B_WILL_DRAW) {
SetString(STRING_HELLO);
}
//
// HelloView::SetString
//
// Sets the message to draw in the view.
//
void HelloView::SetString(const char *s) {
if (strlen(s) < 127) {
strcpy(message, s);
}
}
//
// HelloView::Draw
//
// This function is called whenever our view
// needs to be redrawn. This happens only because
// we specified B_WILL_DRAW for the flags when
// we created the view (see the constructor).
//
// The updateRect is the rectangle that needs to be
// redrawn. We're ignoring it, but you can use it to
// speed up your refreshes for more complex programs.
//
void HelloView::Draw(BRect updateRect) {
MovePenTo(BPoint(20,75)); // Move pen
DrawString(message);
}
//
// HelloWindow class
//
// This class defines the hello world window.
//
class HelloWindow : public BWindow {
public:
HelloWindow(BRect frame);
~HelloWindow();
virtual bool QuitRequested();
virtual void MessageReceived(BMessage *message);
private:
void Register(bool need_id);
void Unregister(void);
BMenuBar *menubar;
HelloView *helloview;
};
//
// HelloWindow::HelloWindow
//
// Constructs the window we'll be drawing into.
//
HelloWindow::HelloWindow(BRect frame)
: BWindow(frame, "Untitled ", B_TITLED_WINDOW,
B_NOT_RESIZABLE|B_NOT_ZOOMABLE) {
BRect r;
BMenu *menu;
BMenuItem *item;
// Add the menu bar
r = Bounds();
menubar = new BMenuBar(r, "menu_bar");
AddChild(menubar);
// Add File menu to menu bar
menu = new BMenu("File");
menu->AddItem(new BMenuItem("New", new BMessage(MENU_FILE_NEW), 'N'));
menu->AddItem(new BMenuItem("Open" B_UTF8_ELLIPSIS,
new BMessage(MENU_FILE_OPEN), 'O'));
menu->AddItem(new BMenuItem("Close", new BMessage(MENU_FILE_CLOSE), 'W'));
menu->AddSeparatorItem();
menu->AddItem(new BMenuItem("Save", new BMessage(MENU_FILE_SAVE), 'S'));
menu->AddItem(new BMenuItem("Save as" B_UTF8_ELLIPSIS,
new BMessage(MENU_FILE_SAVEAS)));
menu->AddSeparatorItem();
menu->AddItem(new BMenuItem("Page Setup" B_UTF8_ELLIPSIS,
new BMessage(MENU_FILE_PAGESETUP)));
menu->AddItem(new BMenuItem("Print" B_UTF8_ELLIPSIS,
new BMessage(MENU_FILE_PRINT), 'P'));
menu->AddSeparatorItem();
menu->AddItem(new BMenuItem("Quit", new BMessage(MENU_FILE_QUIT), 'Q'));
menubar->AddItem(menu);
// Add Options menu to menu bar
menu = new BMenu("Options");
item=new BMenuItem("Say Hello", new BMessage(MENU_OPT_HELLO));
item->SetMarked(true);
menu->AddItem(item);
menubar->AddItem(menu);
// Add the drawing view
r.top = menubar->Bounds().bottom+1;
AddChild(helloview = new HelloView(r));
// Tell the application that there's one more window
// and get the number for this untitled window.
Register(true);
Show();
}
//
// HelloWindow::~HelloWindow
//
// Destruct the window. This calls Unregister().
//
HelloWindow::~HelloWindow() {
Unregister();
}
//
// HelloWindow::MessageReceived
//
// Called when a message is received by our
// application.
//
void HelloWindow::MessageReceived(BMessage *message) {
switch(message->what) {
case WINDOW_REGISTRY_ADDED:
{
char s[22];
int32 id = 0;
if (message->FindInt32("new_window_number", &id) == B_OK) {
sprintf(s, "Untitled %ld", id);
SetTitle(s);
}
}
break;
case MENU_FILE_NEW:
{
BRect r;
r = Frame();
r.OffsetBy(20,20);
new HelloWindow(r);
}
break;
case MENU_FILE_CLOSE:
Quit();
break;
case MENU_FILE_QUIT:
be_app->PostMessage(B_QUIT_REQUESTED);
break;
case MENU_OPT_HELLO:
{
BMenuItem *item;
const char *s;
bool mark;
message->FindPointer("source", (void **) &item);
if (item->IsMarked()) {
s = STRING_GOODBYE;
mark = false;
}
else {
s = STRING_HELLO;
mark = true;
}
helloview->SetString(s);
item->SetMarked(mark);
helloview->Invalidate();
}
break;
default:
BWindow::MessageReceived(message);
break;
}
}
//
// HelloWindow::Register
//
// Since MessageWorld can have multiple windows and
// we need to know when there aren't any left so the
// application can be shut down, this function is used
// to tell the application that a new window has been
// opened.
//
// If the need_id argument is true, we'll specify true
// for the "need_id" field in the message we send; this
// will cause the application to send back a
// WINDOW_REGISTRY_ADDED message containing the window's
// unique ID number. If this argument is false, we won't
// request an ID.
//
void HelloWindow::Register(bool need_id) {
BMessenger messenger(APP_SIGNATURE);
BMessage message(WINDOW_REGISTRY_ADD);
message.AddBool("need_id", need_id);
messenger.SendMessage(&message, this);
}
//
// HelloWindow::Unregister
//
// Unregisters a window. This tells the application that
// one fewer windows are open. The application will
// automatically quit if the count goes to zero because
// of this call.
//
void HelloWindow::Unregister(void) {
BMessenger messenger(APP_SIGNATURE);
messenger.SendMessage(new BMessage(WINDOW_REGISTRY_SUB));
}
//
// HelloWindow::QuitRequested
//
// Here we just give permission to close the window.
//
bool HelloWindow::QuitRequested() {
return true;
}
//
// HelloApp class
//
// This class, derived from BApplication, defines the
// Hello World application itself.
//
class HelloApp : public BApplication {
public:
HelloApp();
virtual void MessageReceived(BMessage *message);
private:
int32 window_count;
int32 next_untitled_number;
};
//
// HelloApp::HelloApp
//
// The constructor for the HelloApp class. This
// will create our window.
//
HelloApp::HelloApp()
: BApplication(APP_SIGNATURE) {
BRect windowRect;
windowRect.Set(50,50,349,399);
window_count = 0; // No windows yet
next_untitled_number = 1; // Next window is "Untitled 1"
new HelloWindow(windowRect);
}
//
// HelloApp::MessageReceived
//
// Handle incoming messages. In particular, handle the
// WINDOW_REGISTRY_ADD and WINDOW_REGISTRY_SUB messages.
//
void HelloApp::MessageReceived(BMessage *message) {
switch(message->what) {
case WINDOW_REGISTRY_ADD:
{
bool need_id = false;
if (message->FindBool("need_id", &need_id) == B_OK) {
if (need_id) {
BMessage reply(WINDOW_REGISTRY_ADDED);
reply.AddInt32("new_window_number", next_untitled_number);
message->SendReply(&reply);
next_untitled_number++;
}
window_count++;
}
break;
}
case WINDOW_REGISTRY_SUB:
window_count--;
if (!window_count) {
Quit();
}
break;
default:
BApplication::MessageReceived(message);
break;
}
}
//
// main
//
// The main() function's only real job in a basic BeOS
// application is to create the BApplication object
// and run it.
//
int main(void) {
HelloApp theApp; // The application object
theApp.Run();
return 0;
}
| 21.696742
| 75
| 0.688922
|
return
|
458900190893fa28482feb5dd9be4cf587142595
| 5,591
|
cpp
|
C++
|
aoc2018_day21.cpp
|
bluespeck/aoc_2018
|
d847613516bd1e0a6c1a7a0c32cc093a3f558dd4
|
[
"MIT"
] | null | null | null |
aoc2018_day21.cpp
|
bluespeck/aoc_2018
|
d847613516bd1e0a6c1a7a0c32cc093a3f558dd4
|
[
"MIT"
] | null | null | null |
aoc2018_day21.cpp
|
bluespeck/aoc_2018
|
d847613516bd1e0a6c1a7a0c32cc093a3f558dd4
|
[
"MIT"
] | 1
|
2018-12-15T11:50:33.000Z
|
2018-12-15T11:50:33.000Z
|
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdint>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
#include <sstream>
#include <utility>
using Registers = std::array<int64_t, 6>;
struct Instruction
{
int opcode;
int a, b, c;
};
using Program = std::vector<Instruction>;
void addr(int a, int b, int c, Registers& reg)
{
reg[c] = reg[a] + reg[b];
}
void addi(int a, int b, int c, Registers®)
{
reg[c] = reg[a] + b;
}
void mulr(int a, int b, int c, Registers®)
{
reg[c] = reg[a] * reg[b];
}
void muli(int a, int b, int c, Registers®)
{
reg[c] = reg[a] * b;
}
void banr(int a, int b, int c, Registers®)
{
reg[c] = reg[a] & reg[b];
}
void bani(int a, int b, int c, Registers®)
{
reg[c] = reg[a] & b;
}
void borr(int a, int b, int c, Registers®)
{
reg[c] = reg[a] | reg[b];
}
void bori(int a, int b, int c, Registers®)
{
reg[c] = reg[a] | b;
}
void setr(int a, int b, int c, Registers®)
{
reg[c] = reg[a];
}
void seti(int a, int b, int c, Registers®)
{
reg[c] = a;
}
void gtir(int a, int b, int c, Registers®)
{
reg[c] = (a > reg[b]) ? 1 : 0;
}
void gtri(int a, int b, int c, Registers®)
{
reg[c] = (reg[a] > b) ? 1 : 0;
}
void gtrr(int a, int b, int c, Registers®)
{
reg[c] = (reg[a] > reg[b]) ? 1 : 0;
}
void eqir(int a, int b, int c, Registers®)
{
reg[c] = (a == reg[b]) ? 1 : 0;
}
void eqri(int a, int b, int c, Registers®)
{
reg[c] = (reg[a] == b) ? 1 : 0;
}
void eqrr(int a, int b, int c, Registers®)
{
reg[c] = (reg[a] == reg[b]) ? 1 : 0;
}
using PossibleOpcodeSets = std::array<std::set<int>, 16>;
using Op = void(*)(int, int, int, Registers&);
using OpcodeTranslationTable = std::array<int, 16>;
std::array<Op, 16> operations{
addr, addi,
mulr, muli,
banr, bani,
borr, bori,
setr, seti,
gtir, gtri, gtrr,
eqir, eqri, eqrr
};
int64_t RunProgram(const Program& program, Registers& regs, int ipr, int maxNumSteps = 0)
{
int64_t numSteps = 0;
while (regs[ipr] < program.size())
{
auto& instruction = program[regs[ipr]];
{
std::cout << "ip=" << regs[ipr];
std::cout << " [";
for (int i = 0; i < 5; i++)
std::cout << regs[i] << ", ";
std::cout << regs[5] << "] " << instruction.opcode << " " << instruction.a << " " << instruction.b << " " << instruction.c << " ";
}
operations[instruction.opcode](instruction.a, instruction.b, instruction.c, regs);
{
std::cout << " [";
for (int i = 0; i < 5; i++)
std::cout << regs[i] << ", ";
std::cout << regs[5] << "]\n";
}
regs[ipr] ++;
numSteps++;
}
return numSteps;
}
void ReadInput(Program& program, int& ip)
{
std::cin.ignore(4);
std::cin >> ip;
std::map<std::string, int> nameToOpcode;
nameToOpcode["addr"] = 0;
nameToOpcode["addi"] = 1;
nameToOpcode["mulr"] = 2;
nameToOpcode["muli"] = 3;
nameToOpcode["banr"] = 4;
nameToOpcode["bani"] = 5;
nameToOpcode["borr"] = 6;
nameToOpcode["bori"] = 7;
nameToOpcode["setr"] = 8;
nameToOpcode["seti"] = 9;
nameToOpcode["gtir"] = 10;
nameToOpcode["gtri"] = 11;
nameToOpcode["gtrr"] = 12;
nameToOpcode["eqir"] = 13;
nameToOpcode["eqri"] = 14;
nameToOpcode["eqrr"] = 15;
while (std::cin)
{
std::string instructionName;
Instruction instruction;
std::cin >> instructionName >> instruction.a >> instruction.b >> instruction.c;
if (std::cin)
{
instruction.opcode = nameToOpcode[instructionName];
program.push_back(instruction);
}
}
}
using Regs25Vec = std::vector<std::pair<int64_t, int64_t>>;
Regs25Vec SimulateReg2AndReg5()
{
int64_t reg2 = 15608036;
int64_t reg5 = 65536;
Regs25Vec regPairs;
while (true)
{
if (reg5 < 256)
{
regPairs.push_back(std::make_pair(reg2, reg5));
}
if (reg5 < 256)
{
reg5 = reg2 | 65536;
reg2 = (5234604 + (reg5 & 255)) & 0x00ff'ffff;
reg2 = (reg2 * 65899) & 0x00ff'ffff;
}
else
{
reg5 /= 256;
// bani 5 255 3
// addr 2 3 2
// bani 2 16777215 2
// muli 2 65899 2
// bani 2 16777215 2
reg2 = (reg2 + (reg5 & 255)) & 0x00ff'ffff;
reg2 = (reg2 * 65899) & 0x00ff'ffff;
}
auto it = std::find_if(regPairs.begin(), regPairs.end(), [reg2, reg5](auto& elem) { return elem.first == reg2 && elem.second == reg5; });
if (it != regPairs.end())
{
break;
}
}
return regPairs;
}
int main()
{
//Program program;
//int ipr = 0;
//ReadInput(program, ipr);
//
//{
// Registers regs = { 0, 0, 0, 0, 0, 0 };
// int64_t steps = RunProgram(program, regs, ipr);
// std::cout << "\n" << steps << "\n";
//}
auto regPairs = SimulateReg2AndReg5();
std::cout << regPairs[0].first << "\n";
for (int i = regPairs.size() - 1; i >= 0; --i)
{
auto current = regPairs[i].first;
auto it = std::find_if(regPairs.begin(), regPairs.begin() + i, [current](const std::pair<int64_t, int64_t>& elem) { return elem.first == current; });
if (it == regPairs.begin() + i)
{
std::cout << regPairs[i].first << "\n";
break;
}
}
return 0;
}
| 21.670543
| 152
| 0.524235
|
bluespeck
|
458bf6d617a44dfd03bbc2a44d0c4749251feb4d
| 801
|
cpp
|
C++
|
DEngine/Physics/cdCollisionWorld.cpp
|
norrischiu/DEngine
|
acea553f110b8d10fc7386ff0941b84f6d7ebce7
|
[
"MIT",
"Unlicense"
] | 8
|
2016-05-23T03:08:08.000Z
|
2020-03-02T06:15:16.000Z
|
DEngine/Physics/cdCollisionWorld.cpp
|
norrischiu/DEngine
|
acea553f110b8d10fc7386ff0941b84f6d7ebce7
|
[
"MIT",
"Unlicense"
] | 8
|
2016-06-01T17:00:58.000Z
|
2021-07-21T13:53:41.000Z
|
DEngine/Physics/cdCollisionWorld.cpp
|
norrischiu/DEngine
|
acea553f110b8d10fc7386ff0941b84f6d7ebce7
|
[
"MIT",
"Unlicense"
] | 1
|
2017-09-25T03:39:34.000Z
|
2017-09-25T03:39:34.000Z
|
#include "cdCollisionWorld.h"
/**
void CollisionWorld::addObject(const CollidableObject & object)
{
m_pObjects.push_back(object);
}
void CollisionWorld::addCollide(const Collide & collide)
{
m_pCollide.push_back(collide);
}
void CollisionWorld::computeCollision()
{
bool value = false;
Collide collide;
for (int i = 0; i < m_pObjects.size(); i++)
{
for (int j = i + 1; j < m_pObjects.size(); j++)
{
collide.collision(&m_pObjects[i], &m_pObjects[j]);
// collide.getCollide() returns a boolean value, true means collide, false means not collide
if (collide.getCollide())
addCollide(collide);
//value = true;
}
}
//return value;
}
*/
CollisionWorld * CollisionWorld::GetInstance()
{
if (!m_pInstance)
{
m_pInstance = new CollisionWorld();
}
return m_pInstance;
}
| 19.536585
| 95
| 0.68789
|
norrischiu
|
458c004d2710be6d40ca18beea5ef17f8842f0f1
| 8,708
|
cxx
|
C++
|
MITK/Plugins/uk.ac.ucl.cmic.igiultrasoundoverlayeditor/src/internal/niftkIGIUltrasoundOverlayEditorPreferencePage.cxx
|
NifTK/NifTK
|
2358b333c89ff1bba1c232eecbbcdc8003305dfe
|
[
"BSD-3-Clause"
] | 13
|
2018-07-28T13:36:38.000Z
|
2021-11-01T19:17:39.000Z
|
MITK/Plugins/uk.ac.ucl.cmic.igiultrasoundoverlayeditor/src/internal/niftkIGIUltrasoundOverlayEditorPreferencePage.cxx
|
NifTK/NifTK
|
2358b333c89ff1bba1c232eecbbcdc8003305dfe
|
[
"BSD-3-Clause"
] | null | null | null |
MITK/Plugins/uk.ac.ucl.cmic.igiultrasoundoverlayeditor/src/internal/niftkIGIUltrasoundOverlayEditorPreferencePage.cxx
|
NifTK/NifTK
|
2358b333c89ff1bba1c232eecbbcdc8003305dfe
|
[
"BSD-3-Clause"
] | 10
|
2018-08-20T07:06:00.000Z
|
2021-07-07T07:55:27.000Z
|
/*=============================================================================
NifTK: A software platform for medical image computing.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include "niftkIGIUltrasoundOverlayEditorPreferencePage.h"
#include "niftkIGIUltrasoundOverlayEditor.h"
#include <QLabel>
#include <QPushButton>
#include <QFormLayout>
#include <QRadioButton>
#include <QColorDialog>
#include <QCheckBox>
#include <ctkPathLineEdit.h>
#include <berryIPreferencesService.h>
#include <berryPlatform.h>
namespace niftk
{
const QString IGIUltrasoundOverlayEditorPreferencePage::FIRST_BACKGROUND_STYLE_SHEET("first background color style sheet");
const QString IGIUltrasoundOverlayEditorPreferencePage::SECOND_BACKGROUND_STYLE_SHEET("second background color style sheet");
const QString IGIUltrasoundOverlayEditorPreferencePage::FIRST_BACKGROUND_COLOUR("first background color");
const QString IGIUltrasoundOverlayEditorPreferencePage::SECOND_BACKGROUND_COLOUR("second background color");
const QString IGIUltrasoundOverlayEditorPreferencePage::CLIP_TO_IMAGE_PLANE("clip to imae plane");
//-----------------------------------------------------------------------------
IGIUltrasoundOverlayEditorPreferencePage::IGIUltrasoundOverlayEditorPreferencePage()
: m_MainControl(0)
, m_ColorButton1(NULL)
, m_ColorButton2(NULL)
, m_ClipToImagePlane(NULL)
{
}
//-----------------------------------------------------------------------------
void IGIUltrasoundOverlayEditorPreferencePage::Init(berry::IWorkbench::Pointer )
{
}
//-----------------------------------------------------------------------------
void IGIUltrasoundOverlayEditorPreferencePage::CreateQtControl(QWidget* parent)
{
berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService();
m_IGIUltrasoundOverlayEditorPreferencesNode = prefService->GetSystemPreferences()->Node(IGIUltrasoundOverlayEditor::EDITOR_ID);
m_MainControl = new QWidget(parent);
QFormLayout *formLayout = new QFormLayout;
m_ClipToImagePlane = new QCheckBox();
formLayout->addRow("clipping planes", m_ClipToImagePlane);
// gradient background
QLabel* gBName = new QLabel;
gBName->setText("gradient background");
formLayout->addRow(gBName);
// color
m_ColorButton1 = new QPushButton;
m_ColorButton1->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum);
m_ColorButton2 = new QPushButton;
m_ColorButton2->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum);
QPushButton* resetButton = new QPushButton;
resetButton->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum);
resetButton->setText("reset");
QLabel* colorLabel1 = new QLabel("first color : ");
colorLabel1->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);
QLabel* colorLabel2 = new QLabel("second color: ");
colorLabel2->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);
QHBoxLayout* colorWidgetLayout = new QHBoxLayout;
colorWidgetLayout->setContentsMargins(4,4,4,4);
colorWidgetLayout->addWidget(colorLabel1);
colorWidgetLayout->addWidget(m_ColorButton1);
colorWidgetLayout->addWidget(colorLabel2);
colorWidgetLayout->addWidget(m_ColorButton2);
colorWidgetLayout->addWidget(resetButton);
QWidget* colorWidget = new QWidget;
colorWidget->setLayout(colorWidgetLayout);
// spacer
QSpacerItem *spacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
QVBoxLayout* vBoxLayout = new QVBoxLayout;
vBoxLayout->addLayout(formLayout);
vBoxLayout->addWidget(colorWidget);
vBoxLayout->addSpacerItem(spacer);
m_MainControl->setLayout(vBoxLayout);
QObject::connect( m_ColorButton1, SIGNAL( clicked() )
, this, SLOT( FirstColorChanged() ) );
QObject::connect( m_ColorButton2, SIGNAL( clicked() )
, this, SLOT( SecondColorChanged() ) );
QObject::connect( resetButton, SIGNAL( clicked() )
, this, SLOT( ResetColors() ) );
this->Update();
}
//-----------------------------------------------------------------------------
QWidget* IGIUltrasoundOverlayEditorPreferencePage::GetQtControl() const
{
return m_MainControl;
}
//-----------------------------------------------------------------------------
bool IGIUltrasoundOverlayEditorPreferencePage::PerformOk()
{
m_IGIUltrasoundOverlayEditorPreferencesNode->Put(IGIUltrasoundOverlayEditorPreferencePage::FIRST_BACKGROUND_STYLE_SHEET, m_FirstColorStyleSheet);
m_IGIUltrasoundOverlayEditorPreferencesNode->Put(IGIUltrasoundOverlayEditorPreferencePage::SECOND_BACKGROUND_STYLE_SHEET, m_SecondColorStyleSheet);
m_IGIUltrasoundOverlayEditorPreferencesNode->Put(IGIUltrasoundOverlayEditorPreferencePage::FIRST_BACKGROUND_COLOUR, m_FirstColor);
m_IGIUltrasoundOverlayEditorPreferencesNode->Put(IGIUltrasoundOverlayEditorPreferencePage::SECOND_BACKGROUND_COLOUR, m_SecondColor);
m_IGIUltrasoundOverlayEditorPreferencesNode->PutBool(IGIUltrasoundOverlayEditorPreferencePage::CLIP_TO_IMAGE_PLANE, m_ClipToImagePlane->isChecked());
return true;
}
//-----------------------------------------------------------------------------
void IGIUltrasoundOverlayEditorPreferencePage::PerformCancel()
{
}
//-----------------------------------------------------------------------------
void IGIUltrasoundOverlayEditorPreferencePage::Update()
{
m_FirstColorStyleSheet = m_IGIUltrasoundOverlayEditorPreferencesNode->Get(IGIUltrasoundOverlayEditorPreferencePage::FIRST_BACKGROUND_STYLE_SHEET, "");
m_SecondColorStyleSheet = m_IGIUltrasoundOverlayEditorPreferencesNode->Get(IGIUltrasoundOverlayEditorPreferencePage::SECOND_BACKGROUND_STYLE_SHEET, "");
m_FirstColor = m_IGIUltrasoundOverlayEditorPreferencesNode->Get(IGIUltrasoundOverlayEditorPreferencePage::FIRST_BACKGROUND_COLOUR, "");
m_SecondColor = m_IGIUltrasoundOverlayEditorPreferencesNode->Get(IGIUltrasoundOverlayEditorPreferencePage::SECOND_BACKGROUND_COLOUR, "");
if (m_FirstColorStyleSheet=="")
{
m_FirstColorStyleSheet = "background-color:rgb(0,0,0)";
}
if (m_SecondColorStyleSheet=="")
{
m_SecondColorStyleSheet = "background-color:rgb(0,0,0)";
}
if (m_FirstColor=="")
{
m_FirstColor = "#000000";
}
if (m_SecondColor=="")
{
m_SecondColor = "#000000";
}
m_ColorButton1->setStyleSheet(m_FirstColorStyleSheet);
m_ColorButton2->setStyleSheet(m_SecondColorStyleSheet);
m_ClipToImagePlane->setChecked(m_IGIUltrasoundOverlayEditorPreferencesNode->GetBool(IGIUltrasoundOverlayEditorPreferencePage::CLIP_TO_IMAGE_PLANE, true));
}
//-----------------------------------------------------------------------------
void IGIUltrasoundOverlayEditorPreferencePage::FirstColorChanged()
{
QColor color = QColorDialog::getColor();
m_ColorButton1->setAutoFillBackground(true);
QString styleSheet = "background-color:rgb(";
styleSheet.append(QString::number(color.red()));
styleSheet.append(",");
styleSheet.append(QString::number(color.green()));
styleSheet.append(",");
styleSheet.append(QString::number(color.blue()));
styleSheet.append(")");
m_ColorButton1->setStyleSheet(styleSheet);
m_FirstColorStyleSheet = styleSheet;
QStringList firstColor;
firstColor << color.name();
m_FirstColor = firstColor.replaceInStrings(";","\\;").join(";");
}
//-----------------------------------------------------------------------------
void IGIUltrasoundOverlayEditorPreferencePage::SecondColorChanged()
{
QColor color = QColorDialog::getColor();
m_ColorButton2->setAutoFillBackground(true);
QString styleSheet = "background-color:rgb(";
styleSheet.append(QString::number(color.red()));
styleSheet.append(",");
styleSheet.append(QString::number(color.green()));
styleSheet.append(",");
styleSheet.append(QString::number(color.blue()));
styleSheet.append(")");
m_ColorButton2->setStyleSheet(styleSheet);
m_SecondColorStyleSheet = styleSheet;
QStringList secondColor;
secondColor << color.name();
m_SecondColor = secondColor.replaceInStrings(";","\\;").join(";");
}
//-----------------------------------------------------------------------------
void IGIUltrasoundOverlayEditorPreferencePage::ResetColors()
{
m_FirstColorStyleSheet = "background-color:rgb(0,0,0)";
m_SecondColorStyleSheet = "background-color:rgb(0,0,0)";
m_FirstColor = "#000000";
m_SecondColor = "#000000";
m_ColorButton1->setStyleSheet(m_FirstColorStyleSheet);
m_ColorButton2->setStyleSheet(m_SecondColorStyleSheet);
}
} // end namespace
| 37.373391
| 156
| 0.706821
|
NifTK
|
45916e18b70b1ba2bd94f6b171cfa3caaa03cbf6
| 12,415
|
hpp
|
C++
|
include/Lodtalk/Collections.hpp
|
ronsaldo/lodtalk
|
4668e8923f508c8a9e87a00242ab67b26fb0c9a4
|
[
"MIT"
] | 3
|
2017-02-10T18:18:58.000Z
|
2019-02-21T02:35:29.000Z
|
include/Lodtalk/Collections.hpp
|
ronsaldo/lodtalk
|
4668e8923f508c8a9e87a00242ab67b26fb0c9a4
|
[
"MIT"
] | null | null | null |
include/Lodtalk/Collections.hpp
|
ronsaldo/lodtalk
|
4668e8923f508c8a9e87a00242ab67b26fb0c9a4
|
[
"MIT"
] | null | null | null |
#ifndef LODTALK_COLLECTIONS_HPP_
#define LODTALK_COLLECTIONS_HPP_
#include <stddef.h>
#include <string>
#include "Lodtalk/Object.hpp"
namespace Lodtalk
{
/**
* Collection
*/
class LODTALK_VM_EXPORT Collection: public Object
{
public:
static SpecialNativeClassFactory Factory;
};
/**
* SequenceableCollection
*/
class LODTALK_VM_EXPORT SequenceableCollection: public Collection
{
public:
static SpecialNativeClassFactory Factory;
};
/**
* ArrayedCollection
*/
class LODTALK_VM_EXPORT ArrayedCollection: public SequenceableCollection
{
public:
static SpecialNativeClassFactory Factory;
};
/**
* Array
*/
class LODTALK_VM_EXPORT Array: public ArrayedCollection
{
public:
static SpecialNativeClassFactory Factory;
static Array *basicNativeNew(VMContext *context, size_t indexableSize);
};
/**
* ByteArray
*/
class LODTALK_VM_EXPORT ByteArray: public ArrayedCollection
{
public:
static SpecialNativeClassFactory Factory;
};
/**
* FloatArray
*/
class LODTALK_VM_EXPORT FloatArray: public ArrayedCollection
{
public:
static SpecialNativeClassFactory Factory;
};
/**
* WordArray
*/
class LODTALK_VM_EXPORT WordArray: public ArrayedCollection
{
public:
static SpecialNativeClassFactory Factory;
};
/**
* IntegerArray
*/
class LODTALK_VM_EXPORT IntegerArray: public ArrayedCollection
{
public:
static SpecialNativeClassFactory Factory;
};
/**
* String
*/
class LODTALK_VM_EXPORT String: public ArrayedCollection
{
public:
static SpecialNativeClassFactory Factory;
};
/**
* ByteString
*/
class LODTALK_VM_EXPORT ByteString: public String
{
public:
static SpecialNativeClassFactory Factory;
static ByteString *basicNativeNew(VMContext *context, size_t indexableSize);
static ByteString *fromNativeRange(VMContext *context, const char *start, size_t size);
static ByteString *fromNativeReverseRange(VMContext *context, const char *start, ptrdiff_t size);
static Ref<ByteString> fromNative(VMContext *context, const std::string &native);
static Oop splitVariableNames(VMContext *context, const std::string &string);
std::string getString();
static int stSplitVariableNames(InterpreterProxy *interpreter);
};
/**
* WideString
*/
class LODTALK_VM_EXPORT WideString: public String
{
public:
static SpecialNativeClassFactory Factory;
};
/**
* Symbol
*/
class LODTALK_VM_EXPORT Symbol: public String
{
public:
static SpecialNativeClassFactory Factory;
};
/**
* ByteSymbol
*/
class LODTALK_VM_EXPORT ByteSymbol: public Symbol
{
public:
static SpecialNativeClassFactory Factory;
static Object *basicNativeNew(VMContext *context, size_t indexableSize);
static Oop fromNative(VMContext *context, const std::string &native);
static Oop fromNativeRange(VMContext *context, const char *star, size_t size);
std::string getString();
};
/**
* WideSymbol
*/
class LODTALK_VM_EXPORT WideSymbol: public Symbol
{
public:
static SpecialNativeClassFactory Factory;
};
/**
* HashedCollection
*/
class LODTALK_VM_EXPORT HashedCollection: public Collection
{
public:
static SpecialNativeClassFactory Factory;
void initialize()
{
capacityObject = Oop::encodeSmallInteger(0);
tallyObject = Oop::encodeSmallInteger(0);
keyValues = (Array*)&NilObject;
}
size_t getCapacity() const
{
return capacityObject.decodeSmallInteger();
}
size_t getTally() const
{
return tallyObject.decodeSmallInteger();
}
Oop *getHashTableKeyValues() const
{
assert(keyValues);
return reinterpret_cast<Oop*> (keyValues->getFirstFieldPointer());
}
protected:
void setKeyCapacity(VMContext *context, size_t keyCapacity)
{
keyValues = Array::basicNativeNew(context, keyCapacity);
}
template<typename KF, typename HF, typename EF>
ptrdiff_t findKeyPosition(Oop key, const KF &keyFunction, const HF &hashFunction, const EF &equals)
{
auto capacity = getCapacity();
if(capacity == 0)
return -1;
auto keyHash = hashFunction(key);
auto startPosition = keyHash % capacity;
auto keyValuesArray = getHashTableKeyValues();
// Search from the hash position to the end.
for(size_t i = startPosition; i < capacity; ++i)
{
// Check no association
auto keyValue = keyValuesArray[i];
if(isNil(keyValue))
return i;
// Check the key
auto slotKey = keyFunction(keyValue);
if(equals(key, slotKey))
return i;
}
// Search from the start to the hash position.
for(size_t i = 0; i < startPosition; ++i)
{
// Check no association
auto keyValue = keyValuesArray[i];
if(isNil(keyValue))
return i;
// Check the key
auto slotKey = keyFunction(keyValuesArray[i]);
if(equals(key, slotKey))
return i;
}
// Not found.
return -1;
}
template<typename KF, typename HF, typename EF>
void increaseSize(VMContext *context, const KF &keyFunction, const HF &hashFunction, const EF &equalityFunction)
{
tallyObject.intValue += 2;
// Do not use more than 80% of the capacity
if(tallyObject.intValue > capacityObject.intValue*4/5)
increaseCapacity(context, keyFunction, hashFunction, equalityFunction);
}
template<typename KF, typename HF, typename EF>
void increaseCapacity(VMContext *context, const KF &keyFunction, const HF &hashFunction, const EF &equalityFunction)
{
size_t newCapacity = getCapacity()*2;
if(!newCapacity)
newCapacity = 16;
setCapacity(context, newCapacity, keyFunction, hashFunction, equalityFunction);
}
template<typename KF, typename HF, typename EF>
Oop internalKeyValueAtOrNil(Oop key, const KF &keyFunction, const HF &hashFunction, const EF &equalityFunction)
{
// If a slot was not found, try to increase the capacity.
auto position = findKeyPosition(key, keyFunction, hashFunction, equalityFunction);
if(position < 0)
return nilOop();
auto oldKeyValue = getHashTableKeyValues()[position];
if(isNil(oldKeyValue))
return nilOop();
return oldKeyValue;
}
template<typename KF, typename HF, typename EF>
void internalPutKeyValue(VMContext *context, Oop keyValue, const KF &keyFunction, const HF &hashFunction, const EF &equalityFunction)
{
// If a slot was not found, try to increase the capacity.
auto position = findKeyPosition(keyFunction(keyValue), keyFunction, hashFunction, equalityFunction);
if(position < 0)
{
OopRef keyValueRef(context, keyValue);
increaseCapacity(context, keyFunction, hashFunction, equalityFunction);
return internalPutKeyValue(context, keyValueRef.oop, keyFunction, hashFunction, equalityFunction);
}
// Put the key and value.
auto keyValueArray = getHashTableKeyValues();
auto oldKeyValue = keyValueArray[position];
keyValueArray[position] = keyValue;
// Increase the size.
if(isNil(oldKeyValue))
increaseSize(context, keyFunction, hashFunction, equalityFunction);
}
template<typename KF, typename HF, typename EF>
void setCapacity(VMContext *context, size_t newCapacity, const KF &keyFunction, const HF &hashFunction, const EF &equalityFunction)
{
// Store temporarily the data.
auto oldKeyValues = Oop::fromPointer(keyValues);
size_t oldCapacity = capacityObject.decodeSmallInteger();
// Create the new capacity.
capacityObject = Oop::encodeSmallInteger(newCapacity);
tallyObject = Oop::encodeSmallInteger(0);
setKeyCapacity(context, newCapacity);
// Add back the old objects.
if(!oldKeyValues.isNil())
{
Oop *oldKeyValuesOops = reinterpret_cast<Oop *> (oldKeyValues.getFirstFieldPointer());
for(size_t i = 0; i < oldCapacity; ++i)
{
auto oldKeyValue = oldKeyValuesOops[i];
if(!isNil(oldKeyValue))
internalPutKeyValue(context, oldKeyValue, keyFunction, hashFunction, equalityFunction);
}
}
}
Oop capacityObject;
Oop tallyObject;
Array* keyValues;
};
/**
* Dictionary
*/
class LODTALK_VM_EXPORT Dictionary: public HashedCollection
{
public:
static SpecialNativeClassFactory Factory;
};
/**
* MethodDictionary
*/
class LODTALK_VM_EXPORT MethodDictionary: public Dictionary
{
public:
static SpecialNativeClassFactory Factory;
static MethodDictionary* basicNativeNew(VMContext *context);
Oop atOrNil(Oop key)
{
return internalAtOrNil(key);
}
Oop atPut(VMContext *context, Oop key, Oop value)
{
internalAtPut(context, key, value);
return value;
}
Oop *getHashTableKeys() const
{
assert(keyValues);
return reinterpret_cast<Oop*> (keyValues->getFirstFieldPointer());
}
Oop *getHashTableValues() const
{
assert(values);
return reinterpret_cast<Oop*> (values->getFirstFieldPointer());
}
static int stAtOrNil(InterpreterProxy *interpreter);
static int stAtPut(InterpreterProxy *interpreter);
protected:
MethodDictionary()
{
object_header_ = ObjectHeader::specialNativeClass(generateIdentityHash(this), SCI_MethodDictionary, 4);
values = (Array*)&NilObject;
}
void increaseSize(VMContext *context)
{
tallyObject.intValue += 2;
// Do not use more than 80% of the capacity
if(tallyObject.intValue > capacityObject.intValue*4/5)
increaseCapacity(context);
}
void increaseCapacity(VMContext *context)
{
size_t newCapacity = getCapacity()*2;
if(!newCapacity)
newCapacity = 16;
setCapacity(context, newCapacity);
}
Oop internalAtOrNil(Oop key)
{
// If a slot was not found, try to increase the capacity.
auto position = findKeyPosition(key, identityFunction<Oop>, identityHashOf, identityOopEquals);
if(position < 0)
return nilOop();
auto oldKey = getHashTableKeys()[position];
if(isNil(oldKey))
return nilOop();
return getHashTableValues()[position];
}
void internalAtPut(VMContext *context, Oop key, Oop value)
{
// If a slot was not found, try to increase the capacity.
auto position = findKeyPosition(key, identityFunction<Oop>, identityHashOf, identityOopEquals);
if(position < 0)
{
OopRef keyRef(context, key);
OopRef valueRef(context, value);
increaseCapacity(context);
return internalAtPut(context, keyRef.oop, valueRef.oop);
}
// Put the key and value.
auto keyArray = getHashTableKeys();
auto valueArray = getHashTableValues();
auto oldKey = keyArray[position];
keyArray[position] = key;
valueArray[position] = value;
// Increase the size.
if(isNil(oldKey))
increaseSize(context);
}
void setCapacity(VMContext *context, size_t newCapacity)
{
// Store temporarily the data.
auto oldKeys = Oop::fromPointer(keyValues);
auto oldValues = Oop::fromPointer(values);
size_t oldCapacity = capacityObject.decodeSmallInteger();
// Create the new capacity.
capacityObject = Oop::encodeSmallInteger(newCapacity);
tallyObject = Oop::encodeSmallInteger(0);
setKeyCapacity(context, newCapacity);
setValueCapacity(context, newCapacity);
// Add back the old objects.
if(!oldKeys.isNil())
{
Oop *oldKeysOops = reinterpret_cast<Oop *> (oldKeys.getFirstFieldPointer());
Oop *oldValuesOops = reinterpret_cast<Oop *> (oldValues.getFirstFieldPointer());
for(size_t i = 0; i < oldCapacity; ++i)
{
auto oldKey = oldKeysOops[i];
if(!isNil(oldKey))
internalAtPut(context, oldKey, oldValuesOops[i]);
}
}
}
void setValueCapacity(VMContext *context, size_t valueCapacity)
{
values = Array::basicNativeNew(context, valueCapacity);
}
Array* values;
};
/**
* IdentityDictionary
*/
class LODTALK_VM_EXPORT IdentityDictionary: public Dictionary
{
public:
static SpecialNativeClassFactory Factory;
Oop putAssociation(VMContext *context, Oop assoc)
{
internalPutKeyValue(context, assoc, getLookupKeyKey, identityHashOf, identityOopEquals);
return assoc;
}
Oop getAssociationOrNil(Oop key)
{
return internalKeyValueAtOrNil(key, getLookupKeyKey, identityHashOf, identityOopEquals);
}
void putNativeAssociation(VMContext *context, Association *assoc)
{
putAssociation(context, Oop::fromPointer(assoc));
}
Association *getNativeAssociationOrNil(Oop key)
{
return reinterpret_cast<Association *> (getAssociationOrNil(key).pointer);
}
static int stPutAssociation(InterpreterProxy *interpreter);
static int stAssociationAtOrNil(InterpreterProxy *interpreter);
};
/**
* SystemDictionary
*/
class LODTALK_VM_EXPORT SystemDictionary: public IdentityDictionary
{
public:
static SpecialNativeClassFactory Factory;
static SystemDictionary *create(VMContext *context);
};
} // End of namespace Lodtalk
#endif //LODTALK_COLLECTIONS_HPP_
| 23.829175
| 134
| 0.737898
|
ronsaldo
|
4593f57d4d81656f516d9deaca99f02bef8d2f98
| 1,610
|
cpp
|
C++
|
codechef/aug17/6.cpp
|
AadityaJ/Spoj
|
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
|
[
"MIT"
] | null | null | null |
codechef/aug17/6.cpp
|
AadityaJ/Spoj
|
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
|
[
"MIT"
] | null | null | null |
codechef/aug17/6.cpp
|
AadityaJ/Spoj
|
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void printArr(vector<string> &v){
for(int i=0;i<v.size();i++){
cout<<v[i]<<endl;
}
}
long long int f(vector<string> &v,string str){
for(int i=0;i<str.length();i++){
bool is=0;
char c=str[i];
for(int j=0;j<v.size();j++){
if(v[j][i]==c){is=1;break;}
}
if(!is){v.push_back(str);return str.length()-i;}
}
return 0;
}
string con2bits(int c,int n){
string str="";
for(int i=0;i<(n-c-1);i++) str.push_back('0');
str.push_back('1');
for(int i=0;i<c;i++) str.push_back('0');
return str;
}
string add(string a,string b){
int ca=0;
string c="";
for(int i=a.length()-1;i>=0;i--){
int ax=a[i]-'0';
int bx=b[i]-'0';
int cx=(ax+bx+ca)%2;
ca=(ax+bx+ca)/2;
c.push_back(cx+'0');
}
reverse(c.begin(),c.end());
return c;
}
int main(int argc, char const *argv[]) {
int t;
cin>>t;
while(t--){
int n,q;
cin>>n>>q;
long long int ans=0;
string x="";
for(int i=0;i<n;i++) x.push_back('0');
vector<string> v;
for(int i=0;i<q;i++){
char ch;
cin>>ch;
if(ch=='?'){cout<<ans<<endl;}
else{
int c;
cin>>c;
string str=con2bits(c,n);
x=add(x,str);
ans+=f(v,x);
cout<<i<<" :: "<<x<<endl;
printArr(v);
cout<<endl;
}
}
}
return 0;
}
| 22.676056
| 56
| 0.445342
|
AadityaJ
|
459410b8db4d34750797b8d22906e62fa7952018
| 72,861
|
cpp
|
C++
|
src/zgemmtune.cpp
|
codedivine/raijinclv2
|
e4c50b757e3fe6d1fa5d09c135f1156b31c08fab
|
[
"Apache-2.0"
] | null | null | null |
src/zgemmtune.cpp
|
codedivine/raijinclv2
|
e4c50b757e3fe6d1fa5d09c135f1156b31c08fab
|
[
"Apache-2.0"
] | null | null | null |
src/zgemmtune.cpp
|
codedivine/raijinclv2
|
e4c50b757e3fe6d1fa5d09c135f1156b31c08fab
|
[
"Apache-2.0"
] | null | null | null |
/**Copyright 2012, Rahul Garg and McGill University
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 <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include "raijin_complex.hpp"
#include "rtimer.hpp"
#include <CL/cl.h>
using namespace std;
using namespace RaijinCL;
struct GemmCsingle{
typedef cl_float2 ctype;
typedef cl_float basetype;
static bool isDouble(){return false;}
static string gemmName(){return "cgemm";}
static string name(){return "float";}
};
struct GemmCdouble{
typedef cl_double2 ctype;
typedef cl_double basetype;
static bool isDouble(){return true;}
static string gemmName(){return "zgemm";}
static string name(){return "double";}
};
static bool genCkernelTNOff(int lsizex,
int lsizey,
int htile,
int wtile,
int ktile,
string dtype,
int simdwidth,
bool storea,
bool storeb,
int maxLocalMemElems,
int padding,
string& kernel,
bool useImageA = false,
bool useImageB = false){
//cout<<"StoreA "<<storea<<" "<<"StoreB "<<storeb<<" "<<htile<<" "<<wtile<<" "<<" "<<ktile<<" "<<simdwidth<<" "<<lsizex<<" "<<lsizey<<" "<<unroll;
//cout<<" "<<maxLocalMemElems<<" "<<endl;
bool isDouble = (dtype.compare("double")==0) ? true:false;
if(isDouble && simdwidth>1 && (useImageA || useImageB)) return false;
if(!isDouble && simdwidth>2 && (useImageA || useImageB)) return false;
//const int unroll = ktile;
if(storea){
/*Number of rows of A per workgroup = ktile. Has to be divisble by lsizey. */
if(ktile%lsizex!=0) return false;
/*Number of columns of A per workgroup = htile*lsizex*/
if((htile*lsizex)%(simdwidth*lsizey)!=0) return false;
}else{
if(htile%simdwidth!=0) return false;
}
if(storeb){
/*Number of columns of B per workgroup = wtile*lsizey. Has to be divisble by lsizex*simdwidth */
if(ktile%lsizex!=0) return false;
if(((wtile*lsizey)%(lsizey*simdwidth))!=0) return false;
}else{
if(wtile%simdwidth!=0) return false;
}
//cout<<"Check 2 passed"<<endl;
if(wtile%simdwidth!=0 || htile%simdwidth!=0) return false;
int numLocalMemElems = 0;
if(storea) numLocalMemElems += ktile*(htile*lsizex+padding);
if(storeb) numLocalMemElems += ktile*(wtile*lsizey+padding);
if(numLocalMemElems>maxLocalMemElems) return false;
//cout<<"Check 3 passed"<<endl;
//if(ktile%unroll!=0) return false;
//cout<<"Check 4 passed"<<endl;
stringstream ss;
ss<<"(";
if(useImageA){
ss<<"__read_only image2d_t A,";
}else{
ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict A,";
}
if(useImageB){
ss<<"__read_only image2d_t B,";
}else{
ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict B,";
}
ss<<"__global "<<dtype<<"2 *restrict C,unsigned int lda,unsigned int ldb,unsigned int ldc,unsigned int K,"<<dtype<<"2 alpha,"<<dtype<<"2 beta){"<<endl;
ss<<"const int htile ="<<htile<<";\n";
ss<<"const int wtile ="<<wtile<<";\n";
ss<<"const int ktile ="<<ktile<<";\n";
ss<<"const int simdwidth="<<simdwidth<<";\n";
ss<<"const int lx = "<<lsizex<<";\n";
ss<<"const int ly = "<<lsizey<<";\n";
ss<<"const int i = get_global_id(1);"<<endl;
ss<<"const int j = get_global_id(0);"<<endl;
//ss<<"const int unroll = "<<unroll<<";\n";
//ss<<"const int unsigned flat = get_local_id(0)+get_local_id(1)*ly;"<<endl;
ss<<"const unsigned int lidx = get_local_id(1);"<<endl;
ss<<"const unsigned int lidy = get_local_id(0);"<<endl;
/*ss<<"const unsigned int lidx = flat%lx;"<<endl;
ss<<"const unsigned int lidy = (get_local_id(0)+get_local_id(1))%ly;"<<endl;*/
ss<<"int k;"<<endl;
if(storea){
ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsA["<<(ktile)<<"]["<<((htile/simdwidth)*lsizex+padding)<<"];"<<endl;
}
if(storeb){
ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsB["<<(ktile)<<"]["<<((wtile/simdwidth)*lsizey+padding)<<"];"<<endl;
}
for(int x=0;x<htile;x++){
for(int y=0;y<wtile/simdwidth;y++){
ss<<dtype<<(simdwidth*2)<<" sum"<<x<<"_"<<y<<" = ("<<dtype<<(simdwidth*2)<<")(0);\n";
}
}
ss<<"for(k=0;k<K;k+=ktile){"<<endl;
if(storea){
ss<<"const int gstartxA = get_group_id(1)*(htile/simdwidth)*lx;\n";
for(int y=0;y<(ktile/lsizex);y++){
for(int x=0;x<((htile*lsizex)/(simdwidth*lsizey));x++){
ss<<" ldsA["<<y<<"*lx + lidx]["<<x<<"*ly + lidy] = ";
if(useImageA){
if(isDouble){
ss<<"as_double2(read_imagei(A,sampler,(int2)(lidy+"<<x<<"*ly+gstartxA,k+"<<y<<"*lx + lidx )))";
}else{
ss<<"(myread_imagef(A,(int2)(lidy+"<<x<<"*ly+gstartxA,k+"<<y<<"*lx + lidx)))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss<<"A[(k+"<<y<<"*lx+lidx)*(lda/simdwidth)+ gstartxA + lidy + "<<x<<"*ly];\n";
}
}
}
}
if(storeb){
ss<<"const int gstartxB = get_group_id(0)*(wtile/simdwidth)*ly;\n";
for(int y=0;y<(ktile/lsizex);y++){
for(int x=0;x<((wtile*lsizey)/(simdwidth*lsizey));x++){
ss<<" ldsB["<<y<<"*lx + lidx]["<<x<<"*ly + lidy] = ";
if(useImageB){
if(isDouble){
ss<<"as_double2(read_imagei(B,sampler,(int2)(lidy + "<<x<<"*ly+gstartxB,k+"<<y<<"*lx +lidx)))";
}else{
ss<<"(myread_imagef(B,(int2)(lidy + "<<x<<"*ly+gstartxB,k+"<<y<<"*lx +lidx)))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss<<"B[(k+"<<y<<"*lx+lidx)*(ldb/simdwidth)+ gstartxB + lidy + "<<x<<"*ly];\n";
}
}
}
}
if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl;
//ss<<" for(kk=0;kk<ktile;kk+=unroll){\n";
ss<<"const int kk = 0;\n";
for (int y = 0; y < ktile; y++) {
for (int x = 0; x < wtile/simdwidth; x++) {
ss << " const " << dtype << (simdwidth*2) << " b" << x << "_" << y << " = ";
if(storeb){
ss << "ldsB[kk+"<<y<<"][ly*"<<x<<"+lidy];\n";
}else{
if(useImageB){
if(isDouble){
ss<<"as_double2( read_imagei(B,sampler,(int2)((get_group_id(0)*(wtile/simdwidth)+"<<x<<")*ly + lidy,k+kk+"<<y<<")))";
}else{
ss<<"( myread_imagef(B,(int2)((get_group_id(0)*(wtile/simdwidth)+"<<x<<")*ly + lidy,k+kk+"<<y<<")))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss << "B[(k+kk+"<<y<<")*(ldb/simdwidth)+ (get_group_id(0)*(wtile/simdwidth)+"<<x<<")*ly + lidy];\n";
}
}
}
}
for (int y = 0; y < ktile; y++){
for (int x = 0; x < htile/simdwidth; x++) {
ss << " const " << dtype << (simdwidth*2) << " a" << x << "_" << y << " = ";
if(storea){
ss << "ldsA[kk+"<<y<<"][lx*"<<x<<"+lidx];\n";
}else{
if(useImageA){
if(isDouble) {
ss<<"as_double2(read_imagei(A,sampler,(int2)((get_group_id(1)*(htile/simdwidth)+"<<x<<")*lx + lidx,k+kk+"<<y<<")))";
}else{
ss<<"(myread_imagef(A,(int2)((get_group_id(1)*(htile/simdwidth)+"<<x<<")*lx + lidx,k+kk+"<<y<<")))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss << "A[(k+kk+"<<y<<")*(lda/simdwidth)+ (get_group_id(1)*(htile/simdwidth)+"<<x<<")*lx + lidx];"<<endl;
}
}
//for(int x=0;x<htile/simdwidth;x++){
for(int xoff=0;xoff<simdwidth;xoff++){
int row = x*simdwidth + xoff;
for(int w=0;w<wtile/simdwidth; w++){
ss<<" sum"<<row<<"_"<<w;
ss<<" = fmaComplex"<<simdwidth;
ss<<"(a"<<x<<"_"<<y<<".s";
for(int m=0;m<simdwidth;m++){
ss<<(2*xoff);
ss<<(2*xoff+1);
}
ss<<",b"<<w<<"_"<<y<<",";
ss<<" sum"<<row<<"_"<<w;
ss<<");\n";
}
}
}
}
//ss<<" }\n";
if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl;
ss<<"}"<<endl;
for (int i = 0; i < htile/simdwidth; i++) {
for(int ii=0;ii<simdwidth;ii++){
for (int j = 0; j < wtile/simdwidth; j++) {
for(int jj=0;jj<simdwidth;jj++){
ss << "C[( (get_group_id(1)*htile+"<<i<<"*simdwidth)*lx + lidx*simdwidth+ "<<ii<<")*ldc + (get_group_id(0)*wtile + " << j << "*simdwidth)*ly + lidy*simdwidth+" << jj << "]";
ss << "= mulComplex1(alpha,sum"<<(i*simdwidth+ii)<<"_"<<j;
if(simdwidth>1){
ss<<".s"<<(2*jj)<<(2*jj+1);
}
ss<<") + mulComplex1(beta,";
ss << "C[( (get_group_id(1)*htile+"<<i<<"*simdwidth)*lx + lidx*simdwidth+ "<<ii<<")*ldc + (get_group_id(0)*wtile + " << j << "*simdwidth)*ly + lidy*simdwidth+" << jj << "]";
//ss << "C[(i*" << htile << "+ " << i << ")*ldc + (get_group_id(0)*wtile + " << j << "*simdwidth)*ly + lidy*simdwidth+" << jj << "]";
ss << ");" << endl;
}
}
}
}
ss<<"}"<<endl;
kernel = ss.str();
return true;
}
static bool genCkernelNTCons(int lsizex, int lsizey, int htile, int wtile, int ktile, string dtype,int simdwidth, bool storea, bool storeb, int maxLocalMemElems,
int padding,string& kernel, bool useImageA,bool useImageB){
//cout<<"StoreA "<<storea<<" "<<"StoreB "<<storeb<<" "<<htile<<" "<<wtile<<" "<<" "<<ktile<<" "<<simdwidth<<" "<<lsizex<<" "<<lsizey<<" "<<unroll;
//cout<<" "<<maxLocalMemElems<<" "<<endl;
if(storea){
/*Number of rows of A per workgroup = htile*lsizex. Has to be divisble by lsizex. Trivially satisfied */
/*Number of columns of A per workgroup = ktile. Has to be divisble by lsizey*simdwidth */
if(ktile%(simdwidth*lsizey)!=0) return false;
}
if(storeb){
/*Number of columns of B per workgroup = ktile. Has to be divisble by lsizey*simdwidth */
if(ktile%(lsizey*simdwidth)!=0) return false;
/*Number of rows of B per workgroup = wtile*lsizey. Has to be divisble by lsizex*/
if((wtile*lsizey)%lsizex!=0) return false;
}
//cout<<"Check 2 passed"<<endl;
bool isDouble = (dtype.compare("double")==0);
if(ktile%simdwidth!=0) return false;
int numLocalMemElems = 0;
if(storea) numLocalMemElems += htile*lsizex*(ktile+padding);
if(storeb) numLocalMemElems += wtile*lsizey*(ktile+padding);
if(numLocalMemElems>maxLocalMemElems) return false;
//cout<<"Check 3 passed"<<endl;
//cout<<"Check 4 passed"<<endl;
stringstream ss;
ss<<"(";
if(useImageA){
ss<<"__read_only image2d_t A,";
}else{
ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict A,";
}
if(useImageB){
ss<<"__read_only image2d_t B,";
}else{
ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict B,";
}
ss<<"__global "<<dtype<<"2 *restrict C,unsigned int lda,unsigned int ldb,unsigned int ldc,unsigned int K,"<<dtype<<"2 alpha,"<<dtype<<"2 beta){"<<endl;
ss<<"const int htile ="<<htile<<";\n";
ss<<"const int wtile ="<<wtile<<";\n";
ss<<"const int ktile ="<<ktile<<";\n";
ss<<"const int simdwidth="<<simdwidth<<";\n";
ss<<"const int lx = "<<lsizex<<";\n";
ss<<"const int ly = "<<lsizey<<";\n";
ss<<"const int i = get_global_id(1);\n";
ss<<"const int j = get_global_id(0);\n";
ss<<"const unsigned int lidx = get_local_id(1);"<<endl;
ss<<"const unsigned int lidy = get_local_id(0);"<<endl;
ss<<"unsigned int k;"<<endl;
if(storea){
ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsA["<<(htile*lsizex)<<"]["<<((ktile/simdwidth)+padding)<<"];"<<endl;
}
if(storeb){
ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsB["<<(wtile*lsizey)<<"]["<<((ktile/simdwidth)+padding)<<"];"<<endl;
}
for(int x=0;x<htile;x++){
for(int y=0;y<wtile;y++){
ss<<dtype<<(simdwidth*2)<<" sum"<<x<<"_"<<y<<" = ("<<dtype<<(simdwidth*2)<<")(0);\n";
}
}
ss<<"const unsigned int ldbs = ldb/simdwidth;\n";
ss<<"const unsigned int ldas = lda/simdwidth;\n";
ss<<"for(k=0;k<K/simdwidth;k+=(ktile/simdwidth)){"<<endl;
if(storea){
ss<<"const int gstartxA = get_group_id(1)*htile*lx;\n";
for(int rowA=0;rowA<htile;rowA++){
for(int colA=0;colA<(ktile/(lsizey*simdwidth));colA++){
ss<<" ldsA["<<rowA<<"*lx + lidx]["<<colA<<"*ly + lidy] = ";
if(useImageA){
if(isDouble){
ss<<"as_double2(read_imagei(A,sampler,(int2)(k+"<<colA<<"*ly+lidy,gstartxA+"<<rowA<<"*lx+lidx)))";
}else{
ss<<"(read_imagef(A,sampler,(int2)(k+"<<colA<<"*ly+lidy,gstartxA+"<<rowA<<"*lx+lidx)))";
}
ss<<".s";
for(int s=0;s<simdwidth;s++) ss<<s;
ss<<";\n";
}else{
ss<<"A[(gstartxA+"<<rowA<<"*lx + lidx)*(lda/simdwidth) + k + "<<colA<<"*ly + lidy];\n";
}
}
}
}
if(storeb){
ss<<"const int gstartxB = get_group_id(0)*wtile*ly;\n";
for(int rowB=0;rowB<(wtile*lsizey)/lsizex;rowB++){
for(int colB=0;colB<(ktile/(lsizey*simdwidth));colB++){
ss<<" ldsB["<<rowB<<"*lx + lidx]["<<colB<<"*ly + lidy] = ";
if(useImageB){
if(isDouble){
ss<<"as_double2(read_imagei(B,sampler,(int2)(k+"<<colB<<"*ly+lidy,gstartxB+"<<rowB<<"*lx+lidx)))";
}else{
ss<<"(read_imagef(B,sampler,(int2)(k+"<<colB<<"*ly+lidy,gstartxB+"<<rowB<<"*lx+lidx)))";
}
ss<<".s";
for(int s=0;s<simdwidth;s++) ss<<s;
ss<<";\n";
}else{
ss<<"B[(gstartxB+"<<rowB<<"*lx + lidx)*(ldb/simdwidth) + k + "<<colB<<"*ly + lidy];\n";
}
}
}
}
if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl;
for(int rowB =0;rowB<wtile;rowB++){
for(int colB = 0;colB<ktile/simdwidth;colB++){
ss<<" const "<<dtype<<(simdwidth*2)<<" b"<<rowB<<"_"<<colB<<" = ";
if(storeb){
ss<<"ldsB["<<rowB<<"+lidy*wtile]["<<colB<<"];\n";
}else{
if(useImageB){
if(isDouble){
ss<<"as_double2(read_imagei(B,sampler,(int2)(k+"<<colB<<",j*wtile+"<<rowB<<")))";
}else{
ss<<"(read_imagef(B,sampler,(int2)(k+"<<colB<<",j*wtile+"<<rowB<<")))";
}
ss<<".s";
for(int s=0;s<simdwidth;s++) ss<<s;
ss<<";\n";
}else{
ss<<"B[(j*wtile+"<<rowB<<")*ldbs + k + "<<colB<<"];\n";
}
}
}
}
for(int rowA=0;rowA<htile;rowA++){
for(int colA =0;colA<ktile/simdwidth;colA++){
ss<<" const "<<dtype<<(simdwidth*2)<<" a"<<rowA<<"_"<<colA<<" = ";
if(storea){
ss<<"ldsA["<<rowA<<"+lidx*htile]["<<colA<<"];\n";
}else{
if(useImageA){
if(isDouble){
ss<<"as_double2(read_imagei(A,sampler,(int2)(k+"<<colA<<",i*htile+"<<rowA<<")))";
}else{
ss<<"(read_imagef(A,sampler,(int2)(k+"<<colA<<",i*htile+"<<rowA<<")))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss<<"A[(i*htile+"<<rowA<<")*ldas +k + "<<colA<<"];\n";
}
}
}
for(int colA =0;colA<ktile/simdwidth;colA++){
const int colB = colA;
for(int rowB=0;rowB<wtile;rowB++){
ss<<" sum"<<rowA<<"_"<<rowB;
ss<<" = fmaComplex"<<simdwidth<<"(a"<<rowA<<"_"<<colA<<",b"<<rowB<<"_"<<colB<<",";
ss<<" sum"<<rowA<<"_"<<rowB;
ss<<");\n";
}
}
}
if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl;
ss<<"}"<<endl;
for (int i = 0; i < htile; i++) {
for (int j = 0; j < wtile; j++) {
ss << "C[(i*" << htile << "+ " << i << ")*ldc + j*" << wtile << "+" << j << "]";
ss << "= mulComplex1(alpha,(";
for(int s=0;s<simdwidth;s++){
ss<<"sum"<<i<<"_"<<j<<".s";
ss<<(2*s)<<(2*s+1);
if(s<(simdwidth-1)) ss<<"+";
}
ss<<"))+ mulComplex1(beta,";
ss << "C[(i*" << htile << "+ " << i << ")*ldc + j*" << wtile << "+" << j << "]";
ss<<");\n";
}
}
//ss<<"}"<<endl;
ss<<"}"<<endl;
kernel = ss.str();
return true;
}
static bool genCkernelTNCons(int lsizex,
int lsizey,
int htile,
int wtile,
int ktile,
string dtype,
int simdwidth,
bool storea,
bool storeb,
int maxLocalMemElems,
int padding,
string& kernel,
bool useImageA = false,
bool useImageB = false){
//cout<<"StoreA "<<storea<<" "<<"StoreB "<<storeb<<" "<<htile<<" "<<wtile<<" "<<" "<<ktile<<" "<<simdwidth<<" "<<lsizex<<" "<<lsizey<<" "<<unroll;
//cout<<" "<<maxLocalMemElems<<" "<<endl;
bool isDouble = (dtype.compare("double")==0) ? true:false;
if(isDouble && simdwidth!=2 && (useImageA || useImageB)) return false;
if(!isDouble && simdwidth!=4 && (useImageA || useImageB)) return false;
//const int unroll = ktile;
if(storea){
/*Number of rows of A per workgroup = ktile. Has to be divisble by lsizey. */
if(ktile%lsizex!=0) return false;
/*Number of columns of A per workgroup = htile*lsizex*/
if((htile*lsizex)%(simdwidth*lsizey)!=0) return false;
}else{
if(htile%simdwidth!=0) return false;
}
if(storeb){
/*Number of columns of B per workgroup = wtile*lsizey. Has to be divisble by lsizex*simdwidth */
if(ktile%lsizex!=0) return false;
if(((wtile*lsizey)%(lsizey*simdwidth))!=0) return false;
}else{
if(wtile%simdwidth!=0) return false;
}
//cout<<"Check 2 passed"<<endl;
if(wtile%simdwidth!=0 || htile%simdwidth!=0) return false;
int numLocalMemElems = 0;
if(storea) numLocalMemElems += ktile*(htile*lsizex+padding);
if(storeb) numLocalMemElems += ktile*(wtile*lsizey+padding);
if(numLocalMemElems>maxLocalMemElems) return false;
//cout<<"Check 3 passed"<<endl;
//if(ktile%unroll!=0) return false;
//cout<<"Check 4 passed"<<endl;
stringstream ss;
ss<<"(";
if(useImageA){
ss<<"__read_only image2d_t A,";
}else{
ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict A,";
}
if(useImageB){
ss<<"__read_only image2d_t B,";
}else{
ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict B,";
}
ss<<"__global "<<dtype<<"2 *restrict C,unsigned int lda,unsigned int ldb,unsigned int ldc,unsigned int K,"<<dtype<<"2 alpha,"<<dtype<<"2 beta){"<<endl;
ss<<"const int htile ="<<htile<<";\n";
ss<<"const int wtile ="<<wtile<<";\n";
ss<<"const int ktile ="<<ktile<<";\n";
ss<<"const int simdwidth="<<simdwidth<<";\n";
ss<<"const int lx = "<<lsizex<<";\n";
ss<<"const int ly = "<<lsizey<<";\n";
ss<<"const int i = get_global_id(1);"<<endl;
ss<<"const int j = get_global_id(0);"<<endl;
//ss<<"const int unroll = "<<unroll<<";\n";
ss<<"const unsigned int lidx = get_local_id(1);"<<endl;
ss<<"const unsigned int lidy = get_local_id(0);"<<endl;
ss<<"int k;"<<endl;
if(storea){
ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsA["<<(ktile)<<"]["<<((htile/simdwidth)*lsizex+padding)<<"];"<<endl;
}
if(storeb){
ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsB["<<(ktile)<<"]["<<((wtile/simdwidth)*lsizey+padding)<<"];"<<endl;
}
for(int x=0;x<htile;x++){
for(int y=0;y<wtile/simdwidth;y++){
ss<<dtype<<(simdwidth*2)<<" sum"<<x<<"_"<<y<<" = ("<<dtype<<(simdwidth*2)<<")(0);\n";
}
}
ss<<"for(k=0;k<K;k+=ktile){"<<endl;
if(storea){
ss<<"const int gstartxA = get_group_id(1)*(htile/simdwidth)*lx;\n";
for(int y=0;y<(ktile/lsizex);y++){
for(int x=0;x<((htile*lsizex)/(simdwidth*lsizey));x++){
ss<<" ldsA["<<y<<"*lx + lidx]["<<x<<"*ly + lidy] = ";
if(useImageA){
if(isDouble){
ss<<"as_double2(read_imagei(A,sampler,(int2)(lidy+"<<x<<"*ly+gstartxA,k+"<<y<<"*lx + lidx )))";
}else{
ss<<"(read_imagef(A,sampler,(int2)(lidy+"<<x<<"*ly+gstartxA,k+"<<y<<"*lx + lidx)))";
}
ss<<".s";
for(int s=0;s<simdwidth;s++) ss<<s;
ss<<";\n";
}else{
ss<<"A[(k+"<<y<<"*lx+lidx)*(lda/simdwidth)+ gstartxA + lidy + "<<x<<"*ly];\n";
}
}
}
}
if(storeb){
ss<<"const int gstartxB = get_group_id(0)*(wtile/simdwidth)*ly;\n";
for(int y=0;y<(ktile/lsizex);y++){
for(int x=0;x<((wtile*lsizey)/(simdwidth*lsizey));x++){
ss<<" ldsB["<<y<<"*lx + lidx]["<<x<<"*ly + lidy] = ";
if(useImageB){
if(isDouble){
ss<<"as_double2(read_imagei(B,sampler,(int2)(lidy + "<<x<<"*ly+gstartxB,k+"<<y<<"*lx +lidx)))";
}else{
ss<<"(read_imagef(B,sampler,(int2)(lidy + "<<x<<"*ly+gstartxB,k+"<<y<<"*lx +lidx)))";
}
ss<<".s";
for(int s=0;s<simdwidth;s++) ss<<s;
ss<<";\n";
}else{
ss<<"B[(k+"<<y<<"*lx+lidx)*(ldb/simdwidth)+ gstartxB + lidy + "<<x<<"*ly];\n";
}
}
}
}
if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl;
//ss<<" for(kk=0;kk<ktile;kk+=unroll){\n";
ss<<"const int kk = 0;\n";
for(int y =0; y < ktile; y++){
for (int x = 0; x < wtile/simdwidth; x++) {
ss << " const " << dtype << (simdwidth*2) << " b" << x << "_" << y << " = ";
if(storeb){
ss << "ldsB[kk+"<<y<<"][lidy*(wtile/simdwidth)+"<<x<<"];\n";
}else{
if(useImageB){
if(isDouble){
ss<<"as_double2( read_imagei(B,sampler,(int2)(j*(wtile/simdwidth)+"<<x<<",k+kk+"<<y<<")))";
}else{
ss<<"( read_imagef(B,sampler,(int2)(j*(wtile/simdwidth)+"<<x<<",k+kk+"<<y<<")))";
}
ss<<".s";
for(int s=0;s<simdwidth;s++) ss<<s;
ss<<";\n";
}else{
ss << "B[(k+kk+"<<y<<")*(ldb/simdwidth)+j*(wtile/simdwidth)+"<<x<<"];\n";
}
}
}
for (int x = 0; x < htile/simdwidth; x++) {
ss << " const " << dtype << (simdwidth*2) << " a" << x << "_" << y << " = ";
if(storea){
ss << "ldsA[kk+"<<y<<"]["<<"lidx*(htile/simdwidth)+"<<x<<"];\n";
}else{
if(useImageA){
if(isDouble) {
ss<<"as_double2(read_imagei(A,sampler,(int2)(i*(htile/simdwidth)+"<<x<<",k+kk+"<<y<<")))";
}else{
ss<<"(read_imagef(A,sampler,(int2)(i*(htile/simdwidth)+"<<x<<",k+kk+"<<y<<")))";
}
ss<<".s";
for(int s=0;s<simdwidth;s++) ss<<s;
ss<<";\n";
}else{
ss << "A[(k+kk+"<<y<<")*(lda/simdwidth)+i*(htile/simdwidth)+"<<x<<"];"<<endl;
}
}
for(int xoff=0;xoff<simdwidth;xoff++){
int row = x*simdwidth + xoff;
for(int w=0;w<wtile/simdwidth; w++){
ss<<" sum"<<row<<"_"<<w;
ss<<" = fmaComplex"<<simdwidth<<"(a"<<x<<"_"<<y;
if(simdwidth>1){
ss<<".s";
for(int m=0;m<simdwidth;m++) {
ss<<(2*xoff)<<(2*xoff+1);
}
}
ss<<",b"<<w<<"_"<<y<<",";
ss<<" sum"<<row<<"_"<<w<<");\n";
}
}
}
}
//ss<<" }\n";
if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl;
ss<<"}"<<endl;
for (int i = 0; i < htile; i++) {
for (int j = 0; j < wtile; j++) {
ss << "C[(i*" << htile << "+ " << i << ")*ldc + j*" << wtile << "+" << j << "]";
ss << "= mulComplex1(alpha,sum"<<i<<"_"<<(j/simdwidth);
if(simdwidth>1) ss<<".s"<<(2*(j%simdwidth))<<(2*(j%simdwidth)+1);
ss<<") + ";
ss << "mulComplex1(beta,C[(i*" << htile << "+ " << i << ")*ldc + j*" << wtile << "+" << j << "]";
//ss<<"C[(i*"<<htile<<"+ i)*N + j*"<<wtile<<"+"<<offset<<"]";
ss << ");" << endl;
}
}
ss<<"}"<<endl;
kernel = ss.str();
return true;
}
static bool genCkernelNTOff(int lsizex, int lsizey, int htile, int wtile, int ktile, string dtype,int simdwidth, bool storea, bool storeb, int maxLocalMemElems,
int padding,string& kernel, bool useImageA,bool useImageB){
//cout<<"StoreA "<<storea<<" "<<"StoreB "<<storeb<<" "<<htile<<" "<<wtile<<" "<<" "<<ktile<<" "<<simdwidth<<" "<<lsizex<<" "<<lsizey<<" "<<unroll;
//cout<<" "<<maxLocalMemElems<<" "<<endl;
if(storea){
/*Number of rows of A per workgroup = htile*lsizex. Has to be divisble by lsizex. Trivially satisfied */
/*Number of columns of A per workgroup = ktile. Has to be divisble by lsizey*simdwidth */
if(ktile%(simdwidth*lsizey)!=0) return false;
}
if(storeb){
/*Number of columns of B per workgroup = ktile. Has to be divisble by lsizey*simdwidth */
if(ktile%(lsizey*simdwidth)!=0) return false;
/*Number of rows of B per workgroup = wtile*lsizey. Has to be divisble by lsizex*/
if((wtile*lsizey)%lsizex!=0) return false;
}
//cout<<"Check 2 passed"<<endl;
bool isDouble = (dtype.compare("double")==0);
if(ktile%simdwidth!=0) return false;
int numLocalMemElems = 0;
if(storea) numLocalMemElems += htile*lsizex*(ktile+padding);
if(storeb) numLocalMemElems += wtile*lsizey*(ktile+padding);
if(numLocalMemElems>maxLocalMemElems) return false;
//cout<<"Check 3 passed"<<endl;
//cout<<"Check 4 passed"<<endl;
stringstream ss;
ss<<"(";
if(useImageA){
ss<<"__read_only image2d_t A,";
}else{
ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict A,";
}
if(useImageB){
ss<<"__read_only image2d_t B,";
}else{
ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict B,";
}
ss<<"__global "<<dtype<<"2 *restrict C,unsigned int lda,unsigned int ldb,unsigned int ldc,unsigned int K,"<<dtype<<"2 alpha,"<<dtype<<"2 beta){"<<endl;
ss<<"const int htile ="<<htile<<";\n";
ss<<"const int wtile ="<<wtile<<";\n";
ss<<"const int ktile ="<<ktile<<";\n";
ss<<"const int simdwidth="<<simdwidth<<";\n";
ss<<"const int lx = "<<lsizex<<";\n";
ss<<"const int ly = "<<lsizey<<";\n";
ss<<"const int i = get_global_id(1);\n";
ss<<"const int j = get_global_id(0);\n";
ss<<"const unsigned int lidx = get_local_id(1);"<<endl;
ss<<"const unsigned int lidy = get_local_id(0);"<<endl;
ss<<"unsigned int k;"<<endl;
if(storea){
ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsA["<<(htile*lsizex)<<"]["<<((ktile/simdwidth)+padding)<<"];"<<endl;
}
if(storeb){
ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsB["<<(wtile*lsizey)<<"]["<<((ktile/simdwidth)+padding)<<"];"<<endl;
}
for(int x=0;x<htile;x++){
for(int y=0;y<wtile;y++){
ss<<dtype<<(simdwidth*2)<<" sum"<<x<<"_"<<y<<" = ("<<dtype<<(simdwidth*2)<<")(0);\n";
}
}
ss<<"const unsigned int ldbs = ldb/simdwidth;\n";
ss<<"const unsigned int ldas = lda/simdwidth;\n";
ss<<"for(k=0;k<K/simdwidth;k+=(ktile/simdwidth)){"<<endl;
if(storea){
ss<<"const int gstartxA = get_group_id(1)*htile*lx;\n";
for(int rowA=0;rowA<htile;rowA++){
for(int colA=0;colA<(ktile/(lsizey*simdwidth));colA++){
ss<<" ldsA["<<rowA<<"*lx + lidx]["<<colA<<"*ly + lidy] = ";
if(useImageA){
if(isDouble){
ss<<"as_double2(read_imagei(A,sampler,(int2)(k+"<<colA<<"*ly+lidy,gstartxA+"<<rowA<<"*lx+lidx)))";
}else{
ss<<"(read_imagef(A,sampler,(int2)(k+"<<colA<<"*ly+lidy,gstartxA+"<<rowA<<"*lx+lidx)))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss<<"A[(gstartxA+"<<rowA<<"*lx + lidx)*(lda/simdwidth) + k + "<<colA<<"*ly + lidy];\n";
}
}
}
}
if(storeb){
ss<<"const int gstartxB = get_group_id(0)*wtile*ly;\n";
for(int rowB=0;rowB<(wtile*lsizey)/lsizex;rowB++){
for(int colB=0;colB<(ktile/(lsizey*simdwidth));colB++){
ss<<" ldsB["<<rowB<<"*lx + lidx]["<<colB<<"*ly + lidy] = ";
if(useImageB){
if(isDouble){
ss<<"as_double2(read_imagei(B,sampler,(int2)(k+"<<colB<<"*ly+lidy,gstartxB+"<<rowB<<"*lx+lidx)))";
}else{
ss<<"(read_imagef(B,sampler,(int2)(k+"<<colB<<"*ly+lidy,gstartxB+"<<rowB<<"*lx+lidx)))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss<<"B[(gstartxB+"<<rowB<<"*lx + lidx)*(ldb/simdwidth) + k + "<<colB<<"*ly + lidy];\n";
}
}
}
}
if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl;
for(int rowB =0;rowB<wtile;rowB++){
for(int colB = 0;colB<ktile/simdwidth;colB++){
ss<<" const "<<dtype<<(simdwidth*2)<<" b"<<rowB<<"_"<<colB<<" = ";
if(storeb){
ss<<"ldsB["<<rowB<<"*ly+lidy]["<<colB<<"];\n";
}else{
if(useImageB){
if(isDouble){
ss<<"as_double2(read_imagei(B,sampler,(int2)(k+"<<colB<<",get_group_id(0)*wtile*ly+"<<rowB<<"*ly+lidy)))";
}else{
ss<<"(read_imagef(B,sampler,(int2)(k+"<<colB<<",get_group_id(0)*wtile*ly+"<<rowB<<"*ly+lidy)))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss<<"B[(get_group_id(0)*wtile*ly + "<<rowB<<"*ly + lidy)*ldbs + k + "<<colB<<"];\n";
}
}
}
}
for(int rowA=0;rowA<htile;rowA++){
for(int colA =0;colA<ktile/simdwidth;colA++){
ss<<" const "<<dtype<<(simdwidth*2)<<" a"<<rowA<<"_"<<colA<<" = ";
if(storea){
ss<<"ldsA["<<rowA<<"*lx+lidx]["<<colA<<"];\n";
}else{
if(useImageA){
if(isDouble){
ss<<"as_double2(read_imagei(A,sampler,(int2)(k+"<<colA<<",get_group_id(1)*htile*lx+"<<rowA<<"*lx+lidx)))";
}else{
ss<<"(read_imagef(A,sampler,(int2)(k+"<<colA<<",get_group_id(1)*htile*lx+"<<rowA<<"*lx+lidx)))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss<<"A[(get_group_id(1)*htile*lx+ "<<rowA<<"*lx+lidx )*ldas +k + "<<colA<<"];\n";
}
}
const int colB = colA;
for(int rowB=0;rowB<wtile;rowB++){
ss<<" sum"<<rowA<<"_"<<rowB;
ss<<" = fmaComplex"<<simdwidth<<"(a"<<rowA<<"_"<<colA<<",b"<<rowB<<"_"<<colB<<",";
ss<<" sum"<<rowA<<"_"<<rowB;
ss<<");\n";
}
}
}
if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl;
ss<<"}"<<endl;
ss<<"const unsigned int Cx = get_group_id(1)*htile*lx;"<<endl;
ss<<"const unsigned int Cy = get_group_id(0)*wtile*ly;"<<endl;
for (int i = 0; i < htile; i++) {
for (int j = 0; j < wtile; j++) {
ss << "C[(Cx + " << i<< "*lx + lidx)*ldc + Cy + " << j << "*ly + lidy]";
ss << "= mulComplex1(alpha,(";
for(int s=0;s<simdwidth;s++){
ss<<"sum"<<i<<"_"<<j;
ss<<".s"<<(2*s)<<(2*s+1);
if(s<(simdwidth-1)) ss<<"+";
}
ss<<"))+ mulComplex1(beta,(";
ss << "C[(Cx + " << i<< "*lx + lidx)*ldc + Cy + " << j << "*ly + lidy]";
ss<<"));\n";
}
}
//ss<<"}"<<endl;
ss<<"}"<<endl;
kernel = ss.str();
return true;
}
static bool genCkernelNNCons(int lsizex,
int lsizey,
int htile,
int wtile,
int ktile,
string dtype,
int simdwidth,
bool storea,
bool storeb,
int maxLocalMemElems,
int padding,
string& kernel,bool useImageA,bool useImageB){
bool isDouble = (dtype.compare("double")==0);
//cout<<"StoreA "<<storea<<" "<<"StoreB "<<storeb<<" "<<htile<<" "<<wtile<<" "<<" "<<ktile<<" "<<simdwidth<<" "<<lsizex<<" "<<lsizey<<" "<<unroll;
//cout<<" "<<maxLocalMemElems<<" "<<endl;
if(storea){
/*Number of rows of A per workgroup = htile*lsizex. Has to be divisble by lsizex. Trivially satisfied */
/*Number of columns of A per workgroup = ktile. Has to be divisble by lsizey*simdwidth */
if(ktile%(simdwidth*lsizey)!=0) return false;
}
if(storeb){
/*Number of columns of B per workgroup = wtile*lsizey. Has to be divisble by lsizey*simdwidth */
if(ktile%lsizex!=0) return false;
if(((wtile*lsizey)%(lsizey*simdwidth))!=0) return false;
}
//cout<<"Check 2 passed"<<endl;
if(wtile%simdwidth!=0 || ktile%simdwidth!=0) return false;
if(!storea && !storeb && ktile>simdwidth) return false;
int numLocalMemElems = 0;
if(storea) numLocalMemElems += htile*lsizex*(ktile+padding);
if(storeb) numLocalMemElems += ktile*(wtile*lsizey+padding);
if(numLocalMemElems>maxLocalMemElems) return false;
//cout<<"Check 3 passed"<<endl;
//cout<<"Check 4 passed"<<endl;
stringstream ss;
ss<<"(";
if(useImageA){
ss<<"__read_only image2d_t A,";
}else{
ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict A,";
}
if(useImageB){
ss<<"__read_only image2d_t B,";
}else{
ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict B,";
}
ss<<"__global "<<dtype<<"2 *restrict C,unsigned int lda,unsigned int ldb,unsigned int ldc,unsigned int K,"<<dtype<<"2 alpha,"<<dtype<<"2 beta){"<<endl;
ss<<"const int htile ="<<htile<<";\n";
ss<<"const int wtile ="<<wtile<<";\n";
ss<<"const int ktile ="<<ktile<<";\n";
ss<<"const int simdwidth="<<simdwidth<<";\n";
ss<<"const int lx = "<<lsizex<<";\n";
ss<<"const int ly = "<<lsizey<<";\n";
ss<<"const int i = get_global_id(1);"<<endl;
ss<<"const int j = get_global_id(0);"<<endl;
ss<<"const unsigned int lidx = get_local_id(1);"<<endl;
ss<<"const unsigned int lidy = get_local_id(0);"<<endl;
ss<<"int k;"<<endl;
if(storea){
ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsA["<<(htile*lsizex)<<"]["<<((ktile/simdwidth)+padding)<<"];"<<endl;
}
if(storeb){
ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsB["<<(ktile)<<"]["<<((wtile/simdwidth)*lsizey+padding)<<"];"<<endl;
}
for(int x=0;x<htile;x++){
for(int y=0;y<wtile/simdwidth;y++){
ss<<dtype<<(simdwidth*2)<<" sum"<<x<<"_"<<y<<" = ("<<dtype<<(simdwidth*2)<<")(0);\n";
}
}
ss<<"for(k=0;k<K;k+=ktile){"<<endl;
if(storea){
ss<<"const int gstartxA = get_group_id(1)*htile*lx;\n";
for(int x=0;x<htile;x++){
for(int y=0;y<(ktile/(lsizey*simdwidth));y++){
ss<<" ldsA["<<x<<"*lx + lidx]["<<y<<"*ly + lidy] = ";
if(useImageA){
if(isDouble){
ss<<"as_double2(read_imagei(A,sampler,(int2)(k/simdwidth +"<<y<<"*ly+lidy,gstartxA+"<<x<<"*lx+lidx)))";
}else{
ss<<"(read_imagef(A,sampler,(int2)(k/simdwidth+"<<y<<"*ly+lidy,gstartxA+"<<x<<"*lx+lidx)))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss<<"A[(gstartxA+"<<x<<"*lx + lidx)*(lda/simdwidth) + k/simdwidth + "<<y<<"*ly + lidy];\n";
}
}
}
}
if(storeb){
ss<<"const int gstartxB = get_group_id(0)*(wtile/simdwidth)*ly;\n";
for(int x=0;x<(wtile/simdwidth);x++){
for(int y=0;y<(ktile/lsizex);y++){
ss<<" ldsB["<<y<<"*lx + lidx]["<<x<<"*ly + lidy] = ";
if(useImageB){
if(isDouble){
ss<<"as_double2(read_imagei(B,sampler,(int2)(gstartxB + lidy + "<<x<<"*ly,k+"<<y<<"*lx +lidx)))";
}else{
ss<<"(read_imagef(B,sampler,(int2)(gstartxB + lidy + "<<x<<"*ly,k+"<<y<<"*lx +lidx)))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss<<"B[(k+"<<y<<"*lx+lidx)*(ldb/simdwidth)+ gstartxB + lidy + "<<x<<"*ly];\n";
}
}
}
}
if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl;
/*for (int x = 0; x < wtile/simdwidth; x++) {
for (int y = 0; y < ktile; y++) {
ss << " const " << dtype << simdwidth << " b" << x << "_" << y << " = ";
if(storeb){
ss << "ldsB["<<y<<"][lidy*(wtile/simdwidth)+"<<x<<"];\n";
}else{
ss << "B[(k+"<<y<<")*(ldb/simdwidth)+j*(wtile/simdwidth)+"<<x<<"];\n";
}
}
}*/
for (int k = 0; k < ktile/simdwidth; k++) {
for (int koff = 0; koff < simdwidth; koff++) {
for (int x = 0; x < wtile/simdwidth; x++) {
int rowB = k*simdwidth+koff;
ss << " const " << dtype << (simdwidth*2) << " b" << x << "_" << rowB << " = ";
if(storeb){
ss << "ldsB["<<rowB<<"][lidy*(wtile/simdwidth)+"<<x<<"];\n";
}else{
if(useImageB){
if(isDouble){
ss<<"as_double2(read_imagei(B,sampler,(int2)(j*(wtile/simdwidth) + "<<x<<",k+"<<rowB<<")))";
}else{
ss<<"(read_imagef(B,sampler,(int2)(j*(wtile/simdwidth) + "<<x<<",k+"<<rowB<<")))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss << "B[(k+"<<rowB<<")*(ldb/simdwidth)+j*(wtile/simdwidth)+"<<x<<"];\n";
}
}
}
}
for(int y =0; y < htile; y++){
ss << " const " << dtype << (simdwidth*2) << " a" << k << "_" << y << " = ";
if(storea){
ss << "ldsA["<<y<<"+lidx*htile]["<<k<<"];\n";
}else{
if(useImageA){
if(isDouble){
ss<<"as_double2(read_imagei(A,sampler,(int2)(k/simdwidth +"<<k<<",i*htile+"<<y<<")))";
}else{
ss<<"(read_imagef(A,sampler,(int2)(k/simdwidth+"<<k<<",i*htile + "<<y<<")))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss << "A[(i*htile + "<<y<<")*(lda/simdwidth) + k/simdwidth+"<<k<<"];"<<endl;
}
}
for(int koff=0;koff<simdwidth;koff++){
int rowB = (k*simdwidth+koff);
for(int x = 0;x<(wtile/simdwidth);x++){
ss<<"sum"<<y<<"_"<<x<<" = fmaComplex"<<simdwidth<<"(a"<<k<<"_"<<y;
ss<<".s";
for(int t=0;t<simdwidth;t++) ss<<(2*koff)<<(2*koff+1);
ss<<",b"<<x<<"_"<<rowB<<",";
ss<<"sum"<<y<<"_"<<x<<");\n";
}
}
}
}
if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl;
ss<<"}"<<endl;
for (int i = 0; i < htile; i++) {
for (int j = 0; j < wtile; j++) {
ss << "C[(i*" << htile << "+ " << i << ")*ldc + j*" << wtile << "+" << j << "]";
ss << "= mulComplex1(alpha,sum"<<i<<"_"<<(j/simdwidth);
ss<<".s"<<2*(j%simdwidth)<<(2*(j%simdwidth)+1);
ss<<") + mulComplex1(beta,";
ss << "C[(i*" << htile << "+ " << i << ")*ldc + j*" << wtile << "+" << j << "])";
ss << ";" << endl;
}
}
ss<<"}"<<endl;
kernel = ss.str();
return true;
}
static bool genCkernelNNOff(int lsizex,
int lsizey,
int htile,
int wtile,
int ktile,
string dtype,
int simdwidth,
bool storea,
bool storeb,
int maxLocalMemElems,
int padding,
string& kernel,bool useImageA,bool useImageB){
bool isDouble = (dtype.compare("double")==0);
//cout<<"StoreA "<<storea<<" "<<"StoreB "<<storeb<<" "<<htile<<" "<<wtile<<" "<<" "<<ktile<<" "<<simdwidth<<" "<<lsizex<<" "<<lsizey<<" "<<unroll;
//cout<<" "<<maxLocalMemElems<<" "<<endl;
if(storea){
/*Number of rows of A per workgroup = htile*lsizex. Has to be divisble by lsizex. Trivially satisfied */
/*Number of columns of A per workgroup = ktile. Has to be divisble by lsizey*simdwidth */
if(ktile%(simdwidth*lsizey)!=0) return false;
}
if(storeb){
/*Number of columns of B per workgroup = wtile*lsizey. Has to be divisble by lsizey*simdwidth */
if(ktile%lsizex!=0) return false;
if(((wtile*lsizey)%(lsizey*simdwidth))!=0) return false;
}
//cout<<"Check 2 passed"<<endl;
if(wtile%simdwidth!=0 || ktile%simdwidth!=0) return false;
if(!storea && !storeb && ktile>simdwidth) return false;
int numLocalMemElems = 0;
if(storea) numLocalMemElems += htile*lsizex*(ktile+padding);
if(storeb) numLocalMemElems += ktile*(wtile*lsizey+padding);
if(numLocalMemElems>maxLocalMemElems) return false;
//cout<<"Check 3 passed"<<endl;
//cout<<"Check 4 passed"<<endl;
stringstream ss;
ss<<"(";
if(useImageA){
ss<<"__read_only image2d_t A,";
}else{
ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict A,";
}
if(useImageB){
ss<<"__read_only image2d_t B,";
}else{
ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict B,";
}
ss<<"__global "<<dtype<<"2 *restrict C,unsigned int lda,unsigned int ldb,unsigned int ldc,unsigned int K,"<<dtype<<"2 alpha,"<<dtype<<"2 beta){"<<endl;
ss<<"const int htile ="<<htile<<";\n";
ss<<"const int wtile ="<<wtile<<";\n";
ss<<"const int ktile ="<<ktile<<";\n";
ss<<"const int simdwidth="<<simdwidth<<";\n";
ss<<"const int lx = "<<lsizex<<";\n";
ss<<"const int ly = "<<lsizey<<";\n";
ss<<"const int i = get_global_id(1);"<<endl;
ss<<"const int j = get_global_id(0);"<<endl;
ss<<"const unsigned int lidx = get_local_id(1);"<<endl;
ss<<"const unsigned int lidy = get_local_id(0);"<<endl;
ss<<"int k;"<<endl;
if(storea){
ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsA["<<(htile*lsizex)<<"]["<<((ktile/simdwidth)+padding)<<"];"<<endl;
}
if(storeb){
ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsB["<<(ktile)<<"]["<<((wtile/simdwidth)*lsizey+padding)<<"];"<<endl;
}
for(int x=0;x<htile;x++){
for(int y=0;y<wtile/simdwidth;y++){
ss<<dtype<<(simdwidth*2)<<" sum"<<x<<"_"<<y<<" = ("<<dtype<<(simdwidth*2)<<")(0);\n";
}
}
ss<<"for(k=0;k<K;k+=ktile){"<<endl;
if(storea){
ss<<"const int gstartxA = get_group_id(1)*htile*lx;\n";
for(int x=0;x<htile;x++){
for(int y=0;y<(ktile/(lsizey*simdwidth));y++){
ss<<" ldsA["<<x<<"*lx + lidx]["<<y<<"*ly + lidy] = ";
if(useImageA){
if(isDouble){
ss<<"as_double2(read_imagei(A,sampler,(int2)(k/simdwidth +"<<y<<"*ly+lidy,gstartxA+"<<x<<"*lx+lidx)))";
}else{
ss<<"(read_imagef(A,sampler,(int2)(k/simdwidth+"<<y<<"*ly+lidy,gstartxA+"<<x<<"*lx+lidx)))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss<<"A[(gstartxA+"<<x<<"*lx + lidx)*(lda/simdwidth) + k/simdwidth + "<<y<<"*ly + lidy];\n";
}
}
}
}
if(storeb){
ss<<"const int gstartxB = get_group_id(0)*(wtile/simdwidth)*ly;\n";
for(int x=0;x<(wtile/simdwidth);x++){
for(int y=0;y<(ktile/lsizex);y++){
ss<<" ldsB["<<y<<"*lx + lidx]["<<x<<"*ly + lidy] = ";
if(useImageB){
if(isDouble){
ss<<"as_double2(read_imagei(B,sampler,(int2)(gstartxB + lidy + "<<x<<"*ly,k+"<<y<<"*lx +lidx)))";
}else{
ss<<"(read_imagef(B,sampler,(int2)(gstartxB + lidy + "<<x<<"*ly,k+"<<y<<"*lx +lidx)))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss<<"B[(k+"<<y<<"*lx+lidx)*(ldb/simdwidth)+ gstartxB + lidy + "<<x<<"*ly];\n";
}
}
}
}
if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl;
/*for (int x = 0; x < wtile/simdwidth; x++) {
for (int y = 0; y < ktile; y++) {
ss << " const " << dtype << simdwidth << " b" << x << "_" << y << " = ";
if(storeb){
ss << "ldsB["<<y<<"][lidy*(wtile/simdwidth)+"<<x<<"];\n";
}else{
ss << "B[(k+"<<y<<")*(ldb/simdwidth)+j*(wtile/simdwidth)+"<<x<<"];\n";
}
}
}*/
for (int k = 0; k < ktile/simdwidth; k++) {
for (int koff = 0; koff < simdwidth; koff++) {
for (int x = 0; x < wtile/simdwidth; x++) {
int rowB = k*simdwidth+koff;
ss << " const " << dtype << (simdwidth*2) << " b" << x << "_" << rowB << " = ";
if(storeb){
ss << "ldsB["<<rowB<<"][lidy+ly*"<<x<<"];\n";
}else{
if(useImageB){
if(isDouble){
ss<<"as_double2(read_imagei(B,sampler,(int2)(get_group_id(0)*(wtile/simdwidth)*ly + lidy+"<<x<<"*ly,k+"<<rowB<<")))";
}else{
ss<<"(read_imagef(B,sampler,(int2)(get_group_id(0)*(wtile/simdwidth)*ly + lidy+"<<x<<"*ly,k+"<<rowB<<")))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss << "B[(k+"<<rowB<<")*(ldb/simdwidth)+get_group_id(0)*(wtile/simdwidth)*ly + lidy+"<<x<<"*ly];\n";
}
}
}
}
for(int y =0; y < htile; y++){
ss << " const " << dtype << (simdwidth*2) << " a" << k << "_" << y << " = ";
if(storea){
ss << "ldsA["<<y<<"*lx+lidx]["<<k<<"];\n";
}else{
if(useImageA){
if(isDouble){
ss<<"as_double2(read_imagei(A,sampler,(int2)(k/simdwidth+"<<k<<",get_group_id(1)*htile*lx + lx*"<<y<<"+lidx)))";
}else{
ss<<"(read_imagef(A,sampler,(int2)(k/simdwidth+"<<k<<",get_group_id(1)*htile*lx + lx*"<<y<<"+lidx)))";
}
ss<<".s";
for(int s=0;s<simdwidth*2;s++) ss<<s;
ss<<";\n";
}else{
ss << "A[(get_group_id(1)*htile*lx + lx*"<<y<<"+lidx)*(lda/simdwidth) + k/simdwidth+"<<k<<"];"<<endl;
}
}
for(int koff=0;koff<simdwidth;koff++){
int rowB = (k*simdwidth+koff);
for(int x = 0;x<(wtile/simdwidth);x++){
ss<<"sum"<<y<<"_"<<x<<" = fmaComplex"<<simdwidth<<"(a"<<k<<"_"<<y;
ss<<".s";
for(int t=0;t<simdwidth;t++) ss<<(2*koff)<<(2*koff+1);
ss<<",b"<<x<<"_"<<rowB<<",";
ss<<"sum"<<y<<"_"<<x<<");\n";
}
}
}
}
if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl;
ss<<"}"<<endl;
ss<<"const unsigned int Cx = get_group_id(1)*htile*lx;"<<endl;
ss<<"const unsigned int Cy = get_group_id(0)*wtile*ly;"<<endl;
for (int i = 0; i < htile; i++) {
for (int j = 0; j < wtile; j++) {
ss << "C[( Cx+ lidx+lx*"<< i << ")*ldc + Cy + simdwidth*lidy + simdwidth*ly*" << j/simdwidth << "+"<<(j%simdwidth)<<"]";
ss << "= mulComplex1(alpha,sum"<<i<<"_"<<(j/simdwidth);
const int off = j%simdwidth;
ss<<".s"<<(2*off)<<(2*off+1);
ss<<") + mulComplex1(beta,";
ss << "C[( Cx+ lidx+lx*"<< i << ")*ldc + Cy + simdwidth*lidy + simdwidth*ly*" << j/simdwidth << "+"<<(j%simdwidth)<<"])";
//ss<<"C[(i*"<<htile<<"+ i)*N + j*"<<wtile<<"+"<<offset<<"]";
ss << ";" << endl;
}
}
ss<<"}"<<endl;
kernel = ss.str();
return true;
}
template <typename T>
static double testGemmComplex(unsigned int N,cl_device_id dvc,cl_context ctx,cl_kernel krnl, RaijinGemmOptKernel& optkernel, RaijinTranspose *transObj,
RaijinCopy *copyObj,
RaijinScale *scaleObj,bool verify=true){
typedef typename T::ctype ctype;
typedef typename T::basetype basetype;
size_t size = sizeof(ctype) * N * N;
cl_mem bufA, bufB, bufC;
ctype *ptrA = new ctype[N * N];
ctype *ptrB = new ctype[N * N];
ctype *ptrC = new ctype[N * N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if(optkernel.transA){
ptrA[i * N + j].s[0] = 0.002 * j;
ptrA[i*N +j].s[1] = 1;
}else{
ptrA[i*N + j].s[0] = 0.002*i;
ptrA[i*N+j].s[1] = 1;
}
if(optkernel.transB){
ptrB[i * N + j].s[0] = 0.002 * i;
ptrB[i*N+j].s[1] = 1;
}else{
ptrB[i*N + j].s[0] = 0.002*j;
ptrB[i*N+j].s[1] = 1;
}
ptrC[i * N + j].s[0] = 0;
ptrC[i*N+j].s[1] = 0;
}
}
cl_command_queue q = clCreateCommandQueue(ctx,dvc,0,NULL);
cl_int errcode;
bufA = clCreateBuffer(ctx, CL_MEM_READ_ONLY, size, NULL, &errcode);
bufB = clCreateBuffer(ctx, CL_MEM_READ_ONLY, size, NULL, &errcode);
bufC = clCreateBuffer(ctx, CL_MEM_READ_WRITE, size, NULL, &errcode);
clEnqueueWriteBuffer(q, bufA, CL_TRUE, 0, size, ptrA, 0, NULL, NULL);
clEnqueueWriteBuffer(q, bufB, CL_TRUE, 0, size, ptrB, 0, NULL, NULL);
clEnqueueWriteBuffer(q, bufC, CL_TRUE, 0, size, ptrC, 0, NULL, NULL);
clFlush( q);
const int niters = 3;
double tdiff = 0;
for(int i=0;i<niters;i++){
RTimer rt;
rt.start();
ctype alpha;
alpha.s[0] = 1;
alpha.s[1] = 0;
ctype beta;
beta.s[0] = 0;
beta.s[1] = 0;
RaijinCleaner *cleaner = new RaijinCleaner;
cl_event evt = raijinApplyOpt<ctype>(q,cleaner,krnl,optkernel,ctx,dvc,RaijinCL::RaijinRowMajor,optkernel.transA,optkernel.transB,N,N,N,
alpha,bufA,N,bufB,N,beta,bufC,N,transObj,copyObj,scaleObj);
clFinish(q);
delete cleaner;
rt.stop();
if(i>0){
tdiff += rt.getDiff();
cout<<rt.getDiff()<<endl;
}
}
tdiff /= (niters-1);
if(verify){
clEnqueueReadBuffer(q, bufC, CL_TRUE, 0, size, ptrC, 0, NULL, NULL);
double totalerror = 0.0;
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
basetype calc = ptrC[i*N+j].s[0];
basetype expected = N*((0.002*i)*(0.002*j)-1);
double val = calc - expected;
if(val<0) val = -val;
//if(val>1) cout<<"Real: "<<i<<" "<<j<<" "<<calc<<" "<<expected<<endl;
//if(val>1) exit(-1);
basetype calcimg = ptrC[i*N+j].s[1];
basetype expimg = N*(0.002*i+0.002*j);
double valimg = calcimg - expimg;
if(valimg<0) valimg *= -1;
totalerror += (val+valimg);
}
}
double avgerror = (totalerror)/(N*N);
cout<<"Avg absolute error "<<(totalerror/(N*N))<<endl;
//if(avgerror>1.0) exit(-1);
}
clReleaseMemObject(bufA);
clReleaseMemObject(bufB);
clReleaseMemObject(bufC);
delete[] ptrA;
delete[] ptrB;
delete[] ptrC;
clReleaseCommandQueue(q);
return 8.0e-9*N*(1.0*N)*(1.0*N)/tdiff;
}
string genCmulFuncs(bool isDouble){
string dtype = (isDouble)? "double":"float";
stringstream ss;
//mulComplex1
if(isDouble){
ss<<"#ifdef cl_khr_fp64\n"<<endl;
ss<<"#pragma OPENCL EXTENSION cl_khr_fp64 : enable"<<endl;
ss<<"#else"<<endl;
ss<<"#pragma OPENCL EXTENSION cl_amd_fp64 : enable"<<endl;
ss<<"#endif"<<endl;
}
ss<<dtype<<"2 mulComplex1("<<dtype<<"2 a,"<<dtype<<"2 b){"<<endl;
ss<<dtype<<"2 c;"<<endl;
//if(isDouble) ss<<"#ifndef FP_FAST_FMAF"<<endl;
//ss<<"c.x = a.x*b.x - a.y*b.y;"<<endl;
//if(isDouble){
//ss<<"#else"<<endl;
ss<<dtype<<" temp = -a.y*b.y;"<<endl;
ss<<"c.x = fma(a.x,b.x,temp);"<<endl;
//ss<<"#endif"<<endl;
//}
//if(isDouble) ss<<"#ifndef FP_FAST_FMAF"<<endl;
//ss<<"c.y = a.x*b.y + a.y*b.x;"<<endl;
//if(isDouble){
//ss<<"#else"<<endl;
ss<<dtype<<" temp2 = a.y*b.x;"<<endl;
ss<<"c.y = fma(a.x,b.y,temp2);"<<endl;
//ss<<"#endif"<<endl;
//}
ss<<"return c;\n}"<<endl;
//mulComplex2
ss<<dtype<<"4 mulComplex2("<<dtype<<"4 a,"<<dtype<<"4 b){"<<endl;
ss<<dtype<<"4 c;"<<endl;
ss<<"c.s01 = mulComplex1(a.s01,b.s01); c.s23 = mulComplex1(a.s23,b.s23);"<<endl;
ss<<"return c;\n}"<<endl;
//fmaComplex1
ss<<dtype<<"2 fmaComplex1("<<dtype<<"2 a,"<<dtype<<"2 b,"<<dtype<<"2 c){"<<endl;
ss<<" "<<dtype<<"2 res;"<<endl;
if(isDouble) ss<<"#ifndef FP_FAST_FMAF"<<endl;
ss<<" res.x = a.x*b.x + c.x;"<<endl;
ss<<" res.y = a.x*b.y + c.y;"<<endl;
ss<<" res.x = -a.y*b.y + res.x;"<<endl;
ss<<" res.y = a.y*b.x + res.y;"<<endl;
if(isDouble){
ss<<"#else"<<endl;
ss<<" res.x = fma(-a.y,b.y,c.x);"<<endl;
ss<<" res.y = fma(a.y,b.x,c.y);"<<endl;
ss<<" res.x = fma(a.x,b.x,res.x);"<<endl;
ss<<" res.y = fma(a.x,b.y,res.y);"<<endl;
ss<<"#endif"<<endl;
}
ss<<" return res;"<<endl;
ss<<"}"<<endl;
//fmaComplex2
ss<<dtype<<"4 fmaComplex2("<<dtype<<"4 a,"<<dtype<<"4 b,"<<dtype<<"4 c){"<<endl;
ss<<dtype<<"4 res;"<<endl;
ss<<"res.s01 = fmaComplex1(a.s01,b.s01,c.s01); res.s23 = fmaComplex1(a.s23,b.s23,c.s23);"<<endl;
ss<<"return res;\n}"<<endl;
/*ss<<dtype<<"2 are = a.s02,aim =a.s13;\n";
ss<<dtype<<"2 bre = b.s02,bim= b.s13;\n";
ss<<dtype<<"2 cre = c.s02,cim =c.s13;\n";
ss<<dtype<<"2 rre = are*bre+cre; rre = -aim*bim+rre;\n";
ss<<dtype<<"2 rim = are*bim+cim; rim = bre*aim+rim;\n";
ss<<"rre = -aim*bim + rre;\n"<<endl;
ss<<"rim = bre*aim + rim;\n";
ss<<dtype<<"4 res; res.s02 = rre; res.s13 = rim;\n";
ss<<"return res;\n}";*/
return ss.str();
}
template <typename T>
static void tuneGemmComplex(cl_context ctx, cl_device_id dvc,RaijinGemmOptKernel *optparams,unsigned int N,double *gflopbest){
cout<<"Inside tuneGemmCache"<<endl;
cout<<"Tuning "<<T::gemmName()<<endl;
cl_int errcode;
cl_command_queue q = clCreateCommandQueue(ctx,dvc,0,&errcode);
if(errcode!=CL_SUCCESS) cout<<"Error creating queue"<<endl;
typedef typename T::ctype ctype;
size_t size = sizeof(ctype)*N*N;
int htiles[] = {2,4,4,8,4};
int wtiles[] = {4,2,4,4,8};
int ktiles[] = {1,2,4,8,16,32};
int simdwidths[] = {1,2,4,8};
int lsizesX[] = {4,8,8,4,16,16};
int lsizesY[] = {8,4,8,16,4,16};
int unrolls[] = {1,2,4,8};
bool storeA[] = {true, false};
bool storeB[] = {true, false};
bool useImageA[] = {true,false};
bool useImageB[] = {true,false};
bool initialized = false;
//double tbest = 0.0;
string prgmbest;
*gflopbest = 0.0;
cl_device_type dvctype;
cl_ulong lmemSize;
cl_device_local_mem_type ltype;
clGetDeviceInfo(dvc,CL_DEVICE_TYPE,sizeof(dvctype),&dvctype,NULL);
clGetDeviceInfo(dvc,CL_DEVICE_LOCAL_MEM_SIZE,sizeof(lmemSize),&lmemSize,NULL);
clGetDeviceInfo(dvc,CL_DEVICE_LOCAL_MEM_TYPE,sizeof(ltype),<ype,NULL);
RaijinTranspose transObj(dvc,ctx);
RaijinCopy copyObj(ctx,dvc);
RaijinScale scaleObj(ctx,dvc);
cl_uint vecWidth;
if(T::isDouble()) clGetDeviceInfo(dvc,CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE,sizeof(cl_uint),&vecWidth,NULL);
else clGetDeviceInfo(dvc,CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT,sizeof(cl_uint),&vecWidth,NULL);
bool imgA[] = {true,false};
bool imgB[] = {true,false};
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
for (int simdidx = 0; simdidx < 2;simdidx++) {
for (int ktileidx = 0; ktileidx < 5; ktileidx++) {
for(int sa = 0 ; sa<1; sa++){
for(int sb = 0; sb <1 ; sb++){
for(int imgAidx=0;imgAidx<2;imgAidx++){
for(int imgBidx=0;imgBidx<2;imgBidx++){
//if(T::isDouble() && simdidx>0) continue;
int ktile = ktiles[ktileidx];
const int unr = ktile;
//cout<<s<<" "<<bfidx<<" "<<splits[s]<<" "<<bfirsts[bfidx]<<endl;
bool isAggregate = false;
bool storec = false;
int htile = htiles[i];
int wtile = wtiles[i];
bool useImageA = imgA[imgAidx];
bool useImageB = imgB[imgBidx];
bool transA = true;
bool transB = false;
if(dvctype!=CL_DEVICE_TYPE_GPU && (useImageA || useImageB)) continue;
if(ltype!=CL_LOCAL && (storeA[sa] || storeB[sb])) continue;
string body;
const int simd = simdwidths[simdidx];
//if(dvctype==CL_DEVICE_TYPE_CPU && simd!=vecWidth) continue;
if(dvctype==CL_DEVICE_TYPE_GPU){
if(T::isDouble() && simd>2) continue;
else if(!(T::isDouble()) && simd>4) continue;
}
int regest = 2*(htile * wtile + htile * simd + wtile * simd);
if(regest>128) continue;
string dtype = T::name();
int lx, ly;
lx = lsizesX[j];
ly = lsizesY[j];
unsigned int nVecRegs = htile*wtile;
nVecRegs += (htile>wtile) ? (wtile/simd) : (htile/simd);
//if(dvctype==CL_DEVICE_TYPE_CPU && nVecRegs>16) continue;
bool kernSuc = genCkernelTNOff(lx,ly,htile, wtile, ktile,dtype, simd, storeA[sa],storeB[sb],lmemSize/(sizeof(ctype))
,1,body,useImageA,useImageB);
/*unsigned int nVecRegs = htile*wtile/simd;
nVecRegs += (htile>wtile) ? (wtile/simd) : (htile/simd);
if(dvctype==CL_DEVICE_TYPE_CPU && nVecRegs>16) continue;
bool kernSuc = genKernelTNCons(lx,ly,htile, wtile, ktile,dtype, simd, storeA[sa],storeB[sb],lmemSize/(sizeof(realtype))
,1,body,useImageA,useImageB);*/
if(!kernSuc) continue;
//cout<<body<<endl;
stringstream kernelstream;
stringstream namestream;
namestream << T::gemmName() << i << "_" << j << "_" << simdidx << "_" << ktileidx << "_" << sa << "_" <<sb<<"_"<<imgAidx<<"_"<<imgBidx;
string kname = namestream.str();
kernelstream<<genCmulFuncs(T::isDouble())<<endl;
if(useImageA || useImageB){
kernelstream<<"__constant sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST;"<<endl;
kernelstream<<"float4 myread_imagef(__read_only image2d_t img,int2 pos){ return read_imagef(img,sampler,pos);\n}"<<endl;
}
kernelstream<<"__kernel ";
if(isAggregate){
kernelstream<<"__attribute__((reqd_work_group_size(1,1,1))) "<<endl;
}else{
kernelstream<<"__attribute__((reqd_work_group_size("<<ly<<","<<lx<<",1))) "<<endl;
}
kernelstream <<"void " << kname;
kernelstream << body;
string kernelsrc = kernelstream.str();
string klogname = kname +".cl";
ofstream klog(klogname.c_str());
klog<<kernelsrc<<endl;
klog.close();
const size_t len = kernelsrc.length();
cl_int errcode1, errcode2;
RTimer rt1, rt2, rt3;
rt1.start();
const char *srcbuf = kernelsrc.c_str();
cl_program prg = clCreateProgramWithSource(ctx, 1, &srcbuf, (const size_t*) &len, &errcode1);
cl_int bldcode = clBuildProgram(prg, 1, &dvc, "", NULL, NULL);
cl_kernel krnl = clCreateKernel(prg, kname.c_str(), &errcode2);
rt1.stop();
cout<<"Compile time "<<rt1.getDiff()<<endl;
if (errcode1 != CL_SUCCESS || errcode2 != CL_SUCCESS || bldcode != CL_SUCCESS) {
/*cl::Program prgmcpp(prg);
const cl::Device dvccpp(dvc);
string buildlog = prgmcpp.getBuildInfo<CL_PROGRAM_BUILD_LOG>(dvccpp);
cout<<buildlog<<endl;*/
size_t retbytes;
cout << "Error creating program from source " << errcode1 << " " << errcode2 << " " << bldcode << endl;
clGetProgramBuildInfo(prg, dvc, CL_PROGRAM_BUILD_LOG, 0, NULL, &retbytes);
char *buildlog = new char[retbytes+1];
clGetProgramBuildInfo(prg,dvc,CL_PROGRAM_BUILD_LOG,retbytes,buildlog,NULL);
cout << "Buildlog " << retbytes<<" "<<buildlog << endl;
//cout << "Error creating program from source " << errcode1 << " " << errcode2 << " " << bldcode << endl;
cout << kernelsrc << endl;
exit(-1);
continue;
} else {
//string fname = kname+".cl";
//ofstream of(fname.c_str());
//of<<kernelsrc<<endl;
//of.close();
//cout<<"Time taken to compile "<<rt1.getDiff()<<endl;
RaijinGemmOptKernel candidate;
candidate.transA = transA;
candidate.transB = transB;
candidate.simdwidth = simd;
candidate.htile = htile;
candidate.wtile = wtile;
candidate.ktile = ktile;
candidate.lsizex = lx;
candidate.lsizey = ly;
candidate.kernel = kernelsrc;
candidate.kname = kname;
candidate.imageA = useImageA;
candidate.imageB = useImageB;
double gflops;
size_t tuneSize = 2048;
gflops = testGemmComplex<T>(tuneSize, dvc, ctx, krnl,candidate,&transObj,©Obj,&scaleObj,true);
clReleaseKernel(krnl);
clReleaseProgram(prg);
double bwidth = (htile+wtile)*gflops*sizeof(ctype)/(8*htile*wtile);
cout<<"htile "<<htile<<" wtile "<<wtile<<" ktile "<<(ktile);
cout<<" lx "<<lx<<" ly "<<ly<<" simd "<<simd<<" storeA? "<<storeA[sa]<<" storeB? "<<storeB[sb];
cout<<" ImageA? "<<useImageA<<" ImageB? "<<useImageB<<endl;
if (!initialized || (gflops > (*gflopbest)) && (gflops < 2500)) {
*optparams = candidate;
*gflopbest = gflops;
initialized = true;
}
cout << "Gflops " << gflops << " Bwidth "<< bwidth<<" Best So Far "<<(*gflopbest)<<" "<<kname<<endl;
}
}
}
}
}
}
}
}
}
clReleaseCommandQueue(q);
}
template <typename T>
bool tuneGemmComplex(cl_platform_id platform, cl_device_id dvc,RaijinGemmOptKernel *optkernel,unsigned int N=1024){
cout<<"Inside tuneGemm"<<endl;
cl_context_properties conprop[3];
conprop[0] = CL_CONTEXT_PLATFORM;
conprop[1] = (cl_context_properties)platform;
conprop[2] = (cl_context_properties)0;
cl_int errcode;
cl_context ctx = clCreateContext(conprop,1,&dvc,NULL,NULL,&errcode);
if(errcode==CL_SUCCESS){
double gflopbest=0.0;
tuneGemmComplex<T>(ctx,dvc,optkernel,N,&gflopbest);
}else{
cout<<"Could not successfully create context for this device"<<endl;
return false;
}
clReleaseContext(ctx);
return true;
}
void RaijinCL::raijinTuneZgemm(cl_device_id dvc){
RaijinGemmOptKernel zgemmParams;
cl_platform_id platform;
clGetDeviceInfo(dvc,CL_DEVICE_PLATFORM,sizeof(cl_platform_id),&platform,NULL);
string zpath = raijinGetProfileFileName(dvc,"zgemm");
ofstream zfile(zpath.c_str());
tuneGemmComplex<GemmCdouble>(platform,dvc,&zgemmParams);
zfile<<zgemmParams<<endl;
zfile.close();
}
void RaijinCL::raijinTuneCgemm(cl_device_id dvc){
RaijinGemmOptKernel cgemmParams;
cl_platform_id platform;
clGetDeviceInfo(dvc,CL_DEVICE_PLATFORM,sizeof(cl_platform_id),&platform,NULL);
string cpath = raijinGetProfileFileName(dvc,"cgemm");
ofstream cfile(cpath.c_str());
tuneGemmComplex<GemmCsingle>(platform,dvc,&cgemmParams);
cfile<<cgemmParams<<endl;
cfile.close();
}
| 44.319343
| 193
| 0.447427
|
codedivine
|
459c85c986e46de885a11a2a0a52ad2704918e44
| 1,840
|
cpp
|
C++
|
hyperplatform_log_parser/hyperplatform_log_parser.cpp
|
tandasat/hyperplatform_log_parser
|
7a7eba3c8c582fa43ba2a47372a363080796d2d4
|
[
"MIT"
] | 17
|
2016-04-08T10:59:03.000Z
|
2021-12-11T07:09:31.000Z
|
hyperplatform_log_parser/hyperplatform_log_parser.cpp
|
c3358/hyperplatform_log_parser
|
7a7eba3c8c582fa43ba2a47372a363080796d2d4
|
[
"MIT"
] | null | null | null |
hyperplatform_log_parser/hyperplatform_log_parser.cpp
|
c3358/hyperplatform_log_parser
|
7a7eba3c8c582fa43ba2a47372a363080796d2d4
|
[
"MIT"
] | 11
|
2016-07-02T15:23:57.000Z
|
2021-01-08T19:27:36.000Z
|
// Copyright (c) 2015-2016, tandasat. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
//
// This module implements an entry point of the driver.
//
#include "stdafx.h"
#include "log_parser.h"
#include "utility.h"
////////////////////////////////////////////////////////////////////////////////
//
// macro utilities
//
////////////////////////////////////////////////////////////////////////////////
//
// constants and macros
//
////////////////////////////////////////////////////////////////////////////////
//
// types
//
////////////////////////////////////////////////////////////////////////////////
//
// prototypes
//
bool AppMain(_In_ const std::vector<std::basic_string<TCHAR>> &args);
////////////////////////////////////////////////////////////////////////////////
//
// variables
//
////////////////////////////////////////////////////////////////////////////////
//
// implementations
//
//
int _tmain(int argc, TCHAR *argv[]) {
auto exit_code = EXIT_FAILURE;
try {
std::vector<std::basic_string<TCHAR>> args;
for (auto i = 0; i < argc; ++i) {
args.push_back(argv[i]);
}
if (AppMain(args)) {
exit_code = EXIT_SUCCESS;
}
} catch (std::exception &e) {
std::cout << e.what() << std::endl;
} catch (...) {
std::cout << "Unhandled exception occurred." << std::endl;
}
return exit_code;
}
// A main application loop
_Use_decl_annotations_ bool AppMain(
const std::vector<std::basic_string<TCHAR>> &args) {
if (args.size() == 1) {
std::cout << "Usage:\n"
<< " >this.exe <log_file_path>\n" << std::endl;
return false;
}
LogParser log_parser(args.at(1));
for (;;) {
std::this_thread::sleep_for(std::chrono::seconds(1));
log_parser.ParseFile();
}
}
| 23.291139
| 80
| 0.448913
|
tandasat
|
459d3fd808aba1dfd91a27a8763c89bd4d83aae4
| 61
|
hpp
|
C++
|
addons/interrogation/functions/script_component.hpp
|
kellerkompanie/kellerkompanie-mods
|
f15704710f77ba6c018c486d95cac4f7749d33b8
|
[
"MIT"
] | 6
|
2018-05-05T22:28:57.000Z
|
2019-07-06T08:46:51.000Z
|
addons/interrogation/functions/script_component.hpp
|
Schwaggot/kellerkompanie-mods
|
7a389e49e3675866dbde1b317a44892926976e9d
|
[
"MIT"
] | 107
|
2018-04-11T19:42:27.000Z
|
2019-09-13T19:05:31.000Z
|
addons/interrogation/functions/script_component.hpp
|
kellerkompanie/kellerkompanie-mods
|
f15704710f77ba6c018c486d95cac4f7749d33b8
|
[
"MIT"
] | 3
|
2018-10-03T11:54:46.000Z
|
2019-02-28T13:30:16.000Z
|
#include "\x\keko\addons\interrogation\script_component.hpp"
| 30.5
| 60
| 0.819672
|
kellerkompanie
|
45a0d5b4a59c688e301f8a5f78f412956f5d1494
| 1,603
|
cpp
|
C++
|
SystemResource/Source/Compression/ZLIB/ZLIBCompressionLevel.cpp
|
BitPaw/BitFireEngine
|
2c02a4eae19276bf60ac925e4393966cec605112
|
[
"MIT"
] | 5
|
2021-10-19T18:30:43.000Z
|
2022-03-19T22:02:02.000Z
|
SystemResource/Source/Compression/ZLIB/ZLIBCompressionLevel.cpp
|
BitPaw/BitFireEngine
|
2c02a4eae19276bf60ac925e4393966cec605112
|
[
"MIT"
] | 12
|
2022-03-09T13:40:21.000Z
|
2022-03-31T12:47:48.000Z
|
SystemResource/Source/Compression/ZLIB/ZLIBCompressionLevel.cpp
|
BitPaw/BitFireEngine
|
2c02a4eae19276bf60ac925e4393966cec605112
|
[
"MIT"
] | null | null | null |
#include "ZLIBCompressionLevel.h"
BF::ZLIBCompressionLevel BF::ConvertCompressionLevel(unsigned char compressionLevel)
{
switch (compressionLevel)
{
case 0u:
return BF::ZLIBCompressionLevel::Fastest;
case 1u:
return BF::ZLIBCompressionLevel::Fast;
case 2u:
return BF::ZLIBCompressionLevel::Default;
case 3u:
return BF::ZLIBCompressionLevel::Slowest;
default:
return BF::ZLIBCompressionLevel::InvalidCompressionLevel;
}
}
unsigned char BF::ConvertCompressionLevel(ZLIBCompressionLevel compressionLevel)
{
switch (compressionLevel)
{
default:
case BF::ZLIBCompressionLevel::InvalidCompressionLevel:
return -1;
case BF::ZLIBCompressionLevel::Default:
return 2u;
case BF::ZLIBCompressionLevel::Slowest:
return 3u;
case BF::ZLIBCompressionLevel::Fast:
return 1u;
case BF::ZLIBCompressionLevel::Fastest:
return 0u;
}
}
const char* BF::CompressionLevelToString(ZLIBCompressionLevel compressionLevel)
{
switch (compressionLevel)
{
default:
case BF::ZLIBCompressionLevel::InvalidCompressionLevel:
return "Invalid";
case BF::ZLIBCompressionLevel::Default:
return "Default";
case BF::ZLIBCompressionLevel::Slowest:
return "Slowest";
case BF::ZLIBCompressionLevel::Fast:
return "Fast";
case BF::ZLIBCompressionLevel::Fastest:
return "Fastest";
}
}
| 23.925373
| 84
| 0.625702
|
BitPaw
|
45a0dc71972c48dd43d07afd55f00e8ee349c216
| 15,185
|
cpp
|
C++
|
src/Conversion.cpp
|
markvilar/Sennet-ZED
|
2b761ed4f3fefa93f5e37e3b5f283eb0934146d3
|
[
"Apache-2.0"
] | null | null | null |
src/Conversion.cpp
|
markvilar/Sennet-ZED
|
2b761ed4f3fefa93f5e37e3b5f283eb0934146d3
|
[
"Apache-2.0"
] | null | null | null |
src/Conversion.cpp
|
markvilar/Sennet-ZED
|
2b761ed4f3fefa93f5e37e3b5f283eb0934146d3
|
[
"Apache-2.0"
] | null | null | null |
#include "Sennet-ZED/Conversion.hpp"
sl::VIEW SennetToStereolabs(const Sennet::ZED::View& view)
{
switch (view)
{
case Sennet::ZED::View::Left:
return sl::VIEW::LEFT;
case Sennet::ZED::View::Right:
return sl::VIEW::RIGHT;
case Sennet::ZED::View::LeftGray:
return sl::VIEW::LEFT_GRAY;
case Sennet::ZED::View::RightGray:
return sl::VIEW::RIGHT_GRAY;
case Sennet::ZED::View::LeftUnrectified:
return sl::VIEW::LEFT_UNRECTIFIED;
case Sennet::ZED::View::RightUnrectified:
return sl::VIEW::RIGHT_UNRECTIFIED;
case Sennet::ZED::View::LeftUnrectifiedGray:
return sl::VIEW::LEFT_UNRECTIFIED_GRAY;
case Sennet::ZED::View::RightUnrectifiedGray:
return sl::VIEW::RIGHT_UNRECTIFIED_GRAY;
case Sennet::ZED::View::SideBySide:
return sl::VIEW::SIDE_BY_SIDE;
default:
return sl::VIEW::LAST;
}
}
sl::RESOLUTION SennetToStereolabs(const Sennet::ZED::Resolution& resolution)
{
switch (resolution)
{
case Sennet::ZED::Resolution::HD2K:
return sl::RESOLUTION::HD2K;
case Sennet::ZED::Resolution::HD1080:
return sl::RESOLUTION::HD1080;
case Sennet::ZED::Resolution::HD720:
return sl::RESOLUTION::HD720;
case Sennet::ZED::Resolution::VGA:
return sl::RESOLUTION::VGA;
default:
return sl::RESOLUTION::LAST;
}
}
sl::VIDEO_SETTINGS SennetToStereolabs(
const Sennet::ZED::VideoSettings& videoSettings)
{
switch (videoSettings)
{
case Sennet::ZED::VideoSettings::Brightness:
return sl::VIDEO_SETTINGS::BRIGHTNESS;
case Sennet::ZED::VideoSettings::Contrast:
return sl::VIDEO_SETTINGS::CONTRAST;
case Sennet::ZED::VideoSettings::Hue:
return sl::VIDEO_SETTINGS::HUE;
case Sennet::ZED::VideoSettings::Saturation:
return sl::VIDEO_SETTINGS::SATURATION;
case Sennet::ZED::VideoSettings::Sharpness:
return sl::VIDEO_SETTINGS::SHARPNESS;
case Sennet::ZED::VideoSettings::Gain:
return sl::VIDEO_SETTINGS::GAIN;
case Sennet::ZED::VideoSettings::Exposure:
return sl::VIDEO_SETTINGS::EXPOSURE;
case Sennet::ZED::VideoSettings::AECAGC:
return sl::VIDEO_SETTINGS::AEC_AGC;
case Sennet::ZED::VideoSettings::WhitebalanceTemperature:
return sl::VIDEO_SETTINGS::WHITEBALANCE_TEMPERATURE;
case Sennet::ZED::VideoSettings::WhitebalanceAuto:
return sl::VIDEO_SETTINGS::WHITEBALANCE_AUTO;
case Sennet::ZED::VideoSettings::LEDStatus:
return sl::VIDEO_SETTINGS::LED_STATUS;
default:
return sl::VIDEO_SETTINGS::LAST;
}
}
sl::DEPTH_MODE SennetToStereolabs(const Sennet::ZED::DepthMode& depthMode)
{
switch (depthMode)
{
case Sennet::ZED::DepthMode::Performance:
return sl::DEPTH_MODE::PERFORMANCE;
case Sennet::ZED::DepthMode::Quality:
return sl::DEPTH_MODE::QUALITY;
case Sennet::ZED::DepthMode::Ultra:
return sl::DEPTH_MODE::ULTRA;
default:
return sl::DEPTH_MODE::LAST;
}
}
sl::FLIP_MODE SennetToStereolabs(const Sennet::ZED::FlipMode& flipMode)
{
switch (flipMode)
{
case Sennet::ZED::FlipMode::Off:
return sl::FLIP_MODE::OFF;
case Sennet::ZED::FlipMode::On:
return sl::FLIP_MODE::ON;
case Sennet::ZED::FlipMode::Auto:
return sl::FLIP_MODE::AUTO;
default:
return sl::FLIP_MODE::OFF;
}
}
sl::UNIT SennetToStereolabs(const Sennet::ZED::Unit& unit)
{
switch (unit)
{
case Sennet::ZED::Unit::Millimeter:
return sl::UNIT::MILLIMETER;
case Sennet::ZED::Unit::Centimeter:
return sl::UNIT::CENTIMETER;
case Sennet::ZED::Unit::Meter:
return sl::UNIT::METER;
case Sennet::ZED::Unit::Inch:
return sl::UNIT::INCH;
case Sennet::ZED::Unit::Foot:
return sl::UNIT::FOOT;
default:
return sl::UNIT::LAST;
}
}
sl::SVO_COMPRESSION_MODE SennetToStereolabs(
const Sennet::ZED::SVOCompressionMode& compressionMode)
{
switch (compressionMode)
{
case Sennet::ZED::SVOCompressionMode::Lossless:
return sl::SVO_COMPRESSION_MODE::LOSSLESS;
case Sennet::ZED::SVOCompressionMode::H264:
return sl::SVO_COMPRESSION_MODE::H264;
case Sennet::ZED::SVOCompressionMode::H265:
return sl::SVO_COMPRESSION_MODE::H265;
default:
return sl::SVO_COMPRESSION_MODE::LAST;
}
}
sl::SENSING_MODE SennetToStereolabs(const Sennet::ZED::SensingMode& sensingMode)
{
switch (sensingMode)
{
case Sennet::ZED::SensingMode::Standard:
return sl::SENSING_MODE::STANDARD;
case Sennet::ZED::SensingMode::Fill:
return sl::SENSING_MODE::FILL;
default:
return sl::SENSING_MODE::LAST;
}
}
sl::REFERENCE_FRAME SennetToStereolabs(
const Sennet::ZED::ReferenceFrame& referenceFrame)
{
switch (referenceFrame)
{
case Sennet::ZED::ReferenceFrame::World:
return sl::REFERENCE_FRAME::WORLD;
case Sennet::ZED::ReferenceFrame::Camera:
return sl::REFERENCE_FRAME::CAMERA;
default:
return sl::REFERENCE_FRAME::LAST;
}
}
sl::COORDINATE_SYSTEM SennetToStereolabs(
const Sennet::ZED::CoordinateSystem& coordinateSystem)
{
switch (coordinateSystem)
{
case Sennet::ZED::CoordinateSystem::Image:
return sl::COORDINATE_SYSTEM::IMAGE;
case Sennet::ZED::CoordinateSystem::LeftHandedYUp:
return sl::COORDINATE_SYSTEM::LEFT_HANDED_Y_UP;
case Sennet::ZED::CoordinateSystem::RightHandedYUp:
return sl::COORDINATE_SYSTEM::RIGHT_HANDED_Y_UP;
case Sennet::ZED::CoordinateSystem::RightHandedZUp:
return sl::COORDINATE_SYSTEM::RIGHT_HANDED_Z_UP;
case Sennet::ZED::CoordinateSystem::LeftHandedZUp:
return sl::COORDINATE_SYSTEM::LEFT_HANDED_Z_UP;
case Sennet::ZED::CoordinateSystem::RightHandedZUpXForward:
return sl::COORDINATE_SYSTEM::RIGHT_HANDED_Z_UP_X_FWD;
default:
return sl::COORDINATE_SYSTEM::LAST;
}
}
sl::InitParameters SennetToStereolabs(
const Sennet::ZED::InitParameters& initParameters)
{
sl::InitParameters params;
params.depth_mode = SennetToStereolabs(
initParameters.depthMode);
params.coordinate_units = SennetToStereolabs(
initParameters.coordinateUnits);
params.coordinate_system =
SennetToStereolabs(initParameters.coordinateSystem);
params.depth_stabilization =
(int)initParameters.enableDepthStabilization;
params.depth_minimum_distance = initParameters.minDepth;
params.depth_maximum_distance = initParameters.maxDepth;
params.enable_right_side_measure = initParameters.enableRightSideDepth;
params.camera_resolution = SennetToStereolabs(
initParameters.resolution);
params.camera_image_flip = SennetToStereolabs(initParameters.flipMode);
params.camera_fps = initParameters.cameraFPS;
params.enable_image_enhancement = initParameters.enableImageEnhancement;
params.camera_disable_self_calib =
initParameters.disableSelfCalibration;
params.sdk_verbose = initParameters.enableVerboseSDK;
params.sensors_required = initParameters.requireSensors;
return params;
}
sl::RecordingParameters SennetToStereolabs(
const Sennet::ZED::RecordingParameters& recordingParameters)
{
sl::RecordingParameters params;
params.video_filename =
sl::String(recordingParameters.filename.c_str());
params.compression_mode =
SennetToStereolabs(recordingParameters.compressionMode);
return params;
}
sl::RuntimeParameters SennetToStereolabs(
const Sennet::ZED::RuntimeParameters& runtimeParameters)
{
sl::RuntimeParameters params;
params.sensing_mode = SennetToStereolabs(runtimeParameters.sensingMode);
params.measure3D_reference_frame =
SennetToStereolabs(runtimeParameters.referenceFrame);
params.enable_depth = runtimeParameters.enableDepth;
params.confidence_threshold = runtimeParameters.confidenceThreshold;
params.texture_confidence_threshold
= runtimeParameters.textureConfidenceThreshold;
return params;
}
///////////////////////////////////////////////////////////////////////////////
// Sennet conversion functions ////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
Sennet::ZED::View StereolabsToSennet(const sl::VIEW& view)
{
switch (view)
{
case sl::VIEW::LEFT:
return Sennet::ZED::View::Left;
case sl::VIEW::RIGHT:
return Sennet::ZED::View::Right;
case sl::VIEW::LEFT_GRAY:
return Sennet::ZED::View::LeftGray;
case sl::VIEW::RIGHT_GRAY:
return Sennet::ZED::View::RightGray;
case sl::VIEW::LEFT_UNRECTIFIED:
return Sennet::ZED::View::LeftUnrectified;
case sl::VIEW::RIGHT_UNRECTIFIED:
return Sennet::ZED::View::RightUnrectified;
case sl::VIEW::LEFT_UNRECTIFIED_GRAY:
return Sennet::ZED::View::LeftUnrectifiedGray;
case sl::VIEW::RIGHT_UNRECTIFIED_GRAY:
return Sennet::ZED::View::RightUnrectifiedGray;
case sl::VIEW::SIDE_BY_SIDE:
return Sennet::ZED::View::SideBySide;
default:
return Sennet::ZED::View::None;
}
}
Sennet::ZED::Resolution StereolabsToSennet(const sl::RESOLUTION& resolution)
{
switch (resolution)
{
case sl::RESOLUTION::HD2K:
return Sennet::ZED::Resolution::HD2K;
case sl::RESOLUTION::HD1080:
return Sennet::ZED::Resolution::HD1080;
case sl::RESOLUTION::HD720:
return Sennet::ZED::Resolution::HD720;
case sl::RESOLUTION::VGA:
return Sennet::ZED::Resolution::VGA;
default:
return Sennet::ZED::Resolution::None;
}
}
Sennet::ZED::VideoSettings StereolabsToSennet(
const sl::VIDEO_SETTINGS& videoSettings)
{
switch (videoSettings)
{
case sl::VIDEO_SETTINGS::BRIGHTNESS:
return Sennet::ZED::VideoSettings::Brightness;
case sl::VIDEO_SETTINGS::CONTRAST:
return Sennet::ZED::VideoSettings::Contrast;
case sl::VIDEO_SETTINGS::HUE:
return Sennet::ZED::VideoSettings::Hue;
case sl::VIDEO_SETTINGS::SATURATION:
return Sennet::ZED::VideoSettings::Saturation;
case sl::VIDEO_SETTINGS::SHARPNESS:
return Sennet::ZED::VideoSettings::Sharpness;
case sl::VIDEO_SETTINGS::GAIN:
return Sennet::ZED::VideoSettings::Gain;
case sl::VIDEO_SETTINGS::EXPOSURE:
return Sennet::ZED::VideoSettings::Exposure;
case sl::VIDEO_SETTINGS::AEC_AGC:
return Sennet::ZED::VideoSettings::AECAGC;
case sl::VIDEO_SETTINGS::WHITEBALANCE_TEMPERATURE:
return Sennet::ZED::VideoSettings::WhitebalanceTemperature;
case sl::VIDEO_SETTINGS::WHITEBALANCE_AUTO:
return Sennet::ZED::VideoSettings::WhitebalanceAuto;
case sl::VIDEO_SETTINGS::LED_STATUS:
return Sennet::ZED::VideoSettings::LEDStatus;
default:
return Sennet::ZED::VideoSettings::None;
}
}
Sennet::ZED::DepthMode StereolabsToSennet(const sl::DEPTH_MODE& depthMode)
{
switch (depthMode)
{
case sl::DEPTH_MODE::PERFORMANCE:
return Sennet::ZED::DepthMode::Performance;
case sl::DEPTH_MODE::QUALITY:
return Sennet::ZED::DepthMode::Quality;
case sl::DEPTH_MODE::ULTRA:
return Sennet::ZED::DepthMode::Ultra;
default:
return Sennet::ZED::DepthMode::None;
}
}
Sennet::ZED::FlipMode StereolabsToSennet(const int flipMode)
{
switch (flipMode)
{
case sl::FLIP_MODE::OFF:
return Sennet::ZED::FlipMode::Off;
case sl::FLIP_MODE::ON:
return Sennet::ZED::FlipMode::On;
case sl::FLIP_MODE::AUTO:
return Sennet::ZED::FlipMode::Auto;
default:
return Sennet::ZED::FlipMode::None;
}
}
Sennet::ZED::Unit StereolabsToSennet(const sl::UNIT& unit)
{
switch (unit)
{
case sl::UNIT::MILLIMETER:
return Sennet::ZED::Unit::Millimeter;
case sl::UNIT::CENTIMETER:
return Sennet::ZED::Unit::Centimeter;
case sl::UNIT::METER:
return Sennet::ZED::Unit::Meter;
case sl::UNIT::INCH:
return Sennet::ZED::Unit::Inch;
case sl::UNIT::FOOT:
return Sennet::ZED::Unit::Foot;
default:
return Sennet::ZED::Unit::None;
}
}
Sennet::ZED::SVOCompressionMode StereolabsToSennet(
const sl::SVO_COMPRESSION_MODE& compressionMode)
{
switch (compressionMode)
{
case sl::SVO_COMPRESSION_MODE::LOSSLESS:
return Sennet::ZED::SVOCompressionMode::Lossless;
case sl::SVO_COMPRESSION_MODE::H264:
return Sennet::ZED::SVOCompressionMode::H264;
case sl::SVO_COMPRESSION_MODE::H265:
return Sennet::ZED::SVOCompressionMode::H265;
default:
return Sennet::ZED::SVOCompressionMode::None;
}
}
Sennet::ZED::SensingMode StereolabsToSennet(const sl::SENSING_MODE& sensingMode)
{
switch (sensingMode)
{
case sl::SENSING_MODE::STANDARD:
return Sennet::ZED::SensingMode::Standard;
case sl::SENSING_MODE::FILL:
return Sennet::ZED::SensingMode::Fill;
default:
return Sennet::ZED::SensingMode::None;
}
}
Sennet::ZED::ReferenceFrame StereolabsToSennet(
const sl::REFERENCE_FRAME& referenceFrame)
{
switch (referenceFrame)
{
case sl::REFERENCE_FRAME::WORLD:
return Sennet::ZED::ReferenceFrame::World;
case sl::REFERENCE_FRAME::CAMERA:
return Sennet::ZED::ReferenceFrame::Camera;
default:
return Sennet::ZED::ReferenceFrame::None;
}
}
Sennet::ZED::CoordinateSystem StereolabsToSennet(
const sl::COORDINATE_SYSTEM& coordinateSystem)
{
typedef Sennet::ZED::CoordinateSystem CoordinateSystem;
switch (coordinateSystem)
{
case sl::COORDINATE_SYSTEM::IMAGE:
return CoordinateSystem::Image;
case sl::COORDINATE_SYSTEM::LEFT_HANDED_Y_UP:
return CoordinateSystem::LeftHandedYUp;
case sl::COORDINATE_SYSTEM::RIGHT_HANDED_Y_UP:
return CoordinateSystem::RightHandedYUp;
case sl::COORDINATE_SYSTEM::RIGHT_HANDED_Z_UP:
return CoordinateSystem::RightHandedZUp;
case sl::COORDINATE_SYSTEM::LEFT_HANDED_Z_UP:
return CoordinateSystem::LeftHandedZUp;
case sl::COORDINATE_SYSTEM::RIGHT_HANDED_Z_UP_X_FWD:
return CoordinateSystem::RightHandedZUpXForward;
default:
return CoordinateSystem::None;
}
}
Sennet::ZED::InitParameters StereolabsToSennet(
const sl::InitParameters& initParameters)
{
Sennet::ZED::InitParameters params;
params.depthMode = StereolabsToSennet(initParameters.depth_mode);
params.coordinateUnits = StereolabsToSennet(
initParameters.coordinate_units);
params.coordinateSystem = StereolabsToSennet(
initParameters.coordinate_system);
params.enableDepthStabilization =
(bool)initParameters.depth_stabilization;
params.minDepth = initParameters.depth_minimum_distance;
params.maxDepth = initParameters.depth_maximum_distance;
params.enableRightSideDepth = initParameters.enable_right_side_measure;
params.resolution = StereolabsToSennet(initParameters.camera_resolution);
params.flipMode = StereolabsToSennet(initParameters.camera_image_flip);
params.cameraFPS = initParameters.camera_fps;
params.enableImageEnhancement = initParameters.enable_image_enhancement;
params.disableSelfCalibration = initParameters.camera_disable_self_calib;
params.enableVerboseSDK = initParameters.sdk_verbose;
params.requireSensors = initParameters.sensors_required;
return params;
}
Sennet::ZED::RecordingParameters StereolabsToSennet(
const sl::RecordingParameters& recordingParameters)
{
Sennet::ZED::RecordingParameters params;
params.filename = std::string(recordingParameters.video_filename.get());
params.compressionMode =
StereolabsToSennet(recordingParameters.compression_mode);
return params;
}
Sennet::ZED::RuntimeParameters StereolabsToSennet(
const sl::RuntimeParameters& runtimeParameters)
{
Sennet::ZED::RuntimeParameters params;
params.sensingMode = StereolabsToSennet(runtimeParameters.sensing_mode);
params.referenceFrame =
StereolabsToSennet(runtimeParameters.measure3D_reference_frame);
params.enableDepth = runtimeParameters.enable_depth;
params.confidenceThreshold = runtimeParameters.confidence_threshold;
params.textureConfidenceThreshold =
runtimeParameters.texture_confidence_threshold;
return params;
}
| 30.989796
| 80
| 0.753309
|
markvilar
|
45a55d2ac83ad14f7d75e5bef293e0e05bf1b121
| 19
|
cpp
|
C++
|
src/Type.cpp
|
phiwen96/ph_image
|
282bdd835d721a561c4f3afcbb76af5f9bda87ba
|
[
"Apache-2.0"
] | 1
|
2021-09-05T08:38:39.000Z
|
2021-09-05T08:38:39.000Z
|
src/Type.cpp
|
phiwen96/ph_image
|
282bdd835d721a561c4f3afcbb76af5f9bda87ba
|
[
"Apache-2.0"
] | null | null | null |
src/Type.cpp
|
phiwen96/ph_image
|
282bdd835d721a561c4f3afcbb76af5f9bda87ba
|
[
"Apache-2.0"
] | 2
|
2021-12-04T14:39:52.000Z
|
2022-03-04T21:12:02.000Z
|
#include "Type.hpp"
| 19
| 19
| 0.736842
|
phiwen96
|
45aa1cc56e96bcf62894efe1c61d5d3ed75c0841
| 238
|
cpp
|
C++
|
Course Experiment/C Language Course Course Exp/Homework/No.7 Homework/5.空格处理.cpp
|
XJDKC/University-Code-Archive
|
2dd9c6edb2164540dc50db1bb94940fe53c6eba0
|
[
"MIT"
] | 4
|
2019-04-01T17:33:38.000Z
|
2022-01-08T04:07:52.000Z
|
Course Experiment/C Language Course Course Exp/Homework/No.7 Homework/5.空格处理.cpp
|
XJDKC/University-Code-Archive
|
2dd9c6edb2164540dc50db1bb94940fe53c6eba0
|
[
"MIT"
] | null | null | null |
Course Experiment/C Language Course Course Exp/Homework/No.7 Homework/5.空格处理.cpp
|
XJDKC/University-Code-Archive
|
2dd9c6edb2164540dc50db1bb94940fe53c6eba0
|
[
"MIT"
] | 1
|
2021-01-06T11:04:31.000Z
|
2021-01-06T11:04:31.000Z
|
#include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
getchar();
while (n--)
{
char a='0',b;
while ((b=getchar())!='\n')
{
if (a!='0'&&a==' '&&b==' ') continue;
a=b;
printf("%c",a);
}
printf("\n");
}
return 0;
}
| 11.9
| 40
| 0.432773
|
XJDKC
|
45b1eec24e6fbb6c79c985d3859420b22890719f
| 2,353
|
cpp
|
C++
|
Projects/Library/Source/Translator/Token.cpp
|
kalineh/KAI
|
43ab555bcbad1886715cd00b2cdac89e12d5cfe5
|
[
"MIT"
] | 1
|
2018-06-16T17:53:43.000Z
|
2018-06-16T17:53:43.000Z
|
Projects/Library/Source/Translator/Token.cpp
|
kalineh/KAI
|
43ab555bcbad1886715cd00b2cdac89e12d5cfe5
|
[
"MIT"
] | null | null | null |
Projects/Library/Source/Translator/Token.cpp
|
kalineh/KAI
|
43ab555bcbad1886715cd00b2cdac89e12d5cfe5
|
[
"MIT"
] | null | null | null |
#include "KAI/KAI.h"
#include "KAI/Translator/Token.h"
#include "KAI/Translator/Lexer.h"
KAI_BEGIN
Token::Token(Type type, const Lexer &lexer, int ln, Slice slice)
: type(type), lexer(&lexer), lineNumber(ln), slice(slice)
{
}
char Token::operator[](int n) const
{
return lexer->input[slice.Start + n];
}
std::string Token::Text() const
{
if (lexer == 0)
return "";
return std::move(lexer->lines[lineNumber].substr(slice.Start, slice.Length()));
}
const char * Token::ToString(Type t)
{
switch (t)
{
case None: return "None";
case Whitespace: return "";
case Semi: return "Semi";
case Int: return "Int";
case Float: return "Float";
case String: return "String";
case Ident: return "Ident";
case Dot: return "Dot";
case If: return "If";
case Else: return "Else";
case For: return "For";
case While: return "While";
case OpenParan: return "OpenParan";
case CloseParan: return "CloseParan";
case Plus: return "Plus";
case Minus: return "Minus";
case Mul: return "Mul";
case Divide: return "Divide";
case Assign: return "Assign";
case Less: return "Less";
case Equiv: return "Equiv";
case Greater: return "Greater";
case LessEquiv: return "LessEquiv";
case GreaterEquiv: return "GreaterEqiv";
case Return: return "Return";
case OpenBrace: return "OpenBrace";
case CloseBrace: return "CloseBrace";
case Not: return "Not";
case NotEquiv: return "NotEquiv";
case And: return "And";
case Or: return "Or";
case Comma: return "Comma";
case OpenSquareBracket: return "OpenSquareBracket";
case CloseSquareBracket: return "CloseSquareBracket";
case Increment: return "++";
case Decrement: return "--";
case Self: return "Self";
case Lookup: return "Lookup";
case Fun: return "Fun";
case Tab: return "Tab";
case NewLine: return "NewLine";
case Comment: return "Comment";
case PlusAssign: return "PlusAssign";
case MinusAssign: return "MinusAssign";
case MulAssign: return "MulAssign";
case DivAssign: return "DivAssign";
case Yield: return "Yield";
}
static char b[100];
_itoa_s(t, b, 100, 10);
return b;
}
std::ostream &operator<<(std::ostream &out, Token const &node)
{
if (node.type == Token::None)
return out;
out << Token::ToString(node.type);
switch (node.type)
{
case Token::Int:
case Token::String:
case Token::Ident:
out << "=" << node.Text();
}
return out;
}
KAI_END
| 23.29703
| 80
| 0.686783
|
kalineh
|
45b23114090b3dc841c5f936a8868d223511c6af
| 521
|
cpp
|
C++
|
Interview-preparation-resources/Usual-C++-interview-question/algorithmic-solutions/possible_combination_of_a_given_string.cpp
|
Ajay-Embed/dataStructure-implementations
|
03638b9bc34a7e1ef5fa450be6c660c223608eff
|
[
"BSD-3-Clause"
] | null | null | null |
Interview-preparation-resources/Usual-C++-interview-question/algorithmic-solutions/possible_combination_of_a_given_string.cpp
|
Ajay-Embed/dataStructure-implementations
|
03638b9bc34a7e1ef5fa450be6c660c223608eff
|
[
"BSD-3-Clause"
] | 4
|
2021-01-23T15:24:39.000Z
|
2021-02-07T05:14:14.000Z
|
Interview-preparation-resources/Usual-C++-interview-question/algorithmic-solutions/possible_combination_of_a_given_string.cpp
|
Ajay-Embed/dataStructure-implementations
|
03638b9bc34a7e1ef5fa450be6c660c223608eff
|
[
"BSD-3-Clause"
] | 2
|
2020-11-17T20:40:39.000Z
|
2021-01-30T17:12:33.000Z
|
//code to find all possible combinations of a given string
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void permut(string s, int i, int n)
{
// Recursion end case
if (i == n)
cout << s << " ";
else
{
for (int j = i; j <= n; j++)
{
swap(s[i], s[j]);
permut(s, i + 1, n);
//backtracking
swap(s[i], s[j]);
}
}
}
int main()
{
string s = "def";
permut(s, 0, s.size() - 1);
return 0;
}
| 15.323529
| 58
| 0.452975
|
Ajay-Embed
|
45b5656d99ec73a5687a9c57e0255033950efb59
| 863
|
hpp
|
C++
|
HexDumper.hpp
|
jancarlsson/snarkfront
|
7f90a4181721f758f114497382aa462185e71dae
|
[
"MIT"
] | 60
|
2015-01-02T12:28:40.000Z
|
2021-04-13T01:40:07.000Z
|
HexDumper.hpp
|
artree222/snarkfront
|
7f90a4181721f758f114497382aa462185e71dae
|
[
"MIT"
] | 8
|
2015-03-05T13:12:39.000Z
|
2018-07-03T07:17:45.000Z
|
HexDumper.hpp
|
artree222/snarkfront
|
7f90a4181721f758f114497382aa462185e71dae
|
[
"MIT"
] | 17
|
2015-01-22T03:10:49.000Z
|
2020-12-27T12:22:17.000Z
|
#ifndef _SNARKFRONT_HEX_DUMPER_HPP_
#define _SNARKFRONT_HEX_DUMPER_HPP_
#include <cstdint>
#include <istream>
#include <ostream>
#include <vector>
#include <cryptl/ASCII_Hex.hpp>
#include <cryptl/DataPusher.hpp>
namespace snarkfront {
////////////////////////////////////////////////////////////////////////////////
// print messages in hexdump format
//
class HexDumper
{
public:
HexDumper(std::ostream&);
void print(const std::vector<std::uint8_t>&);
void print(std::istream&);
private:
// print as text characters
class PrintText
{
public:
PrintText(std::ostream&);
void pushOctet(const std::uint8_t);
private:
std::ostream& m_os;
};
cryptl::DataPusher<cryptl::PrintHex<true>> m_hex;
cryptl::DataPusher<PrintText> m_text;
std::ostream& m_os;
};
} // namespace snarkfront
#endif
| 19.177778
| 80
| 0.618772
|
jancarlsson
|
45b6bb571b5dcd870ad59efbb29989e5fc5dfa59
| 1,278
|
hpp
|
C++
|
Siv3D/include/Siv3D/Base64.hpp
|
Fuyutsubaki/OpenSiv3D
|
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
|
[
"MIT"
] | 1
|
2018-05-23T10:57:32.000Z
|
2018-05-23T10:57:32.000Z
|
Siv3D/include/Siv3D/Base64.hpp
|
Fuyutsubaki/OpenSiv3D
|
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
|
[
"MIT"
] | null | null | null |
Siv3D/include/Siv3D/Base64.hpp
|
Fuyutsubaki/OpenSiv3D
|
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
|
[
"MIT"
] | 1
|
2019-10-06T17:09:26.000Z
|
2019-10-06T17:09:26.000Z
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2018 Ryo Suzuki
// Copyright (c) 2016-2018 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include "Fwd.hpp"
namespace s3d
{
/// <summary>
/// Base64
/// </summary>
/// <remarks>
/// Base64 エンコード/デコードの機能を提供します。
/// </remarks>
namespace Base64
{
/// <summary>
/// データを Base64 エンコードします。
/// </summary>
/// <param name="data">
/// エンコードするデータの先頭ポインタ
/// </param>
/// <param name="size">
/// エンコードするデータのサイズ(バイト)
/// </param>
/// <returns>
/// エンコードされたテキストデータ、エンコードに失敗した場合空の文字列
/// </returns>
[[nodiscard]] String Encode(const void* data, size_t size);
/// <summary>
/// データを Base64 エンコードします。
/// </summary>
/// <param name="view">
/// エンコードするデータ
/// </param>
/// <returns>
/// エンコードされたテキストデータ、エンコードに失敗した場合空の文字列
/// </returns>
[[nodiscard]] String Encode(ByteArrayView view);
/// <summary>
/// テキストを Base64 でデコードします。
/// </summary>
/// <param name="view">
/// デコードするテキスト
/// </param>
/// <returns>
/// デコードされたバイナリデータ、デコードに失敗した場合空のバイナリデータ
/// </returns>
[[nodiscard]] ByteArray Decode(StringView view);
};
}
| 20.612903
| 61
| 0.553991
|
Fuyutsubaki
|
45b73eca1940d922653a5d22e172df165ef4f990
| 824
|
cpp
|
C++
|
superneurons/testing/test_malloc_free_speed.cpp
|
Phaeton-lang/baselines
|
472c248047fbb55b5fa0e620758047b7f0a1d041
|
[
"MIT"
] | null | null | null |
superneurons/testing/test_malloc_free_speed.cpp
|
Phaeton-lang/baselines
|
472c248047fbb55b5fa0e620758047b7f0a1d041
|
[
"MIT"
] | null | null | null |
superneurons/testing/test_malloc_free_speed.cpp
|
Phaeton-lang/baselines
|
472c248047fbb55b5fa0e620758047b7f0a1d041
|
[
"MIT"
] | null | null | null |
//
// Created by ay27 on 8/15/17.
//
#include <superneurons.h>
using namespace std;
using namespace SuperNeurons;
int main(int argc, char** argv) {
const int T = 100;
const size_t MB = 1024*1024;
double ts;
double t1 = 0, t2 = 0;
size_t size;
//------------------------------------------------
for (size_t size = 128; size <= 5*1024; size += 128) {
t1 = 0;
t2 = 0;
float *ptr;
for (int i = 0; i < T; ++i) {
ts = get_cur_time();
cudaMalloc(&ptr, size * MB);
t1 += get_cur_time() - ts;
ts = get_cur_time();
cudaFree(ptr);
t2 += get_cur_time() - ts;
}
t1 = t1 / (double)T;
t2 = t2 / (double)T;
printf("- %f\n", t1);
printf("+ %f\n", t2);
}
}
| 20.097561
| 58
| 0.433252
|
Phaeton-lang
|
45c0d698f2da891f8e4c70ef14a9883932ed1004
| 1,492
|
cpp
|
C++
|
GeeksForGeeks/Strongly Connected Components (Kosaraju's Algo).cpp
|
tanishq1g/cp_codes
|
80b8ccc9e195a66d6d317076fdd54a02cd21275b
|
[
"MIT"
] | null | null | null |
GeeksForGeeks/Strongly Connected Components (Kosaraju's Algo).cpp
|
tanishq1g/cp_codes
|
80b8ccc9e195a66d6d317076fdd54a02cd21275b
|
[
"MIT"
] | null | null | null |
GeeksForGeeks/Strongly Connected Components (Kosaraju's Algo).cpp
|
tanishq1g/cp_codes
|
80b8ccc9e195a66d6d317076fdd54a02cd21275b
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <vector>
#include <locale>
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include <bitset>
#include <climits>
#include <queue>
#include <stack>
using namespace std;
// GRAPH
void dfs(vector<int> adj[], vector<bool> &vis, stack<int> &st, int ind){
vis[ind] = true;
int sadj = adj[ind].size();
for(int i = 0; i < sadj; i++){
if(vis[adj[ind][i]] == false){
dfs(adj, vis, st, adj[ind][i]);
}
}
st.push(ind);
}
void dfs2(vector<int> adj[], vector<bool> &vis, int ind){
vis[ind] = true;
int sadj = adj[ind].size();
for(int i = 0; i < sadj; i++){
if(vis[adj[ind][i]] == false){
dfs2(adj, vis, adj[ind][i]);
}
}
// st.push(ind);
}
int kosaraju(int V, vector<int> adj[]){
if(V==0)
return 0;
vector<bool> vis(V, false);
stack<int> st;
for(int i = 0; i < V; i++){
if(vis[i] == false){
dfs(adj, vis, st, i);
}
}
vis = vector<bool> (V, false);
vector<int> adj2[V];
int sadj;
for(int i = 0; i < V; i++){
sadj = adj[i].size();
for(int j = 0; j < sadj; j++){
adj2[adj[i][j]].push_back(i);
}
}
delete adj;
int count = 0;
while(!st.empty()){
int i = st.top();
st.pop();
if(vis[i] == false){
dfs2(adj2, vis, i);
count++;
}
}
return count;
}
| 19.893333
| 72
| 0.476542
|
tanishq1g
|
45c1f7f43093cf219183eba6c6043dbd56ca7db3
| 1,532
|
cpp
|
C++
|
CWin/CWin/events/event_trigger_condition.cpp
|
benbraide/CWin
|
0441b48a71fef0dbddabf61033d7286669772c1e
|
[
"MIT"
] | null | null | null |
CWin/CWin/events/event_trigger_condition.cpp
|
benbraide/CWin
|
0441b48a71fef0dbddabf61033d7286669772c1e
|
[
"MIT"
] | null | null | null |
CWin/CWin/events/event_trigger_condition.cpp
|
benbraide/CWin
|
0441b48a71fef0dbddabf61033d7286669772c1e
|
[
"MIT"
] | null | null | null |
#include "event_trigger_condition.h"
cwin::events::trigger_condition::~trigger_condition() = default;
cwin::events::trigger_condition::operator m_callback_type() const{
return get();
}
cwin::events::trigger_condition::m_callback_type cwin::events::trigger_condition::get() const{
return nullptr;
}
cwin::events::external_trigger_condition::external_trigger_condition(const m_callback_type &value)
: value_(value){}
cwin::events::external_trigger_condition::~external_trigger_condition() = default;
cwin::events::trigger_condition::m_callback_type cwin::events::external_trigger_condition::get() const{
return value_;
}
cwin::events::odd_count_trigger_condition::~odd_count_trigger_condition() = default;
cwin::events::trigger_condition::m_callback_type cwin::events::odd_count_trigger_condition::get() const{
return [](std::size_t count){
return ((count % 2u) == 1u);
};
}
cwin::events::even_count_trigger_condition::~even_count_trigger_condition() = default;
cwin::events::trigger_condition::m_callback_type cwin::events::even_count_trigger_condition::get() const{
return [](std::size_t count){
return ((count % 2u) == 0u);
};
}
cwin::events::max_count_trigger_condition::max_count_trigger_condition(std::size_t value)
: value_(value){}
cwin::events::max_count_trigger_condition::~max_count_trigger_condition() = default;
cwin::events::trigger_condition::m_callback_type cwin::events::max_count_trigger_condition::get() const{
return [value = value_](std::size_t count){
return (count <= value);
};
}
| 31.916667
| 105
| 0.772846
|
benbraide
|
45c4ff283f1bd510f5089c454c2a348f353c0a08
| 3,347
|
cpp
|
C++
|
12_TIM1_PWM_input/main.cpp
|
AVilezhaninov/STM32F429VG
|
cb77fb53235ffd4cdf000749e4857108bc96c2cb
|
[
"MIT"
] | null | null | null |
12_TIM1_PWM_input/main.cpp
|
AVilezhaninov/STM32F429VG
|
cb77fb53235ffd4cdf000749e4857108bc96c2cb
|
[
"MIT"
] | null | null | null |
12_TIM1_PWM_input/main.cpp
|
AVilezhaninov/STM32F429VG
|
cb77fb53235ffd4cdf000749e4857108bc96c2cb
|
[
"MIT"
] | null | null | null |
/* CMSIS */
#include "CMSIS\Device\stm32f4xx.h"
/* User */
#include "user\RCC.h"
/******************************************************************************/
/* Private definitions ********************************************************/
/******************************************************************************/
#define TIM1_PSC 0u /* TIM1 clock: (180 MHz / 1) = 180 MHz */
#define TIM1_ARR 65535u /* TIM1 maximum clock value */
#define TIM1_IRQ_PRIORITY 5u
/******************************************************************************/
/* Private function prototypes ************************************************/
/******************************************************************************/
static void InitTim1();
/******************************************************************************/
/* Interrupts *****************************************************************/
/******************************************************************************/
extern "C" {
/**
* TIM1 capture compare interrupt handler
*/
void TIM1_CC_IRQHandler() {
uint16_t period;
uint16_t width;
if ((TIM1->SR & TIM_SR_CC2IF) == TIM_SR_CC2IF) {
period = TIM1->CCR2; /* Get pulse period */
width = TIM1->CCR1; /* Get pulse width */
}
TIM1->SR &= ~TIM_SR_CC1OF; /* Clear overcapture 1 flag */
TIM1->SR &= ~TIM_SR_CC2OF; /* Clear overcapture 2 flag */
}
} /* extern "C" */
/******************************************************************************/
/* Main ***********************************************************************/
/******************************************************************************/
int main(void) {
InitSystemClock();
InitTim1();
while (1) {
;
}
}
/******************************************************************************/
/* Private functions **********************************************************/
/******************************************************************************/
void InitTim1() {
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOEEN; /* Enable PORTE clock */
GPIOE->MODER |= GPIO_MODER_MODER11_1; /* PE11 alternate mode */
GPIOE->AFR[1u] |= (1u << 12u); /* PE11 in AF1 */
RCC->APB2ENR |= RCC_APB2ENR_TIM1EN; /* Enable TIM1 clock */
TIM1->PSC = TIM1_PSC; /* Set TIM1 prescaler */
TIM1->ARR = TIM1_ARR; /* Set TIM1 auto reload value */
TIM1->CCMR1 |= TIM_CCMR1_CC1S_1; /* IC1 mapped on TI2 */
TIM1->CCER |= TIM_CCER_CC1P; /* Falling edge on TI1 */
TIM1->CCMR1 |= TIM_CCMR1_CC2S_0; /* IC2 mapped on TI1 */
TIM1->SMCR |= TIM_SMCR_TS_2 | TIM_SMCR_TS_1; /* Filtered timer input 2 */
TIM1->SMCR |= TIM_SMCR_SMS_2; /* "Reset" slave mode */
TIM1->DIER |= TIM_DIER_CC2IE; /* Capture 2 interrupt enable */
TIM1->CCER |= TIM_CCER_CC2E; /* Caputre 2 output enbale */
TIM1->CCER |= TIM_CCER_CC1E; /* Caputre 1 output enbale */
NVIC_SetPriority(TIM1_CC_IRQn, TIM1_IRQ_PRIORITY); /* Set TIM1 interrupt
* priority */
NVIC_EnableIRQ(TIM1_CC_IRQn); /* Enable TIM1 capture interrupt */
TIM1->CR1 |= TIM_CR1_CEN; /* Enable TIM1 timer */
}
| 42.367089
| 80
| 0.380042
|
AVilezhaninov
|
45c88d8e96e32d7e9ca06903b231e840b90406f2
| 836
|
cxx
|
C++
|
src/engine/ivp/ivp_collision/ivp_clustering_lrange_hash.cxx
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | 6
|
2022-01-23T09:40:33.000Z
|
2022-03-20T20:53:25.000Z
|
src/engine/ivp/ivp_collision/ivp_clustering_lrange_hash.cxx
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | null | null | null |
src/engine/ivp/ivp_collision/ivp_clustering_lrange_hash.cxx
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | 1
|
2022-02-06T21:05:23.000Z
|
2022-02-06T21:05:23.000Z
|
// Copyright (C) Ipion Software GmbH 1999-2000. All rights reserved.
#include <ivp_physics.hxx>
#include <ivu_vhash.hxx>
#include <ivp_clustering_longrange.hxx>
#include <ivp_clustering_lrange_hash.hxx>
IVP_ov_tree_hash::~IVP_ov_tree_hash() { ; }
int IVP_ov_tree_hash::node_to_index(IVP_OV_Node *node) {
return hash_index((char *) &node->data, sizeof(node->data));
}
IVP_BOOL IVP_ov_tree_hash::compare(void *elem0, void *elem1) const {
IVP_OV_Node *node0 = (IVP_OV_Node *) elem0;
IVP_OV_Node *node1 = (IVP_OV_Node *) elem1;
if (node0->data.rasterlevel != node1->data.rasterlevel) return (IVP_FALSE);
if (node0->data.x != node1->data.x) return (IVP_FALSE);
if (node0->data.y != node1->data.y) return (IVP_FALSE);
if (node0->data.z != node1->data.z) return (IVP_FALSE);
return (IVP_TRUE);
}
| 24.588235
| 79
| 0.697368
|
cstom4994
|
68f7074b50725b6a6363ef2a3ca8ae00111b5899
| 19,721
|
cpp
|
C++
|
components/sound/manager/sources/manager/sound_manager.cpp
|
untgames/funner
|
c91614cda55fd00f5631d2bd11c4ab91f53573a3
|
[
"MIT"
] | 7
|
2016-03-30T17:00:39.000Z
|
2017-03-27T16:04:04.000Z
|
components/sound/manager/sources/manager/sound_manager.cpp
|
untgames/Funner
|
c91614cda55fd00f5631d2bd11c4ab91f53573a3
|
[
"MIT"
] | 4
|
2017-11-21T11:25:49.000Z
|
2018-09-20T17:59:27.000Z
|
components/sound/manager/sources/manager/sound_manager.cpp
|
untgames/Funner
|
c91614cda55fd00f5631d2bd11c4ab91f53573a3
|
[
"MIT"
] | 4
|
2016-11-29T15:18:40.000Z
|
2017-03-27T16:04:08.000Z
|
#include <stl/algorithm>
#include <stl/hash_map>
#include <stl/list>
#include <stl/stack>
#include <stl/string>
#include <xtl/bind.h>
#include <xtl/common_exceptions.h>
#include <xtl/function.h>
#include <xtl/intrusive_ptr.h>
#include <xtl/iterator.h>
#include <xtl/shared_ptr.h>
#include <xtl/signal.h>
#include <common/log.h>
#include <common/time.h>
#include <sound/device.h>
#include <sound/driver.h>
#include <sound/manager.h>
#include <media/sound.h>
#include <media/sound_declaration.h>
using namespace sound;
using namespace sound::low_level;
using namespace stl;
using namespace xtl;
using namespace common;
using namespace media;
#ifdef _MSC_VER
#pragma warning (disable : 4355) //'this' : used in base member initializer list
#endif
namespace
{
const float EPS = 0.001f;
const char* LOG_NAME = "sound::SoundManager"; //имя потока протоколирования
SeekMode get_seek_mode (bool looping)
{
if (looping) return SeekMode_Repeat;
else return SeekMode_Clamp;
}
typedef stl::list<SoundDeclarationLibrary> SoundDeclarationLibraryList;
typedef xtl::com_ptr<ISample> SamplePtr;
}
/*
Описание реализации SoundManager
*/
struct SoundManagerEmitter
{
int channel_number; //номер канала проигрывания (-1 - отсечён или не проигрывается)
float cur_position; //текущая позиция проигрывания в секундах
size_t play_start_time; //время начала проигрывания
bool is_playing; //статус проигрывания
SoundDeclaration sound_declaration; //описание звука
SamplePtr sound_sample; //сэмпл звука
double duration; //длительность звука
float sound_declaration_gain; //громкость, заданная в описании звука (установка громкости производится относительно этого значения)
bool sample_chosen; //эммитер ещё не проигрывался
Source source; //излучатель звука
string source_name; //имя источника
size_t sample_index; //индекс сэмпла
auto_connection update_volume_connection; //соединение события изменения громкости
auto_connection update_properties_connection; //соединение события изменения свойств
SoundManagerEmitter (connection in_update_volume_connection, connection in_update_properties_connection)
: channel_number (-1), is_playing (false), sample_chosen (false), sample_index (0),
update_volume_connection (in_update_volume_connection), update_properties_connection (in_update_properties_connection)
{}
};
typedef xtl::shared_ptr<SoundManagerEmitter> SoundManagerEmitterPtr;
typedef stl::hash_map<Emitter*, SoundManagerEmitterPtr> EmitterSet;
typedef xtl::com_ptr<low_level::IDevice> DevicePtr;
typedef xtl::com_ptr<low_level::IDriver> DriverPtr;
typedef stl::stack<unsigned short> ChannelsSet;
struct SoundManager::Impl : public xtl::trackable
{
DevicePtr device; //устройство воспроизведения
float volume; //добавочная громкость
bool is_muted; //флаг блокировки проигрывания звука
sound::Listener listener; //параметры слушателя
EmitterSet emitters; //излучатели звука
ChannelsSet free_channels; //номера свободных каналов
Capabilities capabilities; //возможности устройства
SoundDeclarationLibraryList sound_declaration_libraries; //библиотека описаний звуков
common::Log log; //протокол
xtl::trackable trackable;
Impl (const char* driver_mask, const char* device_mask, const char* init_string)
: volume (1.f), log (LOG_NAME)
{
try
{
device = DevicePtr (DriverManager::CreateDevice (driver_mask, device_mask, init_string), false);
device->GetCapabilities (capabilities);
for (unsigned short i = 0; i < capabilities.channels_count; i++)
free_channels.push (i);
}
catch (xtl::exception& exception)
{
exception.touch ("sound::low_level::SoundManager::SoundManager");
throw;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///Блокировка проигрывания звука
///////////////////////////////////////////////////////////////////////////////////////////////////
void SetMute (bool state)
{
is_muted = state;
device->SetMute (state);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///Обновление свойств эмиттеров
///////////////////////////////////////////////////////////////////////////////////////////////////
void UpdateEmitterVolume (Emitter& emitter, EmitterEvent event)
{
EmitterSet::iterator emitter_iter = emitters.find (&emitter);
if (emitter_iter == emitters.end ())
return;
emitter_iter->second->source.gain = emitter_iter->second->sound_declaration_gain * emitter_iter->first->Volume ();
if (emitter_iter->second->channel_number != -1)
device->SetSource (emitter_iter->second->channel_number, emitter_iter->second->source);
}
void UpdateEmitterProperties (Emitter& emitter, EmitterEvent event)
{
EmitterSet::iterator emitter_iter = emitters.find (&emitter);
if (emitter_iter == emitters.end ())
return;
emitter_iter->second->source.position = emitter_iter->first->Position ();
emitter_iter->second->source.direction = emitter_iter->first->Direction ();
emitter_iter->second->source.velocity = emitter_iter->first->Velocity ();
if (emitter_iter->second->channel_number != -1)
device->SetSource (emitter_iter->second->channel_number, emitter_iter->second->source);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///Проигрывание звуков
///////////////////////////////////////////////////////////////////////////////////////////////////
void PlaySound (Emitter& emitter, float offset)
{
try
{
emitter.Activate ();
EmitterSet::iterator emitter_iter = emitters.find (&emitter);
SoundManagerEmitterPtr manager_emitter;
if (emitter_iter == emitters.end ())
manager_emitter = SoundManagerEmitterPtr (new SoundManagerEmitter (emitter.RegisterEventHandler (EmitterEvent_OnUpdateVolume, xtl::bind (&SoundManager::Impl::UpdateEmitterVolume, this, _1, _2)),
emitter.RegisterEventHandler (EmitterEvent_OnUpdateProperties, xtl::bind (&SoundManager::Impl::UpdateEmitterProperties, this, _1, _2)))); //создаем эмиттер, в карту добавляем позже, если найдем описание звука
else
manager_emitter = emitter_iter->second;
if (strcmp (manager_emitter->source_name.c_str (), emitter.Source ()))
{
SoundDeclaration *emitter_sound_declaration = 0;
for (SoundDeclarationLibraryList::iterator iter = sound_declaration_libraries.begin (),
end = sound_declaration_libraries.end (); iter != end; ++iter)
{
emitter_sound_declaration = iter->Find (emitter.Source ());
if (emitter_sound_declaration)
break;
}
if (!emitter_sound_declaration)
{
log.Printf ("Can't find sound declaration for id '%s'.", emitter.Source ());
StopSound (emitter);
return;
}
manager_emitter->sound_declaration = *emitter_sound_declaration;
manager_emitter->sound_declaration_gain = manager_emitter->sound_declaration.Param (SoundParam_Gain);
manager_emitter->source.gain = emitter.Volume() * manager_emitter->sound_declaration_gain;
manager_emitter->source.minimum_gain = manager_emitter->sound_declaration.Param (SoundParam_MinimumGain);
manager_emitter->source.maximum_gain = manager_emitter->sound_declaration.Param (SoundParam_MaximumGain);
manager_emitter->source.inner_angle = manager_emitter->sound_declaration.Param (SoundParam_InnerAngle);
manager_emitter->source.outer_angle = manager_emitter->sound_declaration.Param (SoundParam_OuterAngle);
manager_emitter->source.outer_gain = manager_emitter->sound_declaration.Param (SoundParam_OuterGain);
manager_emitter->source.reference_distance = manager_emitter->sound_declaration.Param (SoundParam_ReferenceDistance);
manager_emitter->source.maximum_distance = manager_emitter->sound_declaration.Param (SoundParam_MaximumDistance);
manager_emitter->source_name = emitter.Source ();
if (emitter_iter == emitters.end ())
emitters.insert_pair (&emitter, manager_emitter);
}
if (!manager_emitter->sample_chosen || manager_emitter->sample_index != emitter.SampleIndex ())
{
manager_emitter->sample_index = emitter.SampleIndex ();
manager_emitter->sound_sample = SamplePtr (device->CreateSample (manager_emitter->sound_declaration.Sample (manager_emitter->sample_index % manager_emitter->sound_declaration.SamplesCount ())), false);
SampleDesc sample_desc;
manager_emitter->sound_sample->GetDesc (sample_desc);
manager_emitter->duration = sample_desc.samples_count / (double)sample_desc.frequency;
manager_emitter->sample_chosen = true;
}
if (!manager_emitter->sound_declaration.Looping () && offset > manager_emitter->duration - EPS) //ignore attempts to play sound beyond end
return;
if (!manager_emitter->is_playing || manager_emitter->channel_number == -1)
{
manager_emitter->is_playing = true;
if (!free_channels.empty ())
{
unsigned short channel_to_use = free_channels.top ();
free_channels.pop ();
manager_emitter->channel_number = channel_to_use;
}
else
{
log.Printf ("Can't play sound %s, no free channels", manager_emitter->sound_sample->GetName ());
manager_emitter->channel_number = -1;
}
}
manager_emitter->play_start_time = milliseconds ();
manager_emitter->cur_position = offset;
UpdateEmitterProperties (emitter, EmitterEvent_OnUpdateProperties);
if (manager_emitter->channel_number != -1)
{
device->Stop (manager_emitter->channel_number);
device->SetSample (manager_emitter->channel_number, manager_emitter->sound_sample.get ());
device->SetSource (manager_emitter->channel_number, manager_emitter->source);
device->Seek (manager_emitter->channel_number, manager_emitter->cur_position, get_seek_mode (manager_emitter->sound_declaration.Looping ()));
device->Play (manager_emitter->channel_number, manager_emitter->sound_declaration.Looping ());
}
}
catch (xtl::exception& e)
{
log.Printf ("Can't play sound. Exception: '%s'", e.what ());
StopSound (emitter);
throw;
}
catch (...)
{
log.Printf ("Can't play sound. Unknown exception");
StopSound (emitter);
throw;
}
}
void PauseSound (Emitter& emitter)
{
EmitterSet::iterator emitter_iter = emitters.find (&emitter);
if (emitter_iter == emitters.end ())
return;
if (emitter_iter->second->is_playing)
{
float offset = (milliseconds () - emitter_iter->second->play_start_time) / 1000.f + emitter_iter->second->cur_position;
if (emitter_iter->second->sound_declaration.Looping ())
emitter_iter->second->cur_position = fmod (offset, (float)emitter_iter->second->duration);
else
emitter_iter->second->cur_position = offset < emitter_iter->second->duration ? offset : 0.0f;
StopPlaying (emitter_iter);
}
}
void StopSound (Emitter& emitter)
{
EmitterSet::iterator emitter_iter = emitters.find (&emitter);
if (emitter_iter == emitters.end ())
{
emitter.Deactivate ();
return;
}
if (emitter_iter->second->is_playing)
StopPlaying (emitter_iter);
emitter.Deactivate ();
emitters.erase (emitter_iter);
}
void StopPlaying (EmitterSet::iterator emitter_iter)
{
emitter_iter->second->is_playing = false;
if (emitter_iter->second->channel_number != -1)
{
device->Stop (emitter_iter->second->channel_number);
free_channels.push (emitter_iter->second->channel_number);
emitter_iter->second->channel_number = -1;
}
}
float Tell (Emitter& emitter)
{
EmitterSet::iterator emitter_iter = emitters.find (&emitter);
if (emitter_iter == emitters.end ())
return 0.f;
if (emitter_iter->second->is_playing)
{
float offset = (milliseconds () - emitter_iter->second->play_start_time) / 1000.f + emitter_iter->second->cur_position;
if (emitter_iter->second->sound_declaration.Looping ()) return fmod (offset, (float)emitter_iter->second->duration);
else return offset < emitter_iter->second->duration ? offset : 0.0f;
}
else
return emitter_iter->second->cur_position;
}
float Duration (Emitter& emitter) const
{
EmitterSet::const_iterator emitter_iter = emitters.find (&emitter);
if (emitter_iter == emitters.end ())
return 0.f;
return (float)emitter_iter->second->duration;
}
bool IsLooping (Emitter& emitter) const
{
EmitterSet::const_iterator emitter_iter = emitters.find (&emitter);
if (emitter_iter == emitters.end ())
return false;
return emitter_iter->second->sound_declaration.Looping ();
}
bool IsPlaying (Emitter& emitter) const
{
EmitterSet::const_iterator emitter_iter = emitters.find (&emitter);
if (emitter_iter == emitters.end ())
return false;
return emitter_iter->second->is_playing;
}
};
/*
Конструктор / деструктор
*/
SoundManager::SoundManager (const char* driver_mask, const char* device_mask, const char* init_string)
: impl (new Impl (driver_mask, device_mask, init_string))
{
}
SoundManager::~SoundManager ()
{
}
/*
Уровень громкости
*/
void SoundManager::SetVolume (float volume)
{
if (volume < 0.0f) volume = 0.0f;
if (volume > 1.0f) volume = 1.0f;
impl->volume = volume;
impl->device->SetVolume (volume);
}
float SoundManager::Volume () const
{
return impl->volume;
}
/*
Блокировка проигрывания звука
*/
void SoundManager::SetMute (bool state)
{
impl->SetMute (state);
}
bool SoundManager::IsMuted () const
{
return impl->is_muted;
}
/*
Проигрывание звуков
*/
void SoundManager::PlaySound (Emitter& emitter, float offset)
{
impl->PlaySound (emitter, offset);
}
void SoundManager::StopSound (Emitter& emitter)
{
impl->StopSound (emitter);
}
float SoundManager::Tell (Emitter& emitter) const
{
return impl->Tell (emitter);
}
float SoundManager::Duration (Emitter& emitter) const
{
return impl->Duration (emitter);
}
bool SoundManager::IsLooping (Emitter& emitter) const
{
return impl->IsLooping (emitter);
}
bool SoundManager::IsPlaying (Emitter& emitter) const
{
return impl->IsPlaying (emitter);
}
/*
Применение операции ко всем слушателям
*/
void SoundManager::ForEachEmitter (const EmitterHandler& emitter_handler)
{
for (EmitterSet::iterator i = impl->emitters.begin (); i != impl->emitters.end (); ++i)
emitter_handler (*(i->first));
}
void SoundManager::ForEachEmitter (const ConstEmitterHandler& emitter_handler) const
{
for (EmitterSet::iterator i = impl->emitters.begin (); i != impl->emitters.end (); ++i)
emitter_handler (*(i->first));
}
/*
Применение операции ко всем слушателям c заданным типом
*/
void SoundManager::ForEachEmitter (const char* type, const EmitterHandler& emitter_handler)
{
if (!type)
throw xtl::make_null_argument_exception ("sound::SoundManager::ForEachEmitter", "type");
for (EmitterSet::iterator i = impl->emitters.begin (); i != impl->emitters.end (); ++i)
if (!strcmp (type, i->second->sound_declaration.Type ()))
emitter_handler (*(i->first));
}
void SoundManager::ForEachEmitter (const char* type, const ConstEmitterHandler& emitter_handler) const
{
if (!type)
throw xtl::make_null_argument_exception ("sound::SoundManager::ForEachEmitter", "type");
for (EmitterSet::iterator i = impl->emitters.begin (); i != impl->emitters.end (); ++i)
if (!strcmp (type, i->second->sound_declaration.Type ()))
emitter_handler (*(i->first));
}
/*
Регистрация обработчиков события удаления объекта
*/
xtl::connection SoundManager::RegisterDestroyHandler (xtl::trackable::slot_type& handler)
{
return impl->connect_tracker (handler);
}
xtl::connection SoundManager::RegisterDestroyHandler (const xtl::trackable::function_type& handler)
{
return impl->connect_tracker (handler);
}
xtl::connection SoundManager::RegisterDestroyHandler (const xtl::trackable::function_type& handler, xtl::trackable& trackable)
{
return impl->connect_tracker (handler, trackable);
}
/*
Установка слушателя
*/
void SoundManager::SetListener (const sound::Listener& listener)
{
impl->listener = listener;
impl->device->SetListener (listener);
}
const sound::Listener& SoundManager::Listener () const
{
return impl->listener;
}
/*
Загрузка/выгрузка библиотек звуков
*/
void SoundManager::LoadSoundLibrary (const char* file_name)
{
impl->sound_declaration_libraries.push_front (SoundDeclarationLibrary (file_name));
for (SoundDeclarationLibraryList::iterator iter = ++impl->sound_declaration_libraries.begin (),
end = impl->sound_declaration_libraries.end (); iter != end; ++iter)
{
if (!xtl::xstrcmp (file_name, iter->Name ()))
{
impl->sound_declaration_libraries.erase (iter);
impl->log.Printf ("Warning: sound declaration library '%s' was reloaded", file_name);
break;
}
}
SoundDeclarationLibrary& new_library = impl->sound_declaration_libraries.front ();
for (SoundDeclarationLibrary::Iterator iter = new_library.CreateIterator (); iter; ++iter)
{
const char* item_id = new_library.ItemId (iter);
for (SoundDeclarationLibraryList::iterator library_iter = ++impl->sound_declaration_libraries.begin (),
end = impl->sound_declaration_libraries.end (); library_iter != end; ++library_iter)
{
if (library_iter->Find (item_id))
{
impl->log.Printf ("Warning: ignoring already loaded sound declaration with id '%s' - redefinition in library '%s'", item_id, file_name);
continue;
}
}
}
}
void SoundManager::UnloadSoundLibrary (const char* file_name)
{
if (!file_name)
return;
for (SoundDeclarationLibraryList::iterator iter = impl->sound_declaration_libraries.begin (),
end = impl->sound_declaration_libraries.end (); iter != end; ++iter)
{
if (!xtl::xstrcmp (file_name, iter->Name ()))
{
impl->sound_declaration_libraries.erase (iter);
break;
}
}
}
| 33.539116
| 221
| 0.637341
|
untgames
|
68f869732418d1de819ccec3d477502ec2a8e751
| 2,715
|
cpp
|
C++
|
vkconfig/widget_preset.cpp
|
johnzupin/VulkanTools
|
4a4d824b43984d29902f7c8246aab99f0909151d
|
[
"Apache-2.0"
] | null | null | null |
vkconfig/widget_preset.cpp
|
johnzupin/VulkanTools
|
4a4d824b43984d29902f7c8246aab99f0909151d
|
[
"Apache-2.0"
] | null | null | null |
vkconfig/widget_preset.cpp
|
johnzupin/VulkanTools
|
4a4d824b43984d29902f7c8246aab99f0909151d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2020 Valve Corporation
* Copyright (c) 2020 LunarG, 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.
*
* Authors:
* - Christophe Riccio <christophe@lunarg.com>
*/
#include "widget_preset.h"
#include <cassert>
PresetWidget::PresetWidget(QTreeWidgetItem* item, const Layer& layer, Parameter& parameter) : layer(layer), parameter(parameter) {
assert(item);
assert(&layer);
assert(¶meter);
this->blockSignals(true);
this->addItem("User Defined Settings");
preset_indexes.push_back(Layer::NO_PRESET);
for (std::size_t i = 0, n = layer.presets.size(); i < n; ++i) {
const LayerPreset& layer_preset = layer.presets[i];
if (!(layer_preset.platform_flags & (1 << VKC_PLATFORM))) {
continue;
}
this->addItem((layer_preset.label + " Preset").c_str());
preset_indexes.push_back(layer_preset.preset_index);
}
this->blockSignals(false);
this->UpdateCurrentIndex();
connect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(OnPresetChanged(int)));
}
void PresetWidget::UpdateCurrentIndex() {
int preset_index = layer.FindPresetIndex(parameter.settings);
this->blockSignals(true);
this->setCurrentIndex(GetComboBoxIndex(preset_index));
this->blockSignals(false);
if (preset_index == Layer::NO_PRESET) return;
const LayerPreset* preset = GetPreset(layer.presets, preset_index);
assert(preset != nullptr);
this->setToolTip(preset->description.c_str());
}
int PresetWidget::GetComboBoxIndex(const int preset_index) const {
for (std::size_t i = 0, n = preset_indexes.size(); i < n; ++i) {
if (preset_indexes[i] == preset_index) return static_cast<int>(i);
}
assert(0);
return -1;
}
void PresetWidget::OnPresetChanged(int combox_preset_index) {
assert(combox_preset_index >= 0 && static_cast<std::size_t>(combox_preset_index) < preset_indexes.size());
const int preset_index = preset_indexes[combox_preset_index];
if (preset_index == Layer::NO_PRESET) return;
const LayerPreset* preset = GetPreset(layer.presets, preset_index);
assert(preset != nullptr);
parameter.ApplyPresetSettings(*preset);
}
| 31.569767
| 130
| 0.698343
|
johnzupin
|
68ff22d8df3673d6303576f88fc3fa40888fd4de
| 1,947
|
cpp
|
C++
|
network/src/network/loopPrivate.cpp
|
yandaomin/network
|
fd88844116d77639c7a76ec61fb352f2710f47a8
|
[
"Apache-2.0"
] | null | null | null |
network/src/network/loopPrivate.cpp
|
yandaomin/network
|
fd88844116d77639c7a76ec61fb352f2710f47a8
|
[
"Apache-2.0"
] | null | null | null |
network/src/network/loopPrivate.cpp
|
yandaomin/network
|
fd88844116d77639c7a76ec61fb352f2710f47a8
|
[
"Apache-2.0"
] | null | null | null |
#include "loopPrivate.h"
#include "async.h"
#include "loop.h"
// LoopPrivate::LoopPrivate()
// : LoopPrivate(false)
// {
// isRunning_ = false;
// }
LoopPrivate::LoopPrivate(bool isDefault) {
isRunning_ = false;
if (isDefault) {
loop_ = uv_default_loop();
}
else {
loop_ = new uv_loop_t();
::uv_loop_init(loop_);
}
}
LoopPrivate::~LoopPrivate() {
if (!isDefaultLoop()) {
uv_loop_close(loop_);
delete async_;
delete loop_;
}
}
// LoopPrivate* LoopPrivate::defaultLoop() {
// static LoopPrivate defaultLoop(true);
// return &defaultLoop;
// }
uv_loop_t* LoopPrivate::handle() {
return loop_;
}
bool LoopPrivate::isDefaultLoop() {
return (loop_ == uv_default_loop());
}
void LoopPrivate::init()
{
async_ = new Async((Loop*)parent_);
}
int LoopPrivate::run() {
if (!isRunning_) {
async_->init();
threadId_ = std::this_thread::get_id();
isRunning_ = true;
auto rlt = ::uv_run(loop_, UV_RUN_DEFAULT);
isRunning_ = false;
return rlt;
}
return -1;
}
int LoopPrivate::runNoWait(){
if (!isRunning_) {
async_->init();
threadId_ = std::this_thread::get_id();
isRunning_ = true;
auto rst = ::uv_run(loop_, UV_RUN_NOWAIT);
isRunning_ = false;
return rst;
}
return -1;
}
int LoopPrivate::stop() {
if (isRunning_){
async_->close([](Async* ptr)
{
::uv_stop((uv_loop_t*)(ptr->loop()->handle()));
});
return 0;
}
return -1;
}
bool LoopPrivate::isRunning() {
return isRunning_;
}
bool LoopPrivate::isSameThread() {
return std::this_thread::get_id() == threadId_;
}
void LoopPrivate::runInLoop(const ActionCallback func) {
if (nullptr == func)
return;
if (isSameThread() || !isRunning()) {
func();
return;
}
async_->run(func);
}
std::string LoopPrivate::getErrorMessage(int status) {
if (WriteResult::result_disconnected == status)
return "the connection is closed";
const char* msg = uv_strerror(status);
std::string errMsg(msg);
//delete[] msg;
return errMsg;
}
| 17.7
| 56
| 0.662044
|
yandaomin
|
ec087b40fc0aeb9bb7862421ed3d0a0427b72406
| 170
|
hpp
|
C++
|
dfg/dataAnalysisAll.hpp
|
tc3t/dfglib
|
7157973e952234a010da8e9fbd551a912c146368
|
[
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 1
|
2017-08-01T04:42:29.000Z
|
2017-08-01T04:42:29.000Z
|
dfg/dataAnalysisAll.hpp
|
tc3t/dfglib
|
7157973e952234a010da8e9fbd551a912c146368
|
[
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 128
|
2018-04-06T23:01:51.000Z
|
2022-03-31T20:19:38.000Z
|
dfg/dataAnalysisAll.hpp
|
tc3t/dfglib
|
7157973e952234a010da8e9fbd551a912c146368
|
[
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 3
|
2018-03-21T01:11:05.000Z
|
2021-04-05T19:20:31.000Z
|
#pragma once
#include "dataAnalysis/correlation.hpp"
#include "dataAnalysis/smoothWithNeighbourAverages.hpp"
#include "dataAnalysis/smoothWithNeighbourMedians.hpp"
| 28.333333
| 56
| 0.823529
|
tc3t
|
ec0ecae6922b038f7a8c11091a6209d1259ba087
| 1,271
|
cpp
|
C++
|
week08/lesson/743-network-delay-time-Dijkstra.cpp
|
MiracleWong/algorithm-learning-camp
|
aa5bee8f12dc25992aaebd46647537633bf1207f
|
[
"MIT"
] | null | null | null |
week08/lesson/743-network-delay-time-Dijkstra.cpp
|
MiracleWong/algorithm-learning-camp
|
aa5bee8f12dc25992aaebd46647537633bf1207f
|
[
"MIT"
] | null | null | null |
week08/lesson/743-network-delay-time-Dijkstra.cpp
|
MiracleWong/algorithm-learning-camp
|
aa5bee8f12dc25992aaebd46647537633bf1207f
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
// 建立图
vector<vector<int>> ver(n+1, vector<int>());
vector<vector<int>> edge(n+1, vector<int>());
for (auto& e: times) {
int x = e[0], y = e[1], z = e[2];
ver[x].push_back(y);
edge[x].push_back(z);
}
vector<int> dist(n+1, 1e9);
vector<bool> v(n+1, false); // expand是否扩展过
dist[k] = 0;
// dist 编号
priority_queue<pair<int,int>> q;
q.push(make_pair(-dist[k], k));
// Dijkstra 算法
while (!q.empty()) {
int x = q.top().second;
q.pop();
if (v[x]) continue;
v[x] = true;
for (int i = 0; i < ver[x].size(); i++) {
int y = ver[x][i];
int z = edge[x][i];
if (dist[x] + z < dist[y]) {
dist[y] = dist[x] + z;
q.push(make_pair(-dist[y], y));
}
}
}
int ans = 0;
for (int i=1; i <= n; i++) {
cout << "dist[i]" << dist[i] << endl;
ans = max(ans, dist[i]);
}
if (ans == 1e9) ans = -1;
return ans;
}
};
| 28.886364
| 68
| 0.389457
|
MiracleWong
|
ec0eef56d74c1c6cc4dae12c44f81b1e0cf72c91
| 689
|
cpp
|
C++
|
benchmarks/clean_shared_memory.cpp
|
MaximilienNaveau/shared_memory
|
1440454759cdd19e0d898753d86b8714c1aefa84
|
[
"BSD-3-Clause"
] | 2
|
2020-09-08T04:01:02.000Z
|
2021-01-28T15:02:11.000Z
|
benchmarks/clean_shared_memory.cpp
|
MaximilienNaveau/shared_memory
|
1440454759cdd19e0d898753d86b8714c1aefa84
|
[
"BSD-3-Clause"
] | 13
|
2019-09-24T17:21:49.000Z
|
2021-03-02T10:09:03.000Z
|
benchmarks/clean_shared_memory.cpp
|
MaximilienNaveau/shared_memory
|
1440454759cdd19e0d898753d86b8714c1aefa84
|
[
"BSD-3-Clause"
] | 2
|
2019-05-06T08:25:35.000Z
|
2020-04-14T11:49:02.000Z
|
/**
* @file clean_shared_memory.cpp
* @author Vincent Berenz
* @license License BSD-3-Clause
* @copyright Copyright (c) 2019, New York University and Max Planck
* Gesellschaft.
* @date 2019-05-22
*
* @brief Clean the shared memory of the benchmark, the unnittests, ...
*/
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/sync/named_mutex.hpp>
#include "shared_memory/benchmarks/benchmark_common.hh"
int main()
{
boost::interprocess::named_mutex::remove(SHM_NAME.c_str());
boost::interprocess::shared_memory_object::remove(SHM_OBJECT_NAME.c_str());
boost::interprocess::shared_memory_object::remove("main_memory");
return 0;
}
| 29.956522
| 79
| 0.744557
|
MaximilienNaveau
|
ec1575753c7539cdf739067f1dad2f0a0b145d89
| 1,263
|
cpp
|
C++
|
solutions/partition_to_k_equal_sum_subsets.cpp
|
kmykoh97/My-Leetcode
|
0ffdea16c3025805873aafb6feffacaf3411a258
|
[
"Apache-2.0"
] | null | null | null |
solutions/partition_to_k_equal_sum_subsets.cpp
|
kmykoh97/My-Leetcode
|
0ffdea16c3025805873aafb6feffacaf3411a258
|
[
"Apache-2.0"
] | null | null | null |
solutions/partition_to_k_equal_sum_subsets.cpp
|
kmykoh97/My-Leetcode
|
0ffdea16c3025805873aafb6feffacaf3411a258
|
[
"Apache-2.0"
] | null | null | null |
// Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into k non-empty subsets whose sums are all equal.
// Example 1:
// Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4
// Output: True
// Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
// Note:
// 1 <= k <= len(nums) <= 16.
// 0 < nums[i] < 10000.
// solution: dfs
class Solution {
public:
bool dfs(const vector<int>& nums, int target, int cur, int k, int used) {
if (k == 0) return (used == (1 << nums.size())-1);
for (int i = 0; i < nums.size(); ++i) {
if (used & (1 << i)) continue;
int t = cur+nums[i];
if (t > target) break;
int new_used = used | (1 << i);
if (t == target && dfs(nums, target, 0, k-1, new_used)) return true;
else if (dfs(nums, target, t, k, new_used)) return true;
}
return false;
}
bool canPartitionKSubsets(vector<int>& nums, int k) {
const int sum = accumulate(nums.begin(), nums.end(), 0);
if (sum % k != 0) return false;
sort(nums.begin(), nums.end());
return dfs(nums, sum/k, 0, k, 0);
}
};
| 29.372093
| 159
| 0.524941
|
kmykoh97
|
ec1b25669f107c859b42ff23c246f036309fd584
| 961
|
cc
|
C++
|
third_party/blink/renderer/modules/peerconnection/rtc_encoded_audio_receiver_sink_optimizer.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668
|
2015-01-01T01:57:10.000Z
|
2022-03-31T23:33:32.000Z
|
third_party/blink/renderer/modules/peerconnection/rtc_encoded_audio_receiver_sink_optimizer.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86
|
2015-10-21T13:02:42.000Z
|
2022-03-14T07:50:50.000Z
|
third_party/blink/renderer/modules/peerconnection/rtc_encoded_audio_receiver_sink_optimizer.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941
|
2015-01-02T11:32:21.000Z
|
2022-03-31T16:35:46.000Z
|
#include "third_party/blink/renderer/modules/peerconnection/rtc_encoded_audio_receiver_sink_optimizer.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
RtcEncodedAudioReceiverSinkOptimizer::RtcEncodedAudioReceiverSinkOptimizer(
UnderlyingSinkSetter set_underlying_sink,
scoped_refptr<blink::RTCEncodedAudioStreamTransformer::Broker> transformer)
: set_underlying_sink_(std::move(set_underlying_sink)),
transformer_(std::move(transformer)) {}
UnderlyingSinkBase*
RtcEncodedAudioReceiverSinkOptimizer::PerformInProcessOptimization(
ScriptState* script_state) {
auto* new_sink = MakeGarbageCollected<RTCEncodedAudioUnderlyingSink>(
script_state, std::move(transformer_));
std::move(set_underlying_sink_).Run(WrapCrossThreadPersistent(new_sink));
return new_sink;
}
} // namespace blink
| 38.44
| 104
| 0.825182
|
zealoussnow
|
ec1df7964614a4d7c573d595175c61fd57240122
| 3,463
|
cpp
|
C++
|
Queries/LanguageQuery.cpp
|
garmin/ActiveCaptainCommunitySDK-common
|
a7574a3b85b77771ceb47e5fc9a99fd31a10d47a
|
[
"Apache-2.0"
] | null | null | null |
Queries/LanguageQuery.cpp
|
garmin/ActiveCaptainCommunitySDK-common
|
a7574a3b85b77771ceb47e5fc9a99fd31a10d47a
|
[
"Apache-2.0"
] | null | null | null |
Queries/LanguageQuery.cpp
|
garmin/ActiveCaptainCommunitySDK-common
|
a7574a3b85b77771ceb47e5fc9a99fd31a10d47a
|
[
"Apache-2.0"
] | null | null | null |
/*------------------------------------------------------------------------------
Copyright 2021 Garmin Ltd. or its subsidiaries.
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.
------------------------------------------------------------------------------*/
/**
@file
Class to represent a specific set of queries
Copyright 2017-2020 by Garmin Ltd. or its subsidiaries.
*/
#define DBG_MODULE "ACDB"
#define DBG_TAG "LanguageQuery"
#include "ACDB_pub_types.h"
#include "Acdb/Queries/LanguageQuery.hpp"
#include "DBG_pub.h"
#include "SQLiteCpp/Column.h"
namespace Acdb {
static const std::string ReadSql{"SELECT id, isoCode FROM languageType;"};
static const std::string WriteSql{
"INSERT OR REPLACE INTO languageType (id, isoCode) VALUES (?, ?)"};
//----------------------------------------------------------------
//!
//! @public
//! @detail Create Language query object.
//!
//----------------------------------------------------------------
LanguageQuery::LanguageQuery(SQLite::Database& aDatabase) {
try {
mRead.reset(new SQLite::Statement{aDatabase, ReadSql});
mWrite.reset(new SQLite::Statement{aDatabase, WriteSql});
} catch (const SQLite::Exception& e) {
DBG_W("SQLite Exception: %i %s", e.getErrorCode(), e.getErrorStr());
mRead.reset();
mWrite.reset();
}
} // End of LanguageQuery
//----------------------------------------------------------------
//!
//! @public
//! @detail Get all objects from database
//!
//----------------------------------------------------------------
bool LanguageQuery::GetAll(std::vector<LanguageTableDataType>& aResultOut) {
enum Columns { Id = 0, IsoCode };
if (!mRead) {
return false;
}
bool success = false;
try {
while (mRead->executeStep()) {
LanguageTableDataType result;
result.mId = mRead->getColumn(Columns::Id).getInt();
result.mIsoCode = mRead->getColumn(Columns::IsoCode).getText();
aResultOut.push_back(std::move(result));
}
success = !aResultOut.empty();
mRead->reset();
} catch (const SQLite::Exception& e) {
DBG_W("SQLite Exception: %i %s", e.getErrorCode(), e.getErrorStr());
success = false;
}
return success;
} // End of GetAll
//----------------------------------------------------------------
//!
//! @public
//! @brief Write language to database
//!
//----------------------------------------------------------------
bool LanguageQuery::Write(LanguageTableDataType&& aLanguageTableData) {
enum Parameters { Id = 1, IsoCode };
if (!mWrite) {
return false;
}
bool success = false;
try {
mWrite->bind(Parameters::Id, aLanguageTableData.mId);
mWrite->bind(Parameters::IsoCode, aLanguageTableData.mIsoCode);
success = mWrite->exec();
mWrite->reset();
} catch (const SQLite::Exception& e) {
DBG_W("SQLite Exception: %i %s", e.getErrorCode(), e.getErrorStr());
success = false;
}
return success;
} // End of Write
} // end of namespace Acdb
| 28.619835
| 80
| 0.574646
|
garmin
|
ec1f214e9a1c35cd7ee04a0109985f1a428a2937
| 2,473
|
hpp
|
C++
|
third-party/Empirical/include/emp/io/ascii_utils.hpp
|
koellingh/empirical-p53-simulator
|
aa6232f661e8fc65852ab6d3e809339557af521b
|
[
"MIT"
] | null | null | null |
third-party/Empirical/include/emp/io/ascii_utils.hpp
|
koellingh/empirical-p53-simulator
|
aa6232f661e8fc65852ab6d3e809339557af521b
|
[
"MIT"
] | null | null | null |
third-party/Empirical/include/emp/io/ascii_utils.hpp
|
koellingh/empirical-p53-simulator
|
aa6232f661e8fc65852ab6d3e809339557af521b
|
[
"MIT"
] | null | null | null |
/**
* @note This file is part of Empirical, https://github.com/devosoft/Empirical
* @copyright Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md
* @date 2020
*
* @file ascii_utils.hpp
* @brief Tools for working with ascii output.
* @note Status: ALPHA
*
*/
#ifndef EMP_ASCII_UTILS_H
#define EMP_ASCII_UTILS_H
#include <iostream>
#include <ostream>
#include "../base/assert.hpp"
#include "../base/vector.hpp"
#include "../datastructs/vector_utils.hpp"
namespace emp {
/// The following function prints an ascii bar graph on to the screen (or provided stream).
template <typename T>
void AsciiBarGraph( emp::vector<T> data,
size_t max_width=80, ///< What's the widest bars allowed?
bool show_scale=true, ///< Should we show the scale at bottom.
bool max_scale_1=true, ///< Should we limit scaling to 1:1?
std::ostream & os=std::cout) ///< Where to output the bar graph?
{
T min_size = emp::FindMin(data);
T max_size = emp::FindMax(data);
double scale = ((double) max_width) / ((double) max_size);
if (max_scale_1 && scale > 1.0) scale = 1.0;
for (T datum : data) {
double bar_width = datum * scale;
while (bar_width >= 1.0) { os << '='; bar_width -= 1.0; }
if (bar_width > 0.0) os << '~';
os << " (" << datum << ")\n";
}
if (show_scale) {
os << "SCALE: = -> " << (1.0 / scale) << std::endl;
}
}
/// Take the input data, break it into bins, and print it as a bar graph.
template <typename T>
void AsciiHistogram(emp::vector<T> data,
size_t num_bins=40, ///< How many bins in histogram?
size_t max_width=80, ///< What's the widest bars allowed?
bool show_scale=true, ///< Should we show the scale at bottom?
std::ostream & os=std::cout) ///< Where to output the bar graph?
{
T min_val = emp::FindMin(data);
T max_val = emp::FindMax(data);
T val_range = max_val - min_val;
T bin_width = val_range / (T) num_bins;
emp::vector<size_t> bins(num_bins, 0);
for (T d : data) {
size_t bin_id = (size_t) ( (d - min_val) / bin_width );
if (bin_id == num_bins) bin_id--;
bins[bin_id]++;
}
AsciiBarGraph<size_t>(bins, max_width, show_scale, true, os);
}
}
#endif
| 33.418919
| 96
| 0.57501
|
koellingh
|
ec1f273a78a9da8364d7fbaac6258d91b67b5c61
| 341
|
cc
|
C++
|
relative_path.cc
|
dancerj/gitlstreefs
|
f5eca366643a47814d3a12bc458e64a6a093e315
|
[
"BSD-3-Clause"
] | 2
|
2015-10-05T10:30:14.000Z
|
2018-09-10T05:35:04.000Z
|
relative_path.cc
|
dancerj/gitlstreefs
|
f5eca366643a47814d3a12bc458e64a6a093e315
|
[
"BSD-3-Clause"
] | 1
|
2015-10-04T16:58:10.000Z
|
2015-10-18T08:53:04.000Z
|
relative_path.cc
|
dancerj/gitlstreefs
|
f5eca366643a47814d3a12bc458e64a6a093e315
|
[
"BSD-3-Clause"
] | 1
|
2015-09-28T04:25:20.000Z
|
2015-09-28T04:25:20.000Z
|
#include "relative_path.h"
#include <assert.h>
#include <string>
using std::string;
string GetRelativePath(const char* path) {
// Input is /absolute/path/below
// convert to a relative path.
assert(*path != 0);
if (path[1] == 0) {
// special-case / ? "" isn't a good relative path.
return "./";
}
return path + 1;
}
| 17.05
| 54
| 0.615836
|
dancerj
|
ec213f9231c8fb1d202eee73c015179b132f8df4
| 5,346
|
cpp
|
C++
|
01_Develop/libXMCocos2D/Source/extensions/CCScrollView/CCSorting.cpp
|
mcodegeeks/OpenKODE-Framework
|
d4382d781da7f488a0e7667362a89e8e389468dd
|
[
"MIT"
] | 2
|
2017-08-03T07:15:00.000Z
|
2018-06-18T10:32:53.000Z
|
01_Develop/libXMCocos2D/Source/extensions/CCScrollView/CCSorting.cpp
|
mcodegeeks/OpenKODE-Framework
|
d4382d781da7f488a0e7667362a89e8e389468dd
|
[
"MIT"
] | null | null | null |
01_Develop/libXMCocos2D/Source/extensions/CCScrollView/CCSorting.cpp
|
mcodegeeks/OpenKODE-Framework
|
d4382d781da7f488a0e7667362a89e8e389468dd
|
[
"MIT"
] | 2
|
2019-03-04T22:57:42.000Z
|
2020-03-06T01:32:26.000Z
|
/* --------------------------------------------------------------------------
*
* File CCSorting.cpp
* Author Y.H Mun
*
* --------------------------------------------------------------------------
*
* Copyright (c) 2010-2013 cocos2d-x.org
* Copyright (c) 2010 Sangwoo Im
*
* http://www.cocos2d-x.org
*
* --------------------------------------------------------------------------
*
* Copyright (c) 2010-2013 XMSoft. All rights reserved.
*
* Contact Email: xmsoft77@gmail.com
*
* --------------------------------------------------------------------------
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
* -------------------------------------------------------------------------- */
#include "Precompiled.h"
#include "extensions/CCScrollView/CCSorting.h"
#include "cocoa/CCString.h"
NS_CC_BEGIN
class CCSortedObject : public CCObject, public CCSortableObject
{
public :
CCSortedObject ( KDvoid )
{
m_uObjectID = 0;
}
virtual KDvoid setObjectID ( KDuint uObjectID )
{
m_uObjectID = uObjectID;
}
virtual KDuint getObjectID ( KDvoid )
{
return m_uObjectID;
}
private :
KDuint m_uObjectID;
};
CCArrayForObjectSorting::CCArrayForObjectSorting ( KDvoid ) : CCArray ( )
{
}
KDvoid CCArrayForObjectSorting::insertSortedObject ( CCSortableObject* pObject )
{
KDuint uIdx;
CCObject* pObj = dynamic_cast<CCObject*> ( pObject );
CCAssert ( pObj, "Invalid parameter." );
uIdx = this->indexOfSortedObject ( pObject );
this->insertObject ( pObj, uIdx );
}
KDvoid CCArrayForObjectSorting::removeSortedObject ( CCSortableObject* pObject )
{
if ( this->count ( ) == 0 )
{
return;
}
KDuint uIdx;
CCSortableObject* pFoundObj;
uIdx = this->indexOfSortedObject ( pObject );
if ( uIdx < this->count ( ) && uIdx != CC_INVALID_INDEX )
{
pFoundObj = dynamic_cast<CCSortableObject*> ( this->objectAtIndex ( uIdx ) );
if ( pFoundObj->getObjectID ( ) == pObject->getObjectID ( ) )
{
this->removeObjectAtIndex ( uIdx );
}
}
}
KDvoid CCArrayForObjectSorting::setObjectID_ofSortedObject ( KDuint uTag, CCSortableObject* pObject )
{
CCSortableObject* pFoundObj;
KDuint uIdx;
uIdx = this->indexOfSortedObject ( pObject );
if ( uIdx < this->count ( ) && uIdx != CC_INVALID_INDEX )
{
pFoundObj = dynamic_cast<CCSortableObject*> ( this->objectAtIndex ( uIdx ) );
CCObject* pObj = dynamic_cast<CCObject*> ( pFoundObj );
pObj->retain ( );
if ( pFoundObj->getObjectID ( ) == pObject->getObjectID ( ) )
{
this->removeObjectAtIndex ( uIdx );
pFoundObj->setObjectID ( uTag );
this->insertSortedObject ( pFoundObj );
pObj->release ( );
}
else
{
pObj->release ( );
}
}
}
CCSortableObject* CCArrayForObjectSorting::objectWithObjectID ( KDuint uTag )
{
if ( this->count ( ) == 0 )
{
return KD_NULL;
}
KDuint uIdx;
CCSortableObject* pFoundObj;
pFoundObj = new CCSortedObject ( );
pFoundObj->setObjectID ( uTag );
uIdx = this->indexOfSortedObject ( pFoundObj );
( (CCSortedObject*) pFoundObj )->release ( );
pFoundObj = KD_NULL;
if ( uIdx < this->count ( ) && uIdx != CC_INVALID_INDEX )
{
pFoundObj = dynamic_cast<CCSortableObject*> ( this->objectAtIndex ( uIdx ) );
if ( pFoundObj->getObjectID ( ) != uTag )
{
pFoundObj = KD_NULL;
}
}
return pFoundObj;
}
KDuint CCArrayForObjectSorting::indexOfSortedObject ( CCSortableObject* pObject )
{
KDuint uIdx = 0;
if ( pObject )
{
// FIXME: need to use binary search to improve performance
CCObject* pObj = KD_NULL;
KDuint uPrevObjectID = 0;
KDuint uOfSortObjectID = pObject->getObjectID ( );
CCARRAY_FOREACH ( this, pObj )
{
CCSortableObject* pSortableObj = dynamic_cast<CCSortableObject*> ( pObj );
KDuint uCurObjectID = pSortableObj->getObjectID ( );
if ( ( uOfSortObjectID == uCurObjectID ) || ( uOfSortObjectID >= uPrevObjectID && uOfSortObjectID < uCurObjectID ) )
{
break;
}
uPrevObjectID = uCurObjectID;
uIdx++;
}
}
else
{
uIdx = CC_INVALID_INDEX;
}
return uIdx;
}
NS_CC_END
| 27.415385
| 128
| 0.559858
|
mcodegeeks
|
ec29a544d9100b3387e11d9bc03102fb43674314
| 329
|
hh
|
C++
|
src/UsageEnvironment/include/UsageEnvironment_version.hh
|
RayanWang/Live555
|
3a8b2998e5872326e4edb96e6e7dc46dc1d16af4
|
[
"MIT"
] | 5
|
2018-04-09T02:03:33.000Z
|
2022-03-26T16:17:52.000Z
|
src/UsageEnvironment/include/UsageEnvironment_version.hh
|
RayanWang/Live555
|
3a8b2998e5872326e4edb96e6e7dc46dc1d16af4
|
[
"MIT"
] | null | null | null |
src/UsageEnvironment/include/UsageEnvironment_version.hh
|
RayanWang/Live555
|
3a8b2998e5872326e4edb96e6e7dc46dc1d16af4
|
[
"MIT"
] | null | null | null |
// Version information for the "UsageEnvironment" library
// Copyright (c) 1996-2014 Live Networks, Inc. All rights reserved.
#ifndef _USAGEENVIRONMENT_VERSION_HH
#define _USAGEENVIRONMENT_VERSION_HH
#define USAGEENVIRONMENT_LIBRARY_VERSION_STRING "2014.12.17"
#define USAGEENVIRONMENT_LIBRARY_VERSION_INT 1418774400
#endif
| 29.909091
| 68
| 0.835866
|
RayanWang
|
ec2bc096ac8d02bf32f1e3d46ed2a7005d6d0383
| 3,663
|
cpp
|
C++
|
Builds/vs2013/Task2/unittest1.cpp
|
AJ-Moore/AIStates
|
b2bc31d7d3cbec25b4efacbe9ae6c9940e8e68e4
|
[
"MIT"
] | null | null | null |
Builds/vs2013/Task2/unittest1.cpp
|
AJ-Moore/AIStates
|
b2bc31d7d3cbec25b4efacbe9ae6c9940e8e68e4
|
[
"MIT"
] | null | null | null |
Builds/vs2013/Task2/unittest1.cpp
|
AJ-Moore/AIStates
|
b2bc31d7d3cbec25b4efacbe9ae6c9940e8e68e4
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "CppUnitTest.h"
#include <AI.h>
#include <FSM.h>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace Task2
{
TEST_CLASS(UnitTest1)
{
public:
//Test that the AI Starting State is Idle
TEST_METHOD(StartState)
{
AI ai(false, 0, 0);
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Idle);
}
//Check Idle to Observe Transition.
TEST_METHOD(IdleToObserve)
{
//create the AI -> Sets Can See Player to true
AI ai(true, 0, 0);
//check that the current state is in idle
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Idle);
//check after the update that the state has changed to Observe
ai.update();
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Observe);
}
//Checks the transition between the Observe and Idle states.
TEST_METHOD(ObserveToIdle)
{
AI ai(true, 0, 0);
ai.update();
ai.canSeePlayer = false;
ai.update();
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Idle);
}
//Observe to Combat Test
TEST_METHOD(ObserveToCombat){
AI ai(true, 70, 0);
ai.update();//state should now be observe.
ai.update();//state should still be observe.
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Observe);
//change health to 71 and ammo to 1
ai.health = 71;
ai.ammunition = 1;
ai.update();//state should now be combat
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Combat);
}
//Combat to Retreat Test.
TEST_METHOD(CombatToRetreat){
AI ai(true, 71, 1);
ai.update();//state should now be observe.
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Observe);
ai.update();//state should now be combat
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Combat);
ai.ammunition = 0;
ai.update();
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Retreat);
}
//Combat to Retreat Test.
TEST_METHOD(CombatToDead){
AI ai(true, 71, 1);
ai.update();//state should now be observe.
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Observe);
ai.update();//state should now be combat
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Combat);
ai.health = 0;
ai.update();
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Dead);
}
//Combat to Retreat Test.
TEST_METHOD(RetreatToDead){
AI ai(true, 71, 1);
ai.update();//state should now be observe.
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Observe);
ai.update();//state should now be combat
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Combat);
ai.ammunition = 0;
ai.update();
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Retreat);
ai.health = 0;
ai.update();
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Dead);
}
TEST_METHOD(RetreatToIdle){
AI ai(true, 71, 1);
ai.update();//state should now be observe.
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Observe);
ai.update();//state should now be combat
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Combat);
ai.ammunition = 0;
ai.update();
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Retreat);
ai.canSeePlayer = false;
ai.update();
Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Idle);
}
};
}
| 31.577586
| 83
| 0.670762
|
AJ-Moore
|
ec2c9e529ef42d3a903fcae5273beb2dec55545d
| 276
|
cpp
|
C++
|
Char.cpp
|
RafelNunes/ifsc-programacao
|
40622fb1a5496e09f4800220e293385468fef323
|
[
"MIT"
] | null | null | null |
Char.cpp
|
RafelNunes/ifsc-programacao
|
40622fb1a5496e09f4800220e293385468fef323
|
[
"MIT"
] | null | null | null |
Char.cpp
|
RafelNunes/ifsc-programacao
|
40622fb1a5496e09f4800220e293385468fef323
|
[
"MIT"
] | null | null | null |
#include<stdio.h>
#include<stdlib.h>
int main(void){
char letra1, letra2;
printf("Digite um caracter: ");
scanf("%c", &letra1);
while(letra1 != 'X')
{printf("Digite um caracter: ");
scanf(" %c", &letra1);
}
printf("Letra1: %c Letra2: %c\n", letra1, letra2);
}
| 16.235294
| 51
| 0.605072
|
RafelNunes
|