text
stringlengths 8
6.88M
|
|---|
#include <iostream>
#include <vector>
using namespace std;
vector<pair<int, int>> t;
pair<int, int> combine(pair<int, int> a, pair<int, int> b) {
if (a.first < b.first) {
return a;
} else if (a.first > b.first) {
return b;
}
return make_pair(a.first, a.second + b.second);
}
void set(int id, int value, int i, int l, int r) {
if (l == r - 1) {
t[i].first = value;
return;
}
if (id < (l+r)/2) {
set(id, value, 2*i+1, l, (l+r)/2);
} else {
set(id, value, 2*i+2, (l+r)/2, r);
}
t[i] = combine(t[2*i+1], t[2*i+2]);
}
pair<int, int> get(int a, int b, int i, int l, int r) {
if (a >= r || b <= l) {
return make_pair(INT32_MAX, 0);
} else if (a <= l && b >= r) {
return t[i];
} else {
return combine(get(a, b, 2*i+1, l, (l+r)/2),
get(a, b, 2*i+2, (l+r)/2, r));
}
}
int main() {
int n, m;
cin >> n >> m;
int x = 1;
while (x < n) {
x *= 2;
}
vector<int> a(x);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = n; i < x; i++) {
a[i] = INT32_MAX;
}
t.resize(2*x-1);
for (int i = 0; i < x; i++) {
t[x - 1 + i].first = a[i];
t[x - 1 + i].second = 1;
}
for (int i = x - 2; i >= 0; i--) {
t[i] = combine(t[2*i+1], t[2*i+2]);
}
for (int i = 0; i < m; i++) {
int mode;
cin >> mode;
if (mode == 1) {
int id, value;
cin >> id >> value;
set(id, value, 0, 0, x);
} else {
int a, b;
cin >> a >> b;
pair<int, int> c = get(a, b, 0, 0, x);
cout << c.first << " " << c.second << endl;
}
}
}
|
#include <stdio.h>
#include <stdlib.h>
template<typename T>
T max(const T arr[], int size) {
T maxElem=arr[0];
for (int i=0;i<size;i++)
if(arr[i]>maxElem)
maxElem=arr[i];
return maxElem;
}
int main(){
int a[] = {1,2,4,8,7};
int b = max(a,sizeof(a)/sizeof(int));
printf("最大数组元素:%d",b);
system("pause");
return 0;
}
//最大数组元素:8
//函数模板也可显示实例化:template int max<int>(const int[],int);
|
/**
* @file orbitSimStruct.h
* @brief This file contains all structures definition used by the orbit Simulator.
* @author Giuseppe Romeo
* @date Created: Nov 15, 2005
*
* $Header: /nfs/slac/g/glast/ground/cvs/orbitSim/orbitSim/orbitSimStruct.h,v 1.2 2008/09/25 17:20:28 vernaleo Exp $
*/
#ifndef orbitSimStruct_h
#define orbitSimStruct_h
#include <string>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Structure that contains all the necessary parameters
*
* This structure contains all the parameters needed
* by the orbit simulator
*
* @author Giuseppe Romeo
* @date Created: Nov 15, 2005
* @date Last Modified: May 04, 2009
*/
typedef struct {
/// starting time in MJD
double start_MJD;
/// stopping time in MJD
double stop_MJD;
/// Timeline file name, path included
std::string TLname;
/// Timeline type (TAKO, ASFLOWN, or SINGLE)
std::string TLtype;
/// Ephemeris file name, path included
std::string EPHname;
/// function name to read/propagate ephemeris
std::string EPHfunc;
/// conversion factor to convert in Km
double Units;
/// Ephemeris resolution, and therefore
/// orbit simulator resolution in minutes
double Resolution;
/// Initial RA
double Ira;
/// Initial DEC
double Idec;
/// Output file where attitude will be written
/// in FT2 format
std::string OutFile;
/// Optional file used for ascii dump
std::string OptFile;
/// SAA file definition
std::string saafile;
/// Flag which is used to decide if Earth avoidance should be enabled, default is yes.
int occflag;
/// Earth Avoidance Angle value, default is 30 degrees
double EAA;
///Earth LIMB TRACING exclusion start time (MJD)
double ELT_OFF_START;
///Earth LIMB TRACING exclusion stop time (MJD)
double ELT_OFF_STOP;
/// Verbosity level
int chat;
/// Debug mode
bool debug;
} InitI;
/**
* @brief Structure that contains parameters for the profile survey
*
* This structure contains all the parameters that
* specify a profiled survey
*
* @author Giuseppe Romeo
* @date Created: Nov 15, 2005
* @date Last Modified: Feb 08, 2006
*/
typedef struct {
/// this is the ROCKSTART in mjd, or when the profile survey cycle is sopposed to begin
double epoch;
/// default offset when ROCKSTART is in the future
double defofst;
/// array containing 17 angles in degrees for the offset
double ofsts[17];
/// array containing 17 time in seconds
double times[17];
} SurProf;
/**
* @brief Structure that contains time parameters
*
* This structure contains all time parameters
*
* @author Giuseppe Romeo
* @date Created: Nov 15, 2005
* @date Last Modified: Feb 08, 2006
*/
typedef struct {
/// year
int yr;
/// month
int mo;
/// day
int dy;
/// hour
int hr;
/// minute
int mn;
/// sec
int sc;
/// millisec
float ms;
} AtTime;
/**
* @brief Structure that contains Two Line Elements (TLE) parameters
*
* This structure contains all the parameters
* contained in the NORAD Two Line Element file
*
* @author Giuseppe Romeo
* @date Created: Nov 15, 2005
* @date Last Modified: Feb 08, 2006
*/
typedef struct atElemTle{
/// Time structure
AtTime tm;
/// Time stamp in MJD when the parameters are good from
double mjd;
/// Fraction of second of the time stamp
double isc;
/// Satellite Number
int SatNum,
/// Revolution number at epoch
EpochRev;
///First time derivative of mean motion.
double xndt2o,
///Second time derivative of mean motion.
xndd6o,
///BSTAR drag term
bstar,
///Inclination in the xplane
xincl,
///Right ascension of the ascending node.
xnodeo,
///Eccentricity.
eo,
///Argument of perigee.
omegao,
///Mean anomaly.
xmo,
///Mean motion.
xno;
/// exponential part of xndd6o
int iexp,
/// exponential part of bstar
ibexp;
} atElemTle;
/**
* @brief Structure that contains 3D vector plus its magnitude
*
*
* @author Giuseppe Romeo
* @date Created: Nov 15, 2005
* @date Last Modified: Mar 14, 2007
*/
typedef struct vector {
/// 3-dimensional vector, the fourth element contains the magnitude
double v[4];
}vector ;
/// Three-dimensional Cartesian Vector
typedef double AtVect[3];
/// 3 x 3 Rotation Matrix
typedef double AtRotMat[3][3];
/**
* @brief Structure that contains 3 Euler angles
*
* Euler angle notation of rotation. (usually z-y-z)
*
* @author Giuseppe Romeo
* @date Created: Nov 15, 2005
* @date Last Modified: Feb 08, 2006
*/
typedef struct {
/// First Euler Angle (radian)
double phi;
/// Second Euler Angle (radian)
double theta;
/// Third Euler Angle (radian)
double psi;
} AtEulerAng;
/**
* @brief Three-dimensional Vector in Polar coordinate.
*
*
* @author Giuseppe Romeo
* @date Created: Nov 15, 2005
* @date Last Modified: Feb 08, 2006
*/
typedef struct {
/// radial component
double r;
/// longitude or R.A. (radian)
double lon;
/// latitude or declination (radian)
double lat;
} AtPolarVect;
/*
typedef struct EphemData {
/// time stamp in MJD format
double *MJD;
/// array for the X position in EC system
double *X;
/// array for the Y position in EC system
double *Y;
/// array for the Z position in EC system
double *Z;
/// array for the Latitude in EC system
double *Lat;
/// array for the Longitude in EC system
double *Long;
/// array for the Height in EC system
double *Alt;
/// array for the velocity compenent in RA in EC system
double *VelRA;
/// array for the velocity compenent in DEC in EC system
double *VelDEC;
/// Ephemeredis Period, not used with the available Ephemeredis
double Period,
/// SemiMajorAxis, not used with the available Ephemeredis
SemiMajorAxis;
/// Number of entries in each array
int ent;
} EphemData;
*/
#ifdef __cplusplus
}
#endif
#endif
|
#include <iostream>
int main()
{
std::cout << (char)30 << (char)30 << (char)30 << (char)30 << (char)30 << (char)30 << (char)30 << (char)176 << 'E' << std::endl;
std::cout << (char)30 << (char)30 << (char)30 << (char)30 << (char)30 << (char)5 << (char)5 << (char)176 << (char)176 << std::endl;
std::cout << (char)30 << (char)30 << (char)5 << (char)30 << (char)30 << (char)5 << (char)5 << (char)176 << (char)176 << std::endl;
std::cout << (char)30 << (char)5 << (char)5 << (char)5 << (char)30 << (char)30 << (char)5 << (char)176 << (char)61 << std::endl;
std::cout << (char)30 << (char)5 << (char)5 << (char)176 << (char)61 << (char)30 << (char)5 << (char)61 << (char)176 << std::endl;
std::cout << (char)30 << 'C' << 'A' << (char)176 << (char)176 << (char)61 << (char)61 << (char)30 << (char)176 << std::endl;
std::cout << (char)5 << (char)176 << (char)176 << (char)176 << (char)176 << (char)30 << (char)30 << (char)5 << (char)5 << std::endl;
return 0;
}
|
/*
I did a brute force approach.
I found, manually, the move to make the least amount of moves and used this program to prove it.
I go thorught my steps and them find alternate moves along the way to see if there a shorter path
*/
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include "board.h"
#include <time.h>
using namespace std;
int main()
{
//variables
gameboard b;
int count =0;
int attempts =0;
int min = 29;
int dir = 0;
int moves = 0;
//set some random numbers
srand(time(NULL));
//loop
while(true){
//go through the moves a knight could move
dir = rand()%16;
if(attempts == 0){
if(count >= 0){
b.rightup();
attempts++;
}
if(count >= 1){
b.ul();
attempts++;
}
if(count >= 2){
b.rightup();
attempts++;
}
if(count >= 3){
b.leftup2();
attempts++;
}
if(count >= 4){
b.ld();
attempts++;
}
if(count >= 5){
b.leftup2();
attempts++;
}
if(count >= 6){
b.leftdown();
attempts++;
}
if(count >= 7){
b.dr();
attempts++;
}
if(count >= 8){
b.leftdown();
attempts++;
}
if(count >= 9){
b.rightdown2();
attempts++;
}
if(count >= 10){
b.ru();
attempts++;
}
if(count >= 11){
b.rightdown2();
attempts++;
}
if(count >= 12){
b.ul();
attempts++;
}
if(count >= 13){
b.rightup();
attempts++;
}
if(count >= 14){
b.ul();
attempts++;
}
if(count >= 15){
b.ld();
attempts++;
}
if(count >= 16){
b.leftup2();
attempts++;
}
if(count >= 17){
b.dr();
attempts++;
}
if(count >= 18){
b.leftdown();
attempts++;
}
if(count >= 19){
b.rightdown2();
attempts++;
}
if(count >= 20){
b.ru();
attempts++;
}
if(count >= 21){
b.ur();
attempts++;
}
if(count >= 22){
b.leftup2();
attempts++;
}
if(count >= 23){
b.ld();
attempts++;
}
if(count >= 24){
b.dr();
attempts++;
}
if(count >= 25){
b.rightup();
attempts++;
}
if(count >= 26){
b.leftdown();
attempts++;
}
b.moved = false;
}
if(dir == 1 && b.k[0]>1 && b.k[1] < 7 && b.emp((b.k[0]-2),(b.k[1]+1)) )
b.rightup();
else if(dir == 8 && b.k[0]>1 && b.k[1] > 0 && b.emp((b.k[0]-2),(b.k[1]+1)) )
b.ul();
else if(dir == 0 && b.k[0]>1 && b.k[1] > 0 && b.emp((b.k[0]-2),(b.k[1]-1)) )
b.leftup();
else if(dir == 9 && b.k[0]>1 && b.k[1] < 7 && b.emp((b.k[0]-2),(b.k[1]-1)) )
b.ur();
else if(dir == 2 && b.k[0]<6 && b.k[1] > 0 && b.emp((b.k[0]+2),(b.k[1]-1)) )
b.leftdown();
else if(dir == 10 && b.k[0]<6 && b.k[1] > 0 && b.emp((b.k[0]+2),(b.k[1]-1)) )
b.dl();
else if(dir == 3 && b.k[0]<6 && b.k[1] < 7 && b.emp((b.k[0]+2),(b.k[1]+1)) )
b.rightdown();
else if(dir == 11 && b.k[0]<6 && b.k[1] < 7 && b.emp((b.k[0]+2),(b.k[1]+1)) )
b.dr();
else if(dir == 4 && b.k[0]>0 && b.k[1] > 1 && b.emp((b.k[0]-1),(b.k[1]-2)) )
b.leftup2();
else if(dir == 12 && b.k[0]>0 && b.k[1] > 1 && b.emp((b.k[0]-1),(b.k[1]-2)) )
b.lu();
else if(dir == 5 && b.k[0]>0 && b.k[1] < 6 && b.emp((b.k[0]-1),(b.k[1]+2)) )
b.rightup2();
else if(dir == 13 && b.k[0]>0 && b.k[1] < 6 && b.emp((b.k[0]-1),(b.k[1]+2)) )
b.ru();
else if(dir == 6 && b.k[0]<7 && b.k[1] > 1 && b.emp((b.k[0]+1),(b.k[1]-2)) )
b.leftdown2();
else if(dir == 14 && b.k[0]<7 && b.k[1] > 1 && b.emp((b.k[0]+1),(b.k[1]-2)) )
b.ld();
else if(dir == 7 && b.k[0]<7 && b.k[1] < 6 && b.emp((b.k[0]+1),(b.k[1]+2)) )
b.rightdown2();
else if(dir == 15 && b.k[0]<7 && b.k[1] < 6 && b.emp((b.k[0]+1),(b.k[1]+2)) )
b.rd();
if(moves > 100){
if(dir == 0 && b.k[0]>1 && b.k[1] > 0)
b.leftup();
else if(dir == 8 && b.k[0]>1 && b.k[1] > 0)
b.ul();
else if(dir == 1 && b.k[0]>1 && b.k[1] < 7)
b.rightup();
else if(dir == 9 && b.k[0]>1 && b.k[1] < 7)
b.ur();
else if(dir == 2 && b.k[0]<6 && b.k[1] > 0)
b.leftdown();
else if(dir == 10 && b.k[0]<6 && b.k[1] > 0)
b.dl();
else if(dir == 3 && b.k[0]<6 && b.k[1] < 7)
b.rightdown();
else if(dir == 11 && b.k[0]<6 && b.k[1] < 7)
b.dr();
else if(dir == 4 && b.k[0]>0 && b.k[1] > 1)
b.leftup2();
else if(dir == 12 && b.k[0]>0 && b.k[1] > 1)
b.lu();
else if(dir == 5 && b.k[0]>0 && b.k[1] < 6)
b.rightup2();
else if(dir == 13 && b.k[0]>0 && b.k[1] < 6)
b.ru();
else if(dir == 6 && b.k[0]<7 && b.k[1] > 1)
b.leftdown2();
else if(dir == 14 && b.k[0]<7 && b.k[1] > 1)
b.ld();
else if(dir == 7 && b.k[0]<7 && b.k[1] < 6)
b.rightdown2();
else if(dir == 15 && b.k[0]<7 && b.k[1] < 6)
b.rd();
}
moves++;
if(b.moved){
attempts++;
b.moved = false;
moves = 0;
}
if( b.win() ){
count++;
system("cls");
b.reset();
cout<<"Current min: "<<min<<" \ncurrent moves it takes "<<attempts;
if(min>attempts){
min = attempts;
}
srand(time(NULL));
attempts = 0;
}
if (attempts > 50){
b.reset();
attempts = 0;
count++;
}
if(count == 28)
count =0;
}
system("PAUSE");
return EXIT_SUCCESS;
}
|
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[5],i;
int *p=arr;
printf("Enter five numbers separated by space:");
scanf("%d%d%d%d%d",p,p+1,p+2,p+3,p+4);
printf("Your numbers are:\n");
for(i=0;i<5;i++)
printf("%d\n",arr[i]);
getch();
return 0;
}
|
#include "userinfo.h"
UserInfo::UserInfo()
{
}
int UserInfo::ID()
{
return m_id;
}
void UserInfo::ID(int id)
{
m_id = id;
}
QString UserInfo::Name()
{
return m_name;
}
void UserInfo::Name(QString name)
{
m_name = name;
}
void UserInfo::NickyName(QString nicky_name)
{
m_nicky_name = nicky_name;
}
QString UserInfo::NickyName()
{
return m_nicky_name;
}
QString UserInfo::Password()
{
return m_passwd;
}
void UserInfo::Password(QString passwd)
{
m_passwd = passwd;
}
|
/***************************************************************************
Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
2010-2020 DADI ORISTAR TECHNOLOGY DEVELOPMENT(BEIJING)CO.,LTD
FileName: UDPDemuxer.h
Description: Provides a "Listener" socket for UDP. Blocks on a local IP & port,
waiting for data. When it gets data, it passes it off to a UDPDemuxerTask(RTPStream)
object depending on where it came from.
Comment: copy from Darwin Streaming Server 5.5.5
Author: taoyunxing@dadimedia.com
Version: v1.0.0.1
CreateDate: 2010-08-16
LastUpdate: 2010-08-19
****************************************************************************/
#include "UDPDemuxer.h"
#include <errno.h>
/* 在指定的address/port组合处加入指定的Hash Table entry,返回OS_NoErr;若该address/port组合在Hash Table中已被占用,返回EPERM */
OS_Error UDPDemuxer::RegisterTask(UInt32 inRemoteAddr, UInt16 inRemotePort, UDPDemuxerTask *inTaskP)
{
/* 确保该Hash Table entry存在 */
Assert(NULL != inTaskP);
OSMutexLocker locker(&fMutex);
/* 若由给定的key值去获取相应的Hash Table element时成功了,表示该address/port组合在Hash Table中已被占用 */
if (this->GetTask(inRemoteAddr, inRemotePort) != NULL)
return EPERM;
/* 否则设置该Hash Table entry(注意它原来的数据可能已被改变) */
inTaskP->Set(inRemoteAddr, inRemotePort);
/* 将新建的Hash Table entry加入Hash Table中 */
fHashTable.Add(inTaskP);
return OS_NoErr;
}
/* 在指定的address/port组合处查找Hash Table entry,将其与入参inTaskP比较,若相同,就从Hash Table中删去该
Hash Table entry,返回OS_NoErr;否则返回EPERM */
OS_Error UDPDemuxer::UnregisterTask(UInt32 inRemoteAddr, UInt16 inRemotePort, UDPDemuxerTask *inTaskP)
{
OSMutexLocker locker(&fMutex);
//remove by executing a lookup based on key information
/* 获取Hash Table中该指定键值对应的Hash Table entry */
UDPDemuxerTask* theTask = this->GetTask(inRemoteAddr, inRemotePort);
if ((NULL != theTask) && (theTask == inTaskP))
{
fHashTable.Remove(theTask);
return OS_NoErr;
}
else
return EPERM;
}
/* 注意该函数在上面的RegisterTask/UnregisterTask()都要使用 */
/* 由指定的key值在Hash Table中获取并返回对应的Hash Table元 */
UDPDemuxerTask* UDPDemuxer::GetTask(UInt32 inRemoteAddr, UInt16 inRemotePort)
{
UDPDemuxerKey theKey(inRemoteAddr, inRemotePort);
/* 利用map获取Hash Table元 */
return fHashTable.Map(&theKey);
}
|
/***************************************************************************
Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
2010-2020 DADI ORISTAR TECHNOLOGY DEVELOPMENT(BEIJING)CO.,LTD
FileName: OSCodeFragment.cpp
Description: Provide OS abstraction for loading code fragments(.so/dll).
Comment: copy from Darwin Streaming Server 5.5.5
Author: taoyunxing@dadimedia.com
Version: v1.0.0.1
CreateDate: 2010-08-16
LastUpdate: 2010-08-19
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h> //加载动态库的头文件,用到dlopen()/dlclose()/dlerror()/dlsym()
#include "SafeStdLib.h"
#include "MyAssert.h"
#include "OSCodeFragment.h"
void OSCodeFragment::Initialize()
{
// does nothing...should do any CFM initialization here
}
//加载指定路径的.so,返回库文件描述符
OSCodeFragment::OSCodeFragment(const char* inPath)
: fFragmentP(NULL)
{
fFragmentP = dlopen(inPath, RTLD_NOW | RTLD_GLOBAL); //加载.so,返回库文件描述符
fprintf (stderr, "%s\n", dlerror());
}
OSCodeFragment::~OSCodeFragment()
{
if (fFragmentP == NULL)
return;
dlclose(fFragmentP); //卸载打开的.so库文件
}
/* used in QTSSModule::LoadFromDisk() */
/* 获取当前动态库中指定符号inSymbolName对应的函数入口地址 */
void* OSCodeFragment::GetSymbol(const char* inSymbolName)
{
if (fFragmentP == NULL)
return NULL;
return dlsym(fFragmentP, inSymbolName);//返回指定的.so的库文件描述符fFragmentP中,指定符号inSymbolName对应的函数入口地址
}
|
#include "pch.h"
#include "Mesh.h"
Mesh::Mesh()
{
}
Mesh::~Mesh()
{
if (positions_) delete[] positions_;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
Cube_mesh::Cube_mesh(XMFLOAT3 xmf3Center, XMFLOAT3 xmf3Extents) : Mesh()
{
vertices_ = 8;
float fx = xmf3Extents.x, fy = xmf3Extents.y, fz = xmf3Extents.z;
positions_ = new XMFLOAT3[vertices_];
positions_[0] = XMFLOAT3(-fx + xmf3Center.x, +fy + xmf3Center.y, -fz + xmf3Center.z);
positions_[1] = XMFLOAT3(+fx + xmf3Center.x, +fy + xmf3Center.y, -fz + xmf3Center.z);
positions_[2] = XMFLOAT3(+fx + xmf3Center.x, +fy + xmf3Center.y, +fz + xmf3Center.z);
positions_[3] = XMFLOAT3(-fx + xmf3Center.x, +fy + xmf3Center.y, +fz + xmf3Center.z);
positions_[4] = XMFLOAT3(-fx + xmf3Center.x, -fy + xmf3Center.y, -fz + xmf3Center.z);
positions_[5] = XMFLOAT3(+fx + xmf3Center.x, -fy + xmf3Center.y, -fz + xmf3Center.z);
positions_[6] = XMFLOAT3(+fx + xmf3Center.x, -fy + xmf3Center.y, +fz + xmf3Center.z);
positions_[7] = XMFLOAT3(-fx + xmf3Center.x, -fy + xmf3Center.y, +fz + xmf3Center.z);
}
Cube_mesh::~Cube_mesh()
{
}
/////////////////////////////////////////////////////////////////////////////////////////////////
void FindXYZ(XMFLOAT3* pPositions, UINT nVertices, XMFLOAT3& Center, XMFLOAT3& Extents)
{
XMFLOAT3 MinMaxVertex[2]; // [0] Min, [1] Max
MinMaxVertex[0] = MinMaxVertex[1] = pPositions[0];
for (UINT i = 1; i < nVertices; i++)
{
XMFLOAT3 Position = pPositions[i];
if (Position.x < MinMaxVertex[0].x) MinMaxVertex[0].x = Position.x;
if (Position.y < MinMaxVertex[0].y) MinMaxVertex[0].y = Position.y;
if (Position.z < MinMaxVertex[0].z) MinMaxVertex[0].z = Position.z;
if (Position.x > MinMaxVertex[1].x) MinMaxVertex[1].x = Position.x;
if (Position.y > MinMaxVertex[1].y) MinMaxVertex[1].y = Position.y;
if (Position.z > MinMaxVertex[1].z) MinMaxVertex[1].z = Position.z;
}
Center = Vector3::Add(MinMaxVertex[0], MinMaxVertex[1]);
Center.x /= 2; Center.y /= 2; Center.z /= 2;
Extents = Vector3::Subtract(MinMaxVertex[1], MinMaxVertex[0]);
Extents.x /= 2; Extents.y /= 2; Extents.z /= 2;
}
Standard_mesh::Standard_mesh() : Mesh()
{
}
Standard_mesh::~Standard_mesh()
{
}
void Standard_mesh::load_mesh_from_file(FILE *pfile)
{
BYTE nstrLength;
char pstrToken[64] = { 0 };
type_ |= 0x01;
fread_s(&vertices_, sizeof(UINT), sizeof(int), 1, pfile);
fread_s(&nstrLength, sizeof(BYTE), sizeof(BYTE), 1, pfile);
fread_s(name_, sizeof(char) * 64, sizeof(char), nstrLength, pfile);
while (true)
{
fread_s(&nstrLength, sizeof(BYTE), sizeof(BYTE), 1, pfile);
fread_s(pstrToken, sizeof(char) * 64, sizeof(char), nstrLength, pfile);
pstrToken[nstrLength] = '\0';
if (!strcmp(pstrToken, "<Positions>:"))
{
positions_ = new XMFLOAT3[vertices_];
fread_s(positions_, sizeof(XMFLOAT3) * vertices_, sizeof(XMFLOAT3), vertices_, pfile);
}
else if (!strcmp(pstrToken, "<TextureCoords>:"))
{
XMFLOAT2* texture_coords0 = new XMFLOAT2[vertices_];
fread_s(texture_coords0, sizeof(XMFLOAT2) * vertices_, sizeof(XMFLOAT2), vertices_, pfile);
delete texture_coords0;
}
else if (!strcmp(pstrToken, "<Normals>:"))
{
XMFLOAT3* normals = new XMFLOAT3[vertices_];
fread_s(normals, sizeof(XMFLOAT3) * vertices_, sizeof(XMFLOAT3), vertices_, pfile);
delete normals;
}
else if (!strcmp(pstrToken, "<Binormals>:"))
{
XMFLOAT3* binormals = new XMFLOAT3[vertices_];
fread_s(binormals, sizeof(XMFLOAT3) * vertices_, sizeof(XMFLOAT3), vertices_, pfile);
delete binormals;
}
else if (!strcmp(pstrToken, "<Tangents>:"))
{
XMFLOAT3* tangents = new XMFLOAT3[vertices_];
fread_s(tangents, sizeof(XMFLOAT3) * vertices_, sizeof(XMFLOAT3), vertices_, pfile);
delete tangents;
}
else if (!strcmp(pstrToken, "<SubMeshes>:"))
{
fread_s(&submeshes_, sizeof(int), sizeof(int), 1, pfile);
subsetindices_ = new int[submeshes_];
subsetindices_array_ = new UINT*[submeshes_];
if (submeshes_ > 0)
{
for (int i = 0; i < submeshes_; i++)
{
fread_s(&nstrLength, sizeof(BYTE), sizeof(BYTE), 1, pfile);
fread_s(pstrToken, sizeof(char) * 64, sizeof(char), nstrLength, pfile);
pstrToken[nstrLength] = '\0';
if (!strcmp(pstrToken, "<SubMesh>:"))
{
fread_s(&subsetindices_[i], sizeof(int), sizeof(int), 1, pfile);
if (subsetindices_[i] > 0)
{
subsetindices_array_[i] = new UINT[subsetindices_[i]];
fread_s(subsetindices_array_[i], sizeof(int) * subsetindices_[i], sizeof(int), subsetindices_[i], pfile);
}
}
}
}
}
else if (!strcmp(pstrToken, "</Mesh>"))
{
break;
}
}
XMFLOAT3 xmf3Center;
XMFLOAT3 xmf3Extents;
FindXYZ(positions_, vertices_, xmf3Center, xmf3Extents);
set_aabb(xmf3Center, xmf3Extents);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
#ifndef EFECTO_COLISION_RECOGEDOR_H
#define EFECTO_COLISION_RECOGEDOR_H
#include "../../interfaces/efecto_colision_recogedor_i.h"
#include "../jugador.h"
#include "../sistemas/contador_tiempo.h"
namespace App_Juego_Logica
{
class Efecto_colision_recogedor:
public App_Interfaces::Efecto_colision_recogedor_I
{
//////////////////////////
//Interface pública.
public:
Efecto_colision_recogedor(App_Juego_Sistemas::Contador_tiempo& t, App_Juego::Jugador& j);
virtual const App_Interfaces::Espaciable& obtener_espaciable()const {return jugador;}
virtual bool puede_recoger_salud();
virtual void sumar_tiempo(float v);
virtual void sumar_salud(float v);
virtual void recibir_impacto(float);
virtual bool es_jugador_aterrizado() const {return jugador.es_aterrizado();}
virtual void marcar_como_salida_nivel() {salida_nivel=true;}
virtual bool es_salida_nivel() const {return salida_nivel;}
///////////////////////////
//Internas...
private:
bool salida_nivel;
App_Juego_Sistemas::Contador_tiempo& tiempo;
App_Juego::Jugador& jugador;
};
}
#endif
|
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include "opencv2/core/core.hpp"
using namespace cv;
using namespace std;
int main()
{
VideoCapture vid(0);
int i, j;
Mat temp, a;
/* createTrackbar("Low", "Vid", &x, 1000);
createTrackbar("High", "Vid", &y, 1000);
*/
namedWindow("Vid", WINDOW_AUTOSIZE);
while (1)
{
vid.read(temp);
a = temp.clone();
Mat b(a.rows, a.cols, CV_8UC3, Scalar(255, 255, 255));
Mat c(a.rows, a.cols, CV_8UC1, Scalar(255));
for (i = 0; i < a.rows; i++)
{
for (j = 0; j < a.cols; j++)
{
b.at<Vec3b>(i, j)[0] = a.at<Vec3b>(i, a.cols - 1 - j)[0];
b.at<Vec3b>(i, j)[1] = a.at<Vec3b>(i, a.cols - 1 - j)[1];
b.at<Vec3b>(i, j)[2] = a.at<Vec3b>(i, a.cols - 1 - j)[2];
}
}
Canny(b, c, 110, 140, 3);
imshow("Vid", c);
int z = waitKey(1);
if (z == (int) 'e')
break;
}
return 0;
}
|
#ifndef DeviceBuzzer_h
#define DeviceBuzzer_h
#include "Arduino.h"
#include "../ArduinoJson/ArduinoJson.h"
#define BUZZER_PIN 13 // D7 => 13
namespace ART
{
class ESPDevice;
class DeviceBuzzer
{
public:
DeviceBuzzer(ESPDevice* espDevice);
~DeviceBuzzer();
static void create(DeviceBuzzer* (&deviceBuzzer), ESPDevice* espDevice);
void test();
private:
ESPDevice * _espDevice;
};
}
#endif
|
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
//#include "config.h"
//#include "sshbuf.h"
#include "sftp-common.h"
#include "sftp-pgsql-plugin-store.h"
//:#define SSHDIR "/etc/ssh"
int main(int argc, char ** argv)
{
int home_dir_handle;
int rc = sftp_cf_open_dir(1, "/home/mskelton", &home_dir_handle);
if (rc)
{
std::cerr << "Encountered error in open_dir '/home/mskelton'; aborting" << std::endl;
exit(1);
}
int read_handle;
rc = sftp_cf_open_file(2, "/home/mskelton/foo.txt", 600, OpenModes::READ, &read_handle);
if (rc)
{
std::cerr << "Encountered error in open_file '/home/mskelton/foo.txt'; aborting" << std::endl;
exit(1);
}
int data_len;
// Read from open file handle
u_char rdbuff[32768];
rc = sftp_cf_read(3, std::to_string(read_handle).c_str(), read_handle, 0, sizeof(rdbuff), rdbuff, &data_len);
if (rc)
{
std::cerr << "Encountered error in readi: '/home/mskelton/foo.txt'; aborting" << std::endl;
exit(1);
}
std::cout << "Successfully read file data from '/home/mskelton/foo.txt': " << rdbuff << std::endl;
int write_handle;
rc = sftp_cf_open_file(4, "/home/mskelton/bar.txt", 600, OpenModes::CREATE | OpenModes::WRITE, &write_handle);
if (rc)
{
std::cerr << "Encountered error in open_file '/home/mskelton/bar.txt'; aborting" << std::endl;
exit(1);
}
// Write to open file handle
u_char wrtbuff[4] = {0x37, 0x38, 0x39, 0x40};
rc = sftp_cf_write(5, std::to_string(write_handle).c_str(), write_handle, 0, sizeof(wrtbuff), wrtbuff, &data_len);
if (rc)
{
std::cerr << "Encountered error in write: '/home/mskelton/bar.txt'; aborting" << std::endl;
exit(1);
}
std::cout << "Successfully wrote file data to '/home/mskelton/bar.txt': " << wrtbuff << std::endl;
rc = sftp_cf_close(6, read_handle);
rc = sftp_cf_close(7, write_handle);
rc = sftp_cf_close(8, home_dir_handle);
}
|
//**************************************************************************
//**
//** See jlquake.txt for copyright info.
//**
//** 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 3
//** 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
//** included (gnu.txt) GNU General Public License for more details.
//**
//**************************************************************************
#include "local.h"
#include "../quake3/local.h"
#include "../wolfsp/local.h"
#include "../wolfmp/local.h"
#include "../et/local.h"
#include "../botlib/local.h"
#include "../public.h"
#include "../../common/Common.h"
#include "../../common/common_defs.h"
#include "../../common/strings.h"
int bot_enable;
int SVT3_BotAllocateClient( int clientNum ) {
int i;
client_t* cl;
// Arnout: added possibility to request a clientnum
if ( clientNum > 0 ) {
if ( clientNum >= sv_maxclients->integer ) {
return -1;
}
cl = &svs.clients[ clientNum ];
if ( cl->state != CS_FREE ) {
return -1;
} else {
i = clientNum;
}
} else {
// find a client slot
for ( i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++ ) {
// Wolfenstein, never use the first slot, otherwise if a bot connects before the first client on a listen server, game won't start
if ( !( GGameType & GAME_Quake3 ) && i < 1 ) {
continue;
}
// done.
if ( cl->state == CS_FREE ) {
break;
}
}
}
if ( i == sv_maxclients->integer ) {
return -1;
}
cl->q3_entity = SVT3_EntityNum( i );
if ( GGameType & GAME_WolfSP ) {
cl->ws_gentity = SVWS_GentityNum( i );
} else if ( GGameType & GAME_WolfMP ) {
cl->wm_gentity = SVWM_GentityNum( i );
} else if ( GGameType & GAME_ET ) {
cl->et_gentity = SVET_GentityNum( i );
} else {
cl->q3_gentity = SVQ3_GentityNum( i );
}
cl->q3_entity->SetNumber( i );
cl->state = CS_ACTIVE;
cl->q3_lastPacketTime = svs.q3_time;
cl->netchan.remoteAddress.type = NA_BOT;
cl->rate = 16384;
return i;
}
void SVT3_BotFreeClient( int clientNum ) {
if ( clientNum < 0 || clientNum >= sv_maxclients->integer ) {
common->Error( "SVT3_BotFreeClient: bad clientNum: %i", clientNum );
}
client_t* cl = &svs.clients[ clientNum ];
cl->state = CS_FREE;
cl->name[ 0 ] = 0;
if ( cl->q3_entity ) {
cl->q3_entity->SetSvFlags( cl->q3_entity->GetSvFlags() & ~Q3SVF_BOT );
}
}
int SVT3_BotLibSetup() {
if ( !bot_enable ) {
return 0;
}
if ( GGameType & GAME_ET ) {
static Cvar* bot_norcd;
static Cvar* bot_frameroutingupdates;
// RF, set RCD calculation status
bot_norcd = Cvar_Get( "bot_norcd", "0", 0 );
BotLibVarSet( "bot_norcd", bot_norcd->string );
// RF, set AAS routing max per frame
if ( SVET_GameIsSinglePlayer() ) {
bot_frameroutingupdates = Cvar_Get( "bot_frameroutingupdates", "9999999", 0 );
} else {
// more restrictive in multiplayer
bot_frameroutingupdates = Cvar_Get( "bot_frameroutingupdates", "1000", 0 );
}
BotLibVarSet( "bot_frameroutingupdates", bot_frameroutingupdates->string );
// added single player
return BotLibSetup( ( SVET_GameIsSinglePlayer() || SVET_GameIsCoop() ) );
} else {
return BotLibSetup( false );
}
}
void SVT3_BotInitCvars() {
if ( GGameType & ( GAME_WolfMP | GAME_ET ) ) {
Cvar_Get( "bot_enable", "0", 0 ); //enable the bot
} else {
Cvar_Get( "bot_enable", "1", 0 ); //enable the bot
}
Cvar_Get( "bot_developer", "0", CVAR_CHEAT ); //bot developer mode
Cvar_Get( "bot_debug", "0", CVAR_CHEAT ); //enable bot debugging
Cvar_Get( "bot_groundonly", "1", 0 ); //only show ground faces of areas
Cvar_Get( "bot_reachability", "0", 0 ); //show all reachabilities to other areas
if ( GGameType & GAME_ET ) {
Cvar_Get( "bot_thinktime", "50", CVAR_CHEAT ); //msec the bots thinks
Cvar_Get( "bot_nochat", "1", 0 ); //disable chats
Cvar_Get( "bot_rocketjump", "0", 0 ); //enable rocket jumping
Cvar_Get( "bot_norcd", "0", 0 ); //enable creation of RCD file
} else {
Cvar_Get( "bot_thinktime", "100", CVAR_CHEAT ); //msec the bots thinks
Cvar_Get( "bot_nochat", "0", 0 ); //disable chats
Cvar_Get( "bot_rocketjump", "1", 0 ); //enable rocket jumping
}
Cvar_Get( "bot_reloadcharacters", "0", 0 ); //reload the bot characters each time
Cvar_Get( "bot_testichat", "0", 0 ); //test ichats
Cvar_Get( "bot_testrchat", "0", 0 ); //test rchats
Cvar_Get( "bot_fastchat", "0", 0 ); //fast chatting bots
Cvar_Get( "bot_grapple", "0", 0 ); //enable grapple
if ( GGameType & ( GAME_WolfSP | GAME_WolfMP ) ) {
Cvar_Get( "bot_miniplayers", "0", 0 ); //minimum players in a team or the game
}
if ( GGameType & GAME_Quake3 ) {
Cvar_Get( "bot_minplayers", "0", 0 ); //minimum players in a team or the game
Cvar_Get( "bot_visualizejumppads", "0", CVAR_CHEAT ); //show jumppads
Cvar_Get( "bot_forceclustering", "0", 0 ); //force cluster calculations
Cvar_Get( "bot_forcereachability", "0", 0 ); //force reachability calculations
Cvar_Get( "bot_forcewrite", "0", 0 ); //force writing aas file
Cvar_Get( "bot_aasoptimize", "0", 0 ); //no aas file optimisation
Cvar_Get( "bot_saveroutingcache", "0", 0 ); //save routing cache
Cvar_Get( "bot_maxdebugpolys", "2", 0 ); //maximum number of debug polys
Cvar_Get( "bot_testsolid", "0", CVAR_CHEAT ); //test for solid areas
Cvar_Get( "bot_testclusters", "0", CVAR_CHEAT ); //test the AAS clusters
Cvar_Get( "bot_pause", "0", CVAR_CHEAT ); //pause the bots thinking
Cvar_Get( "bot_report", "0", CVAR_CHEAT ); //get a full report in ctf
Cvar_Get( "bot_challenge", "0", 0 ); //challenging bot
Cvar_Get( "bot_interbreedchar", "", CVAR_CHEAT ); //bot character used for interbreeding
Cvar_Get( "bot_interbreedbots", "10", CVAR_CHEAT ); //number of bots used for interbreeding
Cvar_Get( "bot_interbreedcycle", "20", CVAR_CHEAT ); //bot interbreeding cycle
Cvar_Get( "bot_interbreedwrite", "", CVAR_CHEAT ); //write interbreeded bots to this file
}
if ( GGameType & GAME_ET ) {
bot_enable = Cvar_VariableIntegerValue( "bot_enable" );
}
}
void SVT3_BotInitBotLib() {
if ( debugpolygons ) {
Mem_Free( debugpolygons );
}
bot_maxdebugpolys = GGameType & GAME_Quake3 ? Cvar_VariableIntegerValue( "bot_maxdebugpolys" ) : 128;
debugpolygons = ( bot_debugpoly_t* )Mem_Alloc( sizeof ( bot_debugpoly_t ) * bot_maxdebugpolys );
}
bool SVT3_BotGetConsoleMessage( int client, char* buf, int size ) {
client_t* cl = &svs.clients[ client ];
cl->q3_lastPacketTime = svs.q3_time;
if ( cl->q3_reliableAcknowledge == cl->q3_reliableSequence ) {
return false;
}
cl->q3_reliableAcknowledge++;
int index = cl->q3_reliableAcknowledge & ( ( GGameType & GAME_Quake3 ?
MAX_RELIABLE_COMMANDS_Q3 : MAX_RELIABLE_COMMANDS_WOLF ) - 1 );
const char* msg = SVT3_GetReliableCommand( cl, index );
if ( !msg || !msg[ 0 ] ) {
return false;
}
if ( !( GGameType & GAME_ET ) ) {
String::NCpyZ( buf, msg, size );
}
return true;
}
int SVT3_BotGetSnapshotEntity( int client, int sequence ) {
client_t* cl = &svs.clients[ client ];
q3clientSnapshot_t* frame = &cl->q3_frames[ cl->netchan.outgoingSequence & PACKET_MASK_Q3 ];
if ( sequence < 0 || sequence >= frame->num_entities ) {
return -1;
}
if ( GGameType & GAME_WolfSP ) {
return svs.ws_snapshotEntities[ ( frame->first_entity + sequence ) % svs.q3_numSnapshotEntities ].number;
}
if ( GGameType & GAME_WolfMP ) {
return svs.wm_snapshotEntities[ ( frame->first_entity + sequence ) % svs.q3_numSnapshotEntities ].number;
}
if ( GGameType & GAME_ET ) {
return svs.et_snapshotEntities[ ( frame->first_entity + sequence ) % svs.q3_numSnapshotEntities ].number;
}
return svs.q3_snapshotEntities[ ( frame->first_entity + sequence ) % svs.q3_numSnapshotEntities ].number;
}
void SVT3_BotFrame( int time ) {
if ( !bot_enable ) {
return;
}
//NOTE: maybe the game is already shutdown
if ( !gvm ) {
return;
}
if ( GGameType & GAME_WolfSP ) {
SVWS_BotFrame( time );
} else if ( GGameType & GAME_WolfMP ) {
SVWM_BotFrame( time );
} else if ( GGameType & GAME_ET ) {
SVET_BotFrame( time );
} else {
SVQ3_BotFrame( time );
}
}
void BotDrawDebugPolygons( void ( * drawPoly )( int color, int numPoints, float* points ), int value ) {
static Cvar* bot_debug, * bot_highlightarea;
bot_debugpoly_t* poly;
int i;
if ( !bot_enable ) {
return;
}
if ( !debugpolygons ) {
return;
}
//bot debugging
if ( !bot_debug ) {
bot_debug = Cvar_Get( "bot_debug", "0", 0 );
}
//get the hightlight area
if ( !bot_highlightarea ) {
bot_highlightarea = Cvar_Get( "bot_highlightarea", "0", 0 );
}
if ( bot_debug->integer ) {
BotLibVarSet( "bot_highlightarea", bot_highlightarea->string );
}
//draw all debug polys
for ( i = 0; i < bot_maxdebugpolys; i++ ) {
poly = &debugpolygons[ i ];
if ( !poly->inuse ) {
continue;
}
drawPoly( poly->color, poly->numPoints, ( float* )poly->points );
}
}
|
//
// CotrollerLayer.cpp
// CatchGirl
//
// Created by xin on 16/4/6.
//
//
#include "CotrollerLayer.hpp"
#include "MapLayer.hpp"
#include "OperateLayer.hpp"
#include "Hrocker.hpp"
#include "PropertyManager.hpp"
#include "BaseRole.hpp"
bool CotrollerLayer::init(){
auto roleMap = FileUtils::getInstance()->getValueMapFromFile("roleData/hero.plist");
auto pManager = PropertyManager::create();
pManager->setArmatureName(roleMap["ArmatureName"].asString());
pManager->setDataName(roleMap["DataName"].asString());
pManager->setHP(roleMap["HP"].asInt());
pManager->setID(roleMap["ID"].asInt());
pManager->setATK(roleMap["ATK"].asInt());
pManager->setATKLimit(roleMap["ATKLimit"].asInt());
pManager->setPlayerName(roleMap["PlayerName"].asString());
pManager->setSpeed(roleMap["Speed"].asInt());
pManager->setHitRect(RectFromString(roleMap["HitRect"].asString()));
pManager->setHitPoint(pManager->getHitRect().origin);
pManager->setGetHitRect(RectFromString(roleMap["GetHitRect"].asString()));
pManager->setHitPoint(pManager->getGetHitRect().origin);
pManager->retain();
auto hero = BaseRole::createWithProperty(pManager);
hero->setPosition(400,200);
hero->type = static_cast<ROLE_TYPE>(roleMap["Type"].asInt());
this->addChild(hero,1,1);
MapLayer * mapLayer = MapLayer::create();
mapLayer->setBackground("mainBg2.png");
this->addChild(mapLayer);
auto operateLayer = OperateLayer::create();
this->addChild(operateLayer);
HRocker * rocker = HRocker::createHRocker("rocker.png", "rocker_bg.png", Vec2(150, 150));
rocker->startRocker(true);
this->addChild(rocker);
return true;
}
|
#pragma once
#include "AnimationBlendTo.h"
class AnimationBlendTest
{
public:
static void Test()
{
TestName();
TestNonMatching();
TestMatching();
TestBlend();
}
static void TestName()
{
Strip* pStrip = new Strip(1, 33);
AnimationBlendTo iAnimation(pStrip);
AssertEqual(iAnimation.getName(), (String) "Blend");
}
static void TestNonMatching()
{
Strip* pStrip = new Strip(1, 33);
AnimationBlendTo iAnimation(pStrip);
Command command("test 255,0,0,1", 0);
bool result = iAnimation.ProcessMessage(&command);
AssertEqual(false, result);
}
static void TestMatching()
{
Strip* pStrip = new Strip(1, 33);
AnimationBlendTo iAnimation(pStrip);
Command command("rgb 255,0,0,1", 0);
bool result = iAnimation.ProcessMessage(&command);
AssertEqual(true, result);
}
static RgbColor UpdateAndGetColor(IAnimation* pAnimation, Strip* pStrip)
{
pAnimation->Update();
RgbColor color = pStrip->GetPixelColor(0);
//cout << "Color: " << (int)color.R << " " << (int)color.G << " " << (int)color.B << endl;
return color;
}
static void TestBlend()
{
Strip* pStrip = new Strip(1, 33);
AnimationBlendTo animation(pStrip);
Command command("rgb 255,0,0,1", 0);
bool result = animation.ProcessMessage(&command);
RgbColor color = UpdateAndGetColor(&animation, pStrip);
AssertEqual(255, (int)color.R);
AssertEqual(0, (int)color.G);
AssertEqual(0, (int)color.B);
command = Command("rgb 0,255,0,3", 0);
animation.ProcessMessage(&command);
color = pStrip->GetPixelColor(0);
AssertEqual(255, (int)color.R);
AssertEqual(0, (int)color.G);
AssertEqual(0, (int)color.B);
color = UpdateAndGetColor(&animation, pStrip);
AssertEqual(82, (int)color.R);
AssertEqual(12, (int)color.G);
AssertEqual(0, (int)color.B);
color = UpdateAndGetColor(&animation, pStrip);
AssertEqual(12, (int)color.R);
AssertEqual(82, (int)color.G);
AssertEqual(0, (int)color.B);
color = UpdateAndGetColor(&animation, pStrip);
AssertEqual(0, (int)color.R);
AssertEqual(255, (int)color.G);
AssertEqual(0, (int)color.B);
}
};
#pragma once
|
#define _CRT_SECURE_NO_WARNINGS
#include "gkfn.h"
#include "utility.h"
#include <string.h>
#define PRTRST 1
char elements[5][10] = { "SO2", "CO", "O3", "NO2", "PM10" };
// time deley
GKFN::~GKFN() {
int i;
for (i = 0; i < DIM; i++) {
delete m[i];
delete Si[i];
}
delete s; delete hn; delete ek; delete ck; delete m; delete Si; delete o_sse;
for (i = 0; i < Nm; i++)
delete tsi[i];
delete tso; delete tsi; delete tse;
}
GKFN::GKFN(int N, double* ts, int E, int Tau, int PredictionStep, double TraningRate, int aq, char *spot) {
int i, j, k;
double Rt;
double X;
AQ = aq;
strcpy(SPOT, spot);
tso = new double[Nm];
tsi = new double*[Nm];
tse = new double[Nm];
for (i = 0; i < Nm; i++)
tsi[i] = new double[id];
s = new double[DIM];
hn = new double[DIM];
ek = new double[Nm];
ck = new double[DIM];
m = new double*[DIM];
Si = new double*[DIM];
o_sse = new double[DIM];
for (i = 0; i < DIM; i++) {
m[i] = new double[id];
Si[i] = new double[DIM];
}
this->N = N;
this->ts = ts;
this->Td = Tau;
this->Tk = E;
this->Tp = PredictionStep;
this->Rt = TraningRate;
Ns = N - (E - 1) * Tau - 1;
k = (E - 1) * Tau + 1;
for (i = 1; i <= Ns; i++) {
tso[i] = ts[k + Tp];
for (j = 0; j < E; j++) {
tsi[i][j + 1] = ts[k - j * Tau];
}
k++;
}
Rt = TraningRate;
Nt = Ns*Rt;
Nf = Ns - Nt;
K0 = 1.f;
}
/*
GKFN::GKFN(char *filename, int E, int Tau, int PredictionStep, double TraningRate) {
int i,j,k;
double X;
FILE *fp;
ts = new double[Nm];
tso = new double[Nm];
tsi = new double*[Nm];
tse = new double[Nm];
for (i = 0; i < Nm; i++)
tsi[i] = new double[id];
s = new double[DIM];
hn = new double[DIM];
ek = new double[Nm];
ck = new double[DIM];
m = new double*[DIM];
Si = new double*[DIM];
o_sse = new double[DIM];
for (i = 0; i < DIM; i++) {
m[i] = new double[id];
Si[i] = new double[DIM];
}
//generate training and test data
if ((fp = fopen(filename, "r")) == NULL)
fprintf(stderr, "File Open Error : %s \n", filename);
for (i = 1; fscanf(fp, "%lf", &ts[i]) == 1; ++i);
fclose(fp);
N = i - 1;
this->Td = Tau;
this->Tk = E;
this->Rt = TraningRate;
Ns = N - Td*(Tk - 1);
for (i = 1; i <= Tk; ++i) {
k = Td*(i - 1);
for (j = 1; j <= Ns; ++j) {
k = k + 1;
tsi[j][i] = ts[k];
}
}
this->Tp = PredictionStep;
Ns = Ns - Tp;
St = Td*(Tk - 1) + Tp;
k = St;
for (i = 1; i <= Ns; ++i) {
k = k + 1;
tso[i] = ts[k];
}
Rt = TraningRate;
Nt = Ns*Rt;
Nf = Ns - Nt;
K0 = 1.f;
}
*/
void GKFN::learn(int NumOfKernels, int NumOfEpochs, double errMargin, double UBofSTD) {
this->ic = errMargin;
this->si = UBofSTD;
this->N1 = NumOfKernels;
this->N2 = NumOfEpochs;
RECRUIT_FTN(); /* initial set-up of PFN */
GENERAL_INVERSE();
PREDICTION();
}
void GKFN::PREDICTION() {
int i, j, n = Nt + Nf;
double yavg, ytrue, yest;
double nu, de;
double yk, x;
double *pka = new double[Np+1];
FILE *res_train, *res_test;
char fname[60];
trainRsq = 0.f;
testRsq = 0.f;
trainRmse = 0.f;
testRmse = 0.f;
yavg = 0.f;
nu = 0.f;
de = 0.f;
for (i = 1; i <= n; i++) {
for (j = 1; j <= Np; ++j) {
x = s[j];
pka[j] = kernx(Tk, x, tsi[i], m[j]);
}
yk = inner(Np, pka, ck);
if (yk < 0)
yk = 0.f;
tse[i] = yk;
}
delete pka;
for (i = 1; i <= Nt; i++)
yavg += tso[i];
yavg /= Nt;
for (i = 1; i <= Nt; i++) {
ytrue = tso[i];
yest = tse[i];
trainRmse += (ytrue - yest)*(ytrue - yest);
de += (ytrue - yavg)*(ytrue - yavg);
}
nu = trainRmse;
trainRsq = 1.f - nu / de;
trainRmse /= Ns; // ¿©±â n-> Ns
trainRmse = sqrt(trainRmse);
#if PRTRST
if (trainRsq >= 0.2 && trainRmse <= yavg) {
sprintf(fname, "result/%s_%s_%d_%d_%.1lf_%d_train(R^2 %.2lf).csv", SPOT, elements[AQ-1], Tk, Td, Rt, N1, trainRsq);
res_train = fopen(fname, "w");
fprintf(res_train, "REAL,ESTIMATE\n");
for (i = 1; i <= Nt; i++)
fprintf(res_train, "%lf,%lf\n", tso[i], tse[i]);
fclose(res_train);
}
#endif
yavg = 0.f;
de = 0.f;
nu = 0.f;
for (i = Nt+1; i <= n; i++)
yavg += tso[i];
yavg /= Nf;
for (i = Nt+1; i <= n; i++) {
ytrue = tso[i];
yest = tse[i];
testRmse += (ytrue - yest)*(ytrue - yest);
de += (ytrue - yavg)*(ytrue - yavg);
}
nu = testRmse;
testRsq = 1.f - nu / de;
testRmse /= Nf; // ¿©±â n -> Nf
testRmse = sqrt(testRmse);
#if PRTRST
if (testRsq >= 0.2 && testRmse <= yavg) {
sprintf(fname, "result/%s_%s_%d_%d_%.1lf_%d_test(R^2 %.2lf).csv", SPOT, elements[AQ-1], Tk, Td, Rt, N1, testRsq);
res_test = fopen(fname, "w");
fprintf(res_test, "REAL,ESTIMATE\n");
for (i = Nt + 1; i <= n; i++)
fprintf(res_test, "%lf,%lf\n", tso[i], tse[i]);
fclose(res_test);
}
#endif
}
void GKFN::RECRUIT_FTN()
{
int a, b, g, i, j, k, l, n, p, q;
double c, x, y, z, ec, dk, sk;
double yd, yk, Ck;
double *a1 = new double[id], *a2 = new double[id], *a3= new double[id];
double *aka = new double[DIM], *akb = new double[DIM], *pka = new double[DIM], *pkb = new double[DIM], *Bka = new double[DIM], *Bkb = new double[DIM];
double **Psa = new double*[DIM], **Psi = new double*[DIM], **dA = new double*[DIM];
for (i = 0; i < DIM; i++) {
Psa[i] = new double[DIM];
Psi[i] = new double[DIM];
dA[i] = new double[DIM];
}
x = 1000.; // min
y = 0.; // max
for (j = 1; j <= Nt; ++j) {
z = tso[j];
if (z < x) {
x = z;
a = j;
}
if (z > y) {
y = z;
b = j;
}
}
/*
* assign input data
*/
for (j = 1; j <= Tk; ++j) {
a1[j] = tsi[b][j];
m[1][j] = a1[j];
a2[j] = tsi[a][j];
m[2][j] = a2[j];
a3[j] = a1[j] - a2[j];
}
/*
* Find maximum standard deviation
*/
x = sc*norm(Tk, a3);
/*
if (x > si)
x = si;
*/
s[1] = x;
s[2] = x;
Psa[1][1] = 1.;
Psi[1][1] = 1.;
ck[1] = tso[b];
i = 2;
ec = ic;
/* recruiting gkfs */
while (i <= N1) {
for (l = 1; l <= Nt; ++l) {
/* input-sample */
for (j = 1; j <= Tk; ++j) {
a1[j] = tsi[l][j];
yd = tso[l];
m[i][j] = a1[j];
}
/* calculation of sigma */
/*
x = si;
*/
for (j = 1; j <= i - 1; ++j) {
for (k = 1; k <= Tk; ++k) {
a2[k] = m[j][k];
a3[k] = a1[k] - a2[k];
}
y = sc*norm(Tk, a3);
/*
if (y < x) x = y;
*/
}
/*
s[i] = x;
*/
s[i] = y;
/* update pka and pkb */
for (j = 1; j <= i; ++j) {
for (k = 1; k <= Tk; ++k) {
a2[k] = m[j][k];
}
pkb[j] = kernx(Tk, x, a2, a1);
}
for (j = 1; j <= i; ++j) {
for (k = 1; k <= Tk; ++k) {
a2[k] = m[j][k];
}
x = s[j];
pka[j] = kernx(Tk, x, a1, a2);
}
/* check error */
yk = inner(i - 1, pka, ck);
ek[l] = yd - yk;
x = ek[l];
if (abx(x) > ec) {
/* recruitment of a PFU */
/* update Psa */
for (j = 1; j <= i - 1; ++j) {
Psa[i][j] = pka[j];
Psa[j][i] = pkb[j];
}
Psa[i][i] = pka[i];
/* calculation of Psi */
AX2(i - 1, i - 1, Psi, pka, aka);
AX1(i - 1, i - 1, Psi, pkb, akb);
sk = inner(i - 1, pkb, aka);
dk = pka[i] - sk;
outer(i - 1, akb, aka, dA);
Ck = 1. / dk;
scale(i - 1, Ck, dA, dA);
Madd(i - 1, i - 1, Psi, dA, Psi);
for (j = 1; j <= i - 1; ++j) {
Bka[j] = -aka[j] / dk;
Bkb[j] = -akb[j] / dk;
}
for (j = 1; j <= i - 1; ++j) {
Psi[i][j] = Bka[j];
Psi[j][i] = Bkb[j];
}
Psi[i][i] = Ck;
/* calculation of ck */
c = ek[l] / dk;
for (j = 1; j <= i - 1; ++j)
ck[j] -= c*akb[j];
ck[i] = c;
i++;
}
if (i>N1) break;
}
/* estimation of rms-error */
z = 0.0;
for (j = 1; j <= Nt; ++j)
z += ek[j] * ek[j];
z = sqrt(z / (double)Nt);
ec *= er;
}
Np = i - 1;
for (i = 0; i < DIM; i++) {
delete Psa[i]; delete Psi[i]; delete dA[i];
}
delete a1; delete a2; delete a3; delete aka; delete akb; delete pka; delete pkb; delete Bka; delete Bkb; delete Psa; delete Psi; delete dA;
}
void GKFN::GENERAL_INVERSE()
{
register int q, p, l, j, k;
int i;
double x, y, z, sk, dk, Ck;
double *aka = new double[DIM], *akb = new double[DIM], *ds = new double[DIM], **dA = new double*[DIM];
for (i = 0; i < DIM; i++)
dA[i] = new double[DIM];
for (q = 1; q <= N2; ++q) {
INITIALIZE_SIGMA(1);
for (p = 1; p <= Ip; ++p) {
for (l = 1; l <= Nt; ++l) {
SIGMA_HN(l);
/* update Si */
AX1(Np, Np, Si, hn, aka);
sk = inner(Np, hn, aka);
dk = 1. + sk;
Ck = 1. / dk;
outer(Np, aka, aka, dA);
scale(Np, Ck, dA, dA);
Msub(Np, Np, Si, dA, Si);
/* adjust sigma of pfn */
AX1(Np, Np, Si, hn, ds);
for (j = 1; j <= Np; ++j) {
s[j] += ds[j] * ek[l];
if (s[j] < 0)
s[j] = -s[j];
}
} /* for-loop ; l */
} /* for-loop ; p */
/* Mean update */
INITIALIZE_SIGMA(2);
for (p = 1; p <= Ip; ++p) {
for (l = 1; l <= Nt; ++l) {
MEAN_HN(l);
/* update Si */
AX1(Np*Tk, Np*Tk, Si, hn, aka);
sk = inner(Np*Tk, hn, aka);
dk = 1. + sk;
Ck = 1. / dk;
outer(Np*Tk, aka, aka, dA);
scale(Np*Tk, Ck, dA, dA);
Msub(Np*Tk, Np*Tk, Si, dA, Si);
/* adjust sigma of pfn */
AX1(Np*Tk, Np*Tk, Si, hn, ds);
for (j = 1; j <= Np; ++j)
for (k = 1; k <= Tk; ++k)
m[j][k] += ds[Tk*(j - 1) + k] * ek[l];
}
}
/* output weight update */
/* initialization of Si */
INITIALIZE_SIGMA(1);
for (p = 1; p <= Ip; ++p) {
for (l = 1; l <= Nt; ++l) {
OUTWEIGHT_HN(l);
/* update Psi */
AX1(Np, Np, Si, hn, aka);
AX2(Np, Np, Si, hn, akb);
dk = 1. + inner(Np, hn, aka);
Ck = 1. / dk;
outer(Np, aka, akb, dA);
scale(Np, Ck, dA, dA);
Msub(Np, Np, Si, dA, Si);
/* update ck */
AX1(Np, Np, Si, hn, aka);
for (j = 1; j <= Np; ++j)
ck[j] += ek[l] * aka[j];
}
/* estimation of rms-error */
z = 0.0;
for (j = 1; j <= Nt; ++j)
z += ek[j] * ek[j];
z = sqrt(z / (double)Nt);
/* added and changed by kmjung */
o_sse[(q - 1)*Ip + p - 1] = z;
}
}
for (i = 0; i < DIM; i++)
delete dA[i];
delete aka; delete akb; delete ds; delete dA;
}
void GKFN::SIGMA_HN(int iter)
{
register int j, k;
double x, y, yd, yk;
double *a1 = new double[id], *a2 = new double[id], *a3 = new double[DIM];
/* input-sample */
for (j = 1; j <= Tk; ++j)
a1[j] = tsi[iter][j];
yd = tso[iter];
/* update pka */
for (j = 1; j <= Np; ++j) {
for (k = 1; k <= Tk; ++k)
a2[k] = m[j][k];
x = s[j];
a3[j] = kernx(Tk, x, a1, a2);
}
/* check error */
yk = inner(Np, a3, ck);
ek[iter] = yd - yk;
/* update hn */
for (j = 1; j <= Np; ++j) {
x = 1. / (2.*s[j] * s[j]);
y = 0.0;
for (k = 1; k <= Tk; ++k)
y += (a1[k] - m[j][k])*(a1[k] - m[j][k]);
hn[j] = ck[j] * y*exp(-x*y) / (s[j] * s[j] * s[j]);
}
delete a1; delete a2; delete a3;
}
void GKFN::MEAN_HN(int iter)
{
register int j, k;
double x, y, z, yd, yk;
double *a1 = new double[id], *a2 = new double[id], *a3 = new double[DIM];
/* input-sample */
for (j = 1; j <= Tk; ++j)
a1[j] = tsi[iter][j];
yd = tso[iter];
/* update pka */
for (j = 1; j <= Np; ++j) {
for (k = 1; k <= Tk; ++k)
a2[k] = m[j][k];
x = s[j];
a3[j] = kernx(Tk, x, a1, a2);
}
/* check error */
yk = inner(Np, a3, ck);
ek[iter] = yd - yk;
/* update hn */
for (j = 1; j <= Np; ++j) {
x = ck[j] / (s[j] * s[j]);
y = 0.0;
for (k = 1; k <= Tk; ++k)
y += (a1[k] - m[j][k])*(a1[k] - m[j][k]);
y /= (2.0*s[j] * s[j]);
z = x*exp(-y);
for (k = 1; k <= Tk; ++k)
hn[Tk*(j - 1) + k] = z*(a1[k] - m[j][k]);
}
delete a1; delete a2; delete a3;
}
void GKFN::OUTWEIGHT_HN(int iter)
{
register int j, k;
double x, y, yd, yk;
double *a1 = new double[id], *a2 = new double[id];
/* input-sample */
for (j = 1; j <= Tk; ++j)
a1[j] = tsi[iter][j];
yd = tso[iter];
/* update pka */
for (j = 1; j <= Np; ++j) {
for (k = 1; k <= Tk; ++k)
a2[k] = m[j][k];
x = s[j];
hn[j] = kernx(Tk, x, a1, a2);
}
/* check error */
yk = inner(Np, hn, ck);
ek[iter] = yd - yk;
delete a1; delete a2;
}
void GKFN::INITIALIZE_SIGMA(int mode) /* 1 = Sigma, Outweight ;; 2 = Mean */
{
register int j, k;
/* initialization of Si */
if (mode == 1) {
for (j = 1; j <= Np; ++j)
for (k = 1; k <= Np; ++k) {
if (j == k)
Si[j][k] = K0;
else
Si[j][k] = 0.;
}
}
else if (mode == 2) {
for (j = 1; j <= Np*Tk; ++j)
for (k = 1; k <= Np*Tk; ++k) {
if (j == k)
Si[j][k] = K0;
else
Si[j][k] = 0.;
}
}
}
//void GKFN::test()
//{
// register int i, j, k;
// double m1, m2, x, z, w, yd, yk, sum;
// double a1[id], a2[id], pka[DIM];
// double tmp1[1000];
// /* evaluation on test-samples */
//
// /* normalization term for training samples */
// m1 = .0;
// for (i = 1; i <= Nt; ++i) {
// m1 = m1 + tso[i];
// }
// m1 = m1 / (double)Nt;
// x = .0;
//
// for (i = 1; i <= Nt; ++i) {
// x = x + (tso[i] - m1)*(tso[i] - m1);
// }
// m1 = sqrt(x / ((double)Nt - 1.));
// /* normalization term for test samples */
// m2 = .0;
// for (i = Nt + 1; i <= Nt + Nf; ++i) {
// m2 = m2 + tso[i];
// }
// m2 = m2 / (double)Nf;
//
// x = .0;
// for (i = Nt + 1; i <= Nt + Nf; ++i) {
// x = x + (tso[i] - m2)*(tso[i] - m2);
// }
// m2 = sqrt(x / ((double)Nf - 1.));
//
// /* calculation of normalized rms error */
// z = .0;
//
// printf("yd yk ek\n");
// for (i = 1; i <= Nt + Nf; ++i) {
// /* input-sample */
// for (j = 1; j <= Tk; ++j) {
// a1[j] = tsi[i][j];
// yd = tso[i];
// }
// /* update pka */
// for (j = 1; j <= Np; ++j) {
// for (k = 1; k <= Tk; ++k) {
// a2[k] = m[j][k];
// }
// x = s[j];
// pka[j] = kernx(Tk, x, a1, a2);
// }
// /* check error */
// yk = inner(Np, pka, ck);
//
// if (yk >= 0)
// tmp1[i] = inner(Np, pka, ck);
// else
// tmp1[i] = 0;
//
// ek[i] = yd - yk;
// printf("%f %f %f\n", yd, yk, ek[i]);
// z = z + ek[i] * ek[i];
// if (i == Nt) {
// w = sqrt(z / (double)(Nt - 1));
// z = 0.0;
// }
// }
//
// z = sqrt(z / (double)(Nf - 1));
//
// /* write simulation results on output-files */
//
//
//
//
// printf("mean vector ..\n");
// for (i = 1; i <= Np; ++i) {
// for (j = 1; j <= Tk; ++j) {
// printf("%f ", m[i][j]);
// }
// printf("\n");
// }
//
// printf("sigma and ck \n");
// for (i = 1; i <= Np; ++i) {
// printf("%f %f\n", s[i], ck[i]);
// }
//
// sum = 0.0;
// for (i = 1; i <= Nt + Nf; ++i)
// sum += fabs(ek[i]);
// sum /= (double)Nt + Nf;
//
//
//
// //msd = metrics.mean_squared_error(true_num_pickups, predicted_num_pickups)
// //m=metrics.r2_score(true_num_pickups, predicted_num_pickups)
// printf("R^2 score\n");
// int tmp0 = Nt + Nf; // Nf : # of test data
//
// tmp1[0] = 0.0;
//
// for (i = 1; i <= n; i++) {
// nu += (tso[i] - tmp1[i]) * (tso[i] - tmp1[i]);
// de += (tso[i] - tavg) * (tso[i] - tavg);
// }
//
// rsq = 1.f - nu / de;
//
// printf("R^2 = %lf\n", rsq);
//
//
// //return;
// for (i = 1; i <= tmp0; i++) {
// var1 += (tso[i] - avg1)*(tso[i] - avg1);
// var2 += (tmp1[i] - avg2)*(tmp1[i] - avg2);
// }
//
// var1 /= tmp0;
// var2 /= tmp0;
//
// for (i = 1; i <= tmp0; i++) {
// for (j = 1; j <= tmp0; j++) {
//
// cov += (tso[i] - avg1)*(tmp1[j] - avg2);
// }
//
// }
//
// //printf("%f", cov);
// cov = cov / (tmp0 - 1);
//
// double S = ((cov)*(cov)) / (var1 * var2);
// double S2 = cov / sqrt(var1*var2);
// printf("S %f\n", S2);
// printf("mena %f %f", avg1, avg2);
// printf("var and cov %f %f %f\n", var1, var2, cov);
//
//
//
//
//
//
//
// printf("Mean of absolute error = %10.4f\n", sum);
//
// printf("Simulation Results of a Network with GKFs\n");
// printf("adaptation of sigmas, mean vectors and output weights\n");
// printf("\n");
// printf("time delay = %d\n", Td);
// printf("\n");
// printf("input dimension = %d\n", Tk);
// printf("\n");
// printf("forward prediction step = %d\n", Tp);
// printf("\n");
// printf("number of total time series data = %d\n", N);
// printf("\n");
// printf("number of training data = %d\n", Nt);
// printf("\n");
// printf("number of test data = %d\n", Nf);
// printf("\n");
// printf("initial error margin = %f\n", ic);
// printf("\n");
// printf("upper-bound of standard deviation = %f\n", si);
// printf("\n");
//
// /*
// printf ( "initial value of diagonal element in Si = %f\n", K0);
// printf ( "\n");*/
// printf("number of epochs for recruiting GKFs = %d\n", N1);
// printf("\n");
// printf("number of epochs for parameter estimation = %d\n", N2);
// printf("\n");
// printf("number of potential functions = %d\n", Np);
// printf("\n");
// /*
// printf ( "quality of inversion: %f %f\n", q0, q1);
// printf ( "\n");*/
// printf("rms error for trainig-samples = %f\n", w);
// printf("\n");
// printf("standard deviation of trainig-samples = %f\n", m1);
// printf("\n");
// x = (w / m1)*100.;
// printf("normlized rms error for trainig-samples = %f percent\n", x);
// printf("\n");
// printf("rms error for test-samples = %f\n", z);
// printf("\n");
// printf("standard deviation of test-samples = %f\n", m2);
// printf("\n");
// x = (z / m2)*100.;
// printf("normlized rms error for test-samples = %f percent\n", x);
// printf("\n");
//}
|
// TODO(dkorolev): Test ScopeGuard and MakeScopeGuard as well.
#include "util.h"
#include "../3party/gtest/gtest.h"
#include "../3party/gtest/gtest-main.h"
static const char global_string[] = "magic";
TEST(Util, CompileTimeStringLength) {
const char local_string[] = "foo";
static const char local_static_string[] = "blah";
EXPECT_EQ(3u, CompileTimeStringLength(local_string));
EXPECT_EQ(4u, CompileTimeStringLength(local_static_string));
EXPECT_EQ(5u, CompileTimeStringLength(global_string));
}
|
// This file has been generated by Py++.
#ifndef DragContainer_hpp__pyplusplus_wrapper
#define DragContainer_hpp__pyplusplus_wrapper
void register_DragContainer_class();
#endif//DragContainer_hpp__pyplusplus_wrapper
|
#include <iostream>
#include <cstring>
using namespace std;
template <typename T> void show(T *, int);
template <>
void show<char *>(char **, int);
template <typename T> T maxn(T *, int);
template <>
char * maxn<char *>(char **, int);
int main(void)
{
int arr_int[6] = {1, 2, 3, 4, 5, 6};
double arr_flt[4] = {10.0, 11.0, 12.0, 13.0};
char * arr_ch[4] = {
"shao",
"zhengjiang",
"haha",
"yesyesyesgood",
};
show(arr_int, 6);
cout << "Max int: " << maxn(arr_int, 6) << endl;
show(arr_flt, 4);
cout << "Max double: " << maxn(arr_flt, 4) << endl;
show(arr_ch, 4);
char* max3=maxn(arr_ch, 4);
cout << "Max string: " << &max3 << endl;
return 0;
}
template <typename T>
T maxn(T * arr, int n)
{
T max = arr[0];
for(int i = 0; i < n; ++i)
{
if(arr[i] > max)
max = arr[i];
}
return max;
}
template <>
char * maxn<char *>(char ** arr, int n)
{
int max_len = strlen(arr[0]);
int tmp_len;
int max_idx = 0;
int i;
for(i = 0; i < n; ++i)
{
tmp_len = strlen(arr[i]);
if(tmp_len > max_len)
{
max_len = tmp_len;
max_idx = i;
}
}
return arr[max_idx];
}
// output array
template <typename T>
void show(T * arr, int n)
{
for(int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << endl;
}
template <>
void show<char *>(char ** arr, int n)
{
for(int i = 0; i < n; ++i)
cout << arr[i] << endl;
}
|
#include "pch.h"
#include "State.h"
void State::SetContext(StateContext* context)
{
m_Context = context;
}
State::~State()
{
}
|
#pragma once
/// @file
/// Provides access to Python deprecation utilities from C++.
#include "pybind11/pybind11.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
namespace drake {
namespace pydrake {
/// Deprecates an attribute `name` of a class `cls`.
/// This *only* works with class attributes (unbound members or methods) as it
/// is implemented with a Python property descriptor.
inline void DeprecateAttribute(
py::object cls, py::str name, py::str message) {
py::object deprecated =
py::module::import("pydrake.util.deprecation").attr("deprecated");
py::object original = cls.attr(name);
cls.attr(name) = deprecated(message)(original);
}
/// Raises a deprecation warning.
///
/// @note If you are deprecating a class's member or method, please use
/// `DeprecateAttribute` so that the warning is issued immediately when
/// accessed, not only when it is called.
inline void WarnDeprecated(py::str message) {
py::object warn_deprecated =
py::module::import("pydrake.util.deprecation").attr("_warn_deprecated");
warn_deprecated(message);
}
} // namespace pydrake
} // namespace drake
|
/**
* ****************************************************************************
* Copyright (c) 2018, Robert Lukierski.
* 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.
*
* ****************************************************************************
* Quick Test.
* ****************************************************************************
*/
#include <cstdint>
#include <cstddef>
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <FireWireDriver.hpp>
#include <KinectOneDriver.hpp>
#include <OpenNIDriver.hpp>
#include <PointGreyDriver.hpp>
#include <RealSenseDriver.hpp>
#include <RealSense2Driver.hpp>
#include <V4LDriver.hpp>
#include <VRMagicDriver.hpp>
struct Intrinsics
{
float fx, fy;
float u0, v0;
std::array<float,5> dist;
friend std::ostream& operator<< (std::ostream& stream, const Intrinsics& matrix)
{
stream << matrix.fx << " , " << matrix.fy << " | " << matrix.u0 << " , " << matrix.v0 << " [ "
<< matrix.dist[0] << ","
<< matrix.dist[1] << ","
<< matrix.dist[2] << ","
<< matrix.dist[3] << ","
<< matrix.dist[4] << ","
<< " ]";
return stream;
}
};
template<typename T> struct __attribute__ ((__packed__)) Triplet { T x,y,z; };
using uchar3 = Triplet<uint8_t>;
template<typename T>
static inline T clamp(const T& v, const T clamp_min, const T clamp_max)
{
return std::max(clamp_min, std::min(v, clamp_max));
}
template<typename T>
static inline T clampRescale(const T& v, const T vmin, const T vmax, const T clamp_min, const T clamp_max)
{
const T alpha = T(1.0f) / (vmax - vmin);
const T beta = -vmin * (T(1.0)/(vmax - vmin));
return clamp(v * alpha + beta, clamp_min, clamp_max);
}
static constexpr std::size_t WidthRGB = 1280;
static constexpr std::size_t HeightRGB = 720;
static constexpr std::size_t WidthDepth = 1280;
static constexpr std::size_t HeightDepth = 720;
static void convertRGB(const drivers::camera::FrameBuffer& fb, cv::Mat& img_out)
{
for(std::size_t y = 0 ; y < fb.getHeight() ; ++y)
{
for(std::size_t x = 0 ; x < fb.getWidth() ; ++x)
{
const uchar3& pix_in = fb.getPixel<uchar3>(x,y);
uchar3& pix_out = img_out.at<uchar3>(y,x);
pix_out.x = pix_in.z;
pix_out.y = pix_in.y;
pix_out.z = pix_in.x;
}
}
}
static void convertDepth(const drivers::camera::FrameBuffer& fb, cv::Mat& img_out, float depthScale = 1.0)
{
float dsum = 0.0, dcount = 0.0;
float dmin = std::numeric_limits<float>::max(), dmax = -std::numeric_limits<float>::max();
for(std::size_t y = 0 ; y < fb.getHeight() ; ++y)
{
for(std::size_t x = 0 ; x < fb.getWidth() ; ++x)
{
const uint16_t& depth_in = fb.getPixel<uint16_t>(x,y);
if(depth_in > 0)
{
const float dth = float(depth_in) * depthScale;
dsum += dth;
dcount += 1.0f;
dmin = std::min(dth, dmin);
dmax = std::max(dth, dmax);
}
}
}
dmin = 0.0f;
dmax = 12.0f;
for(std::size_t y = 0 ; y < fb.getHeight() ; ++y)
{
for(std::size_t x = 0 ; x < fb.getWidth() ; ++x)
{
const uint16_t& depth_in = fb.getPixel<uint16_t>(x,y);
uint8_t& pix_out = img_out.at<uint8_t>(y,x);
if(depth_in > 0)
{
const float d = float(depth_in) * depthScale;
pix_out = (uint8_t)(clampRescale(d,dmin,dmax,0.0f,1.0f) * 255.0f);
}
else
{
pix_out = 0;
}
}
}
}
extern "C" int main(int argc, char** argv)
{
typedef drivers::camera::RealSense2 CamDriverT;
CamDriverT camera;
cv::namedWindow("Image");
cv::namedWindow("Depth");
camera.open();
camera.setDepthMode(WidthDepth,HeightDepth,30,true);
camera.setRGBMode(WidthRGB,HeightRGB,30,drivers::camera::EPixelFormat::PIXEL_FORMAT_RGB8,false);
camera.start();
std::cerr << "IsO: " << camera.isOpened() << " and " << camera.isStarted() << std::endl;
cv::Mat img_rgb(HeightRGB, WidthRGB, CV_8UC3);
cv::Mat img_depth(HeightDepth, WidthDepth, CV_8UC1);
const float ds = camera.getDepthScale();
std::cerr << "Depth Scale: " << ds << " or " << std::endl;
Intrinsics i_rgb, i_depth;
camera.getRGBIntrinsics(i_rgb.fx,i_rgb.fy,i_rgb.u0,i_rgb.v0,&i_rgb.dist);
camera.getDepthIntrinsics(i_depth.fx,i_depth.fy,i_depth.u0,i_depth.v0,&i_depth.dist);
std::cerr << "RGB Intrinsics: " << i_rgb << std::endl;
std::cerr << "Depth Intrinsics: " << i_depth << std::endl;
while(1)
{
drivers::camera::FrameBuffer fb_rgb, fb_depth;
if(camera.captureFrame(fb_depth, fb_rgb,std::chrono::seconds(1)))
{
convertRGB(fb_rgb, img_rgb);
convertDepth(fb_depth, img_depth, ds);
//std::cerr << "OK" << std::endl;
}
else
{
//std::cerr << "Fail" << std::endl;
}
cv::imshow("Image", img_rgb);
cv::imshow("Depth", img_depth);
int key = cv::waitKey(5) & 0xFF;
if((key == 27) || (key == 1048603)) { break; }
}
camera.stop();
cv::destroyAllWindows();
return 0;
}
|
#ifndef _camaraCPP_
#define _camaraCPP_
#include "camaraOrtho.h"
camaraOrtho::camaraOrtho(){
ortogonal = false;
examinar = false;
esferica = false;
}
void camaraOrtho::cambiarEsferica(){
reset();
esferica = !esferica;
}
camaraOrtho::camaraOrtho(float x, float y, float z, float m_x, float m_y, float m_z, float vo_x, float vo_y, float vo_z, float an_x,float an_y,float an_z){
ortogonal = false;
examinar = false;
esferica = false;
//PARÁMETROS LOOK AT
obs_x=x;
obs_y=y;
obs_z=z;
//PARÁMETROS QUE NO USO SIN LOOK AT
mirada_x=m_x;
mirada_y=m_y;
mirada_z=m_z;
vec_obs_x=vo_x;
vec_obs_y=vo_y;
vec_obs_z=vo_z;
//FIN DE PARÁMETROS QUE NO USO SIN LOOK AT
//FIN DE PARÁMETROS LOOK AT
ang_x = an_x;
ang_y = an_y;
ang_z = an_z;
//GUARDAMOS PARA RESET
backupValores.reserve(12);
backupValores.push_back(obs_x);
backupValores.push_back(obs_y);
backupValores.push_back(obs_z);
backupValores.push_back(mirada_x);
backupValores.push_back(mirada_y);
backupValores.push_back(mirada_z);
backupValores.push_back(vec_obs_x);
backupValores.push_back(vec_obs_y);
backupValores.push_back(vec_obs_z);
backupValores.push_back(ang_x);
backupValores.push_back(ang_y);
backupValores.push_back(ang_z);
}
void camaraOrtho::setProyeccion(float a,float b, float c, float d, float e, float f){
izquierda=a;
derecha=b;
abajo=c;
arriba=d;
cerca=e;
lejos=f;
}
void camaraOrtho::cambiarProyeccion(int p){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
cout << "izquierda: "<< izquierda<<"derecha"<< derecha<<"abajo"<< abajo<<"arriba: "<< arriba<<"cerca"<< cerca<<"lejos"<< lejos<<endl;
switch(p){
case 0:
ortogonal = false;
cout << "Frustum"<<endl;
glFrustum(izquierda,derecha,abajo,arriba,cerca,lejos);
break;
case 1:
ortogonal = true;
cout << "Ortogonal"<<endl;
glOrtho(izquierda*zoom,derecha*zoom,abajo*zoom,arriba*zoom,cerca,lejos);
break;
}
};
void camaraOrtho::activarExplorar(_vertex3f puntoGiro){
//explorar = true;
esferica = true;
//FAIO
//obs_x = puntoGiro.x;
//obs_y = puntoGiro.y;
//obs_z = puntoGiro.z;
obs_x = 5;
obs_y = 0;
obs_z = 10;
}
void camaraOrtho::setObservador(){
// cout << "Translada " << -obs_x << " " << -obs_y << " "<<-obs_z<<endl;
if(ortogonal){
// cout << "observador ortogonal"<<endl;
cout << " obs_x " << obs_x << " obs_y " << obs_y << " obs_z " << obs_z << " mirada_x " << mirada_x << " mirada_y " << mirada_y << " mirada_z " << mirada_z << "vec_obs_x: " << vec_obs_x << "vec_obs_y: " << vec_obs_y << "vec_obs_z: " << vec_obs_z<<endl;
gluLookAt (obs_x, obs_y, obs_z, mirada_x, mirada_y, mirada_z, vec_obs_x, vec_obs_y, vec_obs_z);
}
else{
// cout << "observador no ortogonal"<<endl;
if(esferica){
glTranslated(-obs_x,-obs_y,-obs_z);
glRotatef(ang_x,1,0,0);
glRotatef(ang_y,0,1,0);
}
else{
glRotatef(ang_x,1.0,0.0,0.0);
glRotatef(ang_y,0.0,1.0,0.0);
glTranslated(-obs_x,-obs_y,-obs_z);
}
}
};
void camaraOrtho::girar(float x, float y){
//ratonEstatico(x, y);
if(ortogonal){
obs_x -=x;
obs_z -=y;
mirada_x-=x;
mirada_z-=y;
}
else{
ang_x+=y;
ang_y+=x;
}
}
void camaraOrtho::desplazar(char movimiento){
if(!esferica)
if(!ortogonal){
float xrotrad, yrotrad;
switch(movimiento){
case 's':
yrotrad = (ang_y / 180 * 3.141592654f);
xrotrad = (ang_x/ 180 * 3.141592654f);
obs_x -= float(sin(yrotrad));
obs_z += float(cos(yrotrad)) ;
obs_y += float(sin(xrotrad));
break;
case 'a':
yrotrad = (ang_y / 180 * 3.141592654f);
obs_x -= float(cos(yrotrad)) * 0.2;
obs_z -= float(sin(yrotrad)) * 0.2;
break;
case 'd':
yrotrad = (ang_y / 180 * 3.141592654f);
obs_x += float(cos(yrotrad)) * 0.2;
obs_z += float(sin(yrotrad)) * 0.2;
break;
case 'w':
yrotrad = (ang_y / 180 * 3.141592654f);
xrotrad = (ang_x / 180 * 3.141592654f);
obs_x += float(sin(yrotrad)) ;
obs_z -= float(cos(yrotrad)) ;
obs_y -= float(sin(xrotrad)) ;
break;
}
}
else{
switch(movimiento){
case 's':
cout << "obs_y ortogonal" << obs_y << endl;
zoom+= 1;
break;
case 'w':
cout << "obs_y ortogonal" << obs_y << endl;
zoom-= 1;
break;
}
cambiarProyeccion(ortogonal);
}
}
void camaraOrtho::reset(){
obs_x=backupValores[0];
obs_y=backupValores[1];
obs_z=backupValores[2];
mirada_x=backupValores[3];
mirada_y=backupValores[4];
mirada_z=backupValores[5];
vec_obs_x=backupValores[6];
vec_obs_y=backupValores[7];
vec_obs_z=backupValores[8];
ang_x=backupValores[9];
ang_y=backupValores[10];
ang_z=backupValores[11];
}
#endif
|
#include "BullyProcess.h"
#include "IdsGenerator.h"
#include <time.h>
#include <unistd.h>
#include "MessageRouter.h"
#include <boost/interprocess/ipc/message_queue.hpp>
#include <iostream>
#include <vector>
BullyProcess::BullyProcess():
StateMachine(ST_MAX_STATES)
{
m_Id = IdsGenerator::getInstance()->getUniqueId();
m_master_Id = -1;
m_Eq_name = "q#" + std::to_string(m_Id)+"Election";
m_Aq_name = "q#" + std::to_string(m_Id)+"Alive";
m_stop = false;
boost::interprocess::message_queue::remove(m_Eq_name.c_str());
boost::interprocess::message_queue::remove(m_Aq_name.c_str());
boost::interprocess::message_queue Emq (boost::interprocess::create_only
,m_Eq_name.c_str()
,100
,sizeof(ElectionMessage));
boost::interprocess::message_queue Amq (boost::interprocess::create_only
,m_Aq_name.c_str()
,100
,sizeof(AliveMessage));
}
void BullyProcess::stop()
{
m_stop = true;
BEGIN_TRANSITION_MAP // - Current State -
TRANSITION_MAP_ENTRY (EVENT_IGNORED) // ST_START
TRANSITION_MAP_ENTRY (ST_STOP) // ST_IDLE
TRANSITION_MAP_ENTRY (ST_STOP) // ST_ELECTION
TRANSITION_MAP_ENTRY (CANNOT_HAPPEN) // ST_STOP
END_TRANSITION_MAP(NULL)
}
void BullyProcess::start()
{
// m_thread = std::thread(&BullyProcess::Idle,this);
BEGIN_TRANSITION_MAP // - Current State -
TRANSITION_MAP_ENTRY (ST_IDLE) // ST_START
TRANSITION_MAP_ENTRY (CANNOT_HAPPEN) // ST_IDLE
TRANSITION_MAP_ENTRY (CANNOT_HAPPEN) // ST_ELECTION
TRANSITION_MAP_ENTRY (CANNOT_HAPPEN) // ST_STOP
END_TRANSITION_MAP(NULL)
}
std::string BullyProcess::getElectionQName() const
{
return m_Eq_name;
}
std::string BullyProcess::getAliveQName() const
{
return m_Aq_name;
}
STATE_DEFINE(BullyProcess, Start, NoEventData)
{
std::cout << "Starting .. " << std::endl;
}
STATE_DEFINE(BullyProcess, Stop, NoEventData)
{
if(m_thread.joinable()) m_thread.join();
}
STATE_DEFINE(BullyProcess, Idle, NoEventData)
{
if(AmITheMaster())
{
while(!m_stop)
{
std::cout << "I'm a live #" << std::to_string(m_Id) << " Master" << std::endl;
AliveMessage m(m_Id);
while(!MessageRouter::getInstance()->broadAliveMessage(m));
usleep((unsigned int)DURATION);
}
InternalEvent(ST_STOP);
}
else
{
bool MasterAlive = true;
do
{
std::cout << "I'm a live #" << std::to_string(m_Id) << std::endl;
boost::interprocess::message_queue mq(
boost::interprocess::open_only,
m_Aq_name.c_str());
boost::interprocess::message_queue::size_type recvd_size;
AliveMessage msg;
unsigned int priority;
boost::posix_time::ptime timeout = boost::posix_time::microsec_clock::universal_time() +
boost::posix_time::milliseconds((double)DELAY);
MasterAlive = mq.timed_receive(&msg, sizeof(msg), recvd_size, priority , timeout);
}
while(MasterAlive);
InternalEvent(ST_ELECTION);
}
}
STATE_DEFINE(BullyProcess, Election,NoEventData)
{
//m_master_Id = m_Id;
std::cout << "Election Start #" << std::endl;
ElectionMessage s_msg(m_Id,m_Id);
while(!MessageRouter::getInstance()->broadCastElectionMessage(s_msg));
boost::interprocess::message_queue mq(
boost::interprocess::open_only,
m_Eq_name.c_str());
boost::posix_time::ptime timeout = boost::posix_time::microsec_clock::universal_time() +
boost::posix_time::milliseconds((double)WAITING_DELAY);
int i = 0;
while(i++ < 7)
{
boost::interprocess::message_queue::size_type recvd_size;
ElectionMessage msg;
unsigned int priority;
if(mq.timed_receive(&msg, sizeof(msg), recvd_size, priority , timeout))
{
if(msg.m_data > m_master_Id)
m_master_Id = msg.m_data;
}
}
InternalEvent(ST_IDLE);
}
|
#include <ESP8266WiFi.h>
#include <Wire.h> //I2C needed for sensors
const char* ssid = "Netwok";
const char* password = "*****";
const int vane = A0;
const byte anemometer = 14;
unsigned int counter = 0;
unsigned int RPM = 0;
unsigned int winddir = 0.0;
const unsigned long period = 2500;
const float pi = 3.14159265;
const int radio = 30; //diametro del anemometro
float windspeedmph =0/ 0.445;
float windgustmph =0;
//Global Variables
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
byte minutes_10m; //Keeps track of where we are in wind gust/dir over last 10 minutes array of data
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void setup()
{
Serial.begin(9600);
Wire.begin(4, 5);
pinMode(14, INPUT_PULLUP);
delay(100);
Serial.println();
Serial.println();
Serial.println("Inicializando Sistema ");
Serial.print("Conectando a ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop()
{
windvelocity();
displaywind();
}
//Wind Speed Trigger/timer
void windvelocity()
{
windspeedmph =0;
counter = 0;
attachInterrupt(0, addcount, RISING);
unsigned long millis();
long starTime = millis();
while(millis() < starTime + period) {
}
detachInterrupt(0);
}
//RPM calc needed for wind speed calc
void RPMcalc(){
RPM=((counter*4)*60)/(period/1000); // Calculate revolutions per minute (RPM)
Serial.print("RPM ");
Serial.println(RPM);
}
void WindSpeed(){
windspeedmph = ((2 * pi * radio * RPM)/60) / 1000;
Serial.print("Velocidad ");
Serial.println(windspeedmph);
}
void addcount(){
counter++;
}
//obtenemos voltaje por la direccion
void Heading(){
float windDir =(analogRead(A0)* 5.00 / 1023.0); //wind direction
if ((windDir > 4.94)||(windDir < 0.01))
(winddir = 0.0);// North
if ((windDir >= 0.02)&&(windDir < 0.30))
(winddir = 22.5);//NNE
if ((windDir >= 0.31)&&(windDir < 0.72))
(winddir = 45.0);//NE
if ((windDir >= 0.72)&&(windDir < 0.99))
(winddir= 67.5);//ENE
if ((windDir >= 1.00)&&(windDir < 1.25))
(winddir = 90.0);//E
if ((windDir >= 1.26)&&(windDir < 1.52))
(winddir= 112.5);//ESE
if ((windDir >= 1.53)&&(windDir < 1.91))
(winddir= 135.0);//SE
if ((windDir >= 1.92)&&(windDir < 2.40))
(winddir = 157.5);//SSE
if ((windDir >= 2.41)&&(windDir < 2.73))
(winddir = 180.0);//S
if ((windDir >= 2.74)&&(windDir < 2.96))
(winddir = 202.5);//SSW
if ((windDir >= 2.97)&&(windDir < 3.37))
(winddir = 225.0);//SW
if ((windDir >= 3.38)&&(windDir < 3.55))
(winddir = 247.5);//WSW
if ((windDir >= 3.56)&&(windDir < 3.85))
(winddir = 270.0);//W
if ((windDir >= 4.13)&&(windDir < 4.06))
(winddir = 292.5);//WNW
if ((windDir >= 4.07)&&(windDir < 4.32))
(winddir = 315.0);//NW
if ((windDir >= 4.33)&&(windDir < 4.93))
(winddir = 337.5);//NNW
Serial.print("Direccion ");
Serial.println(winddir);
Serial.println(windDir);
}
//mostrar resultados
void displaywind()
{
Serial.print("RPM ");
Serial.println(RPM);
Serial.print("Velocidad ");
Serial.println(windspeedmph);
Serial.print("Direccion ");
Serial.println(winddir);
}
|
#ifndef MAGVIEW_H
#define MAGVIEW_H
#include <QWidget>
#include <QWidget>
#include <QtGui>
namespace Ui {
class Magview;
}
class Magview : public QWidget
{
Q_OBJECT
public:
explicit Magview(QWidget *parent = 0);
~Magview();
void setmagyaw(const qreal &value);
protected:
void paintEvent(QPaintEvent *);
public:
void set_mag(int start_x,int start_y,int width,int heigth,int other);
private:
Ui::Magview *ui;
qreal yaw;
int START_X,START_Y,WIDTH,HEIGTH,OTHER;
};
#endif // MAGVIEW_H
|
#include "world.hpp"
#include "constants.hpp"
#include <SFML/Graphics.hpp>
#include <iostream>
#include "miscFunctions.hpp"
#include "plane3d.hpp"
#include <assert.h>
World::World ():
window (sf::VideoMode (800, 600), "Game", sf::Style::Titlebar | sf::Style::Close)
{
exists = true;
// Set up the spriteMap
spriteMap.loadFromFile ("spriteMap.png");
// Create the player
Vector3d playerStartingPosition (PLAYER_START_X, PLAYER_START_Y);
Creature p (spriteMap, 10, PLAYER_SPEED, playerStartingPosition);
playerCreatureIds.push_back (addCreature (p));
// Set up the block grid
// Actually shows up mirrored across the y = -x axis
std::vector<std::vector<int>> tempGrid =
{{0,0,0,0,0,0,0,0,0,},
{0,0,0,0,0,0,0,0,0,},
{0,0,0,0,0,0,0,0,0,},
{0,0,0,0,0,0,0,0,0,},
{0,0,0,0,0,0,0,0,0,},
{0,0,0,0,0,0,0,1,0,},
{0,0,0,0,0,0,0,0,0,}};
/*{{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1},
{1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1},
{1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1},
{1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1},
{1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0},
{1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0},
{1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1},
{1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1},
{1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1},
{1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1},
{1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}};*/
// For the temp grid
for (unsigned int x = 0; x != tempGrid.size (); ++x)
{
std::vector<Block> newVect;
grid.push_back (newVect);
for (unsigned int y = 0; y != tempGrid[x].size (); ++y)
{
if (tempGrid[x][y] == 0)
{
BlockType type = GRASS;
grid[x].push_back (Block (spriteMap, type, x, y));
}
if (tempGrid[x][y] == 1)
{
BlockType type = STONE;
grid[x].push_back (Block (spriteMap, type, x, y));
}
}
}
}
int World::addCreature (Creature a)
{
++creatureIdCounter;
creatureMap[creatureIdCounter] = a;
return creatureIdCounter;
}
void World::getInput ()
{
// First catch events
while (window.pollEvent (event))
{
// Close the window and exit the game if the close button is pressed.
if (event.type == sf::Event::Closed)
{
window.close ();
exists = false;
}
}
// Now check currently pressed keys
// The movement keys
Vector3d movement;
if (sf::Keyboard::isKeyPressed (sf::Keyboard::Right))
{
movement.x += 1;
}
if (sf::Keyboard::isKeyPressed (sf::Keyboard::Left))
{
movement.x -= 1;
}
if (sf::Keyboard::isKeyPressed (sf::Keyboard::Up))
{
movement.y -= 1;
}
if (sf::Keyboard::isKeyPressed (sf::Keyboard::Down))
{
movement.y += 1;
}
// Change the player's creature's velocity based on the pressed keys
creatureMap[playerCreatureIds[0]].setMovement (movement);
}
void World::update ()
{
// Update the time since last tick
timeSinceLastTick = clock.restart ().asSeconds ();
// Move all the creatures
for (auto iter = creatureMap.begin (); iter != creatureMap.end (); ++iter)
{
moveCreature (iter->first);
}
return;
}
void World::display ()
{
// Blank the screen with white
window.clear (sf::Color::Black);
// Draw the grid
for (unsigned int x = 0; x != grid.size (); ++x)
{
for (unsigned int y = 0; y != grid[x].size (); ++y)
{
window.draw (grid[x][y].sprite);
}
}
// Draw the player
window.draw (creatureMap[playerCreatureIds[0]].sprite);
window.display ();
return;
}
void World::moveCreature (int id)
{
Vector3d movement = creatureMap[id].getVelocity () * timeSinceLastTick;
// While there is still distance to move
//while (movement.length () != 0) // TODO: change this back after testing
{
// Move the creature by the movement vector
creatureMap[id].setPosition (creatureMap[id].getPosition () + movement);
// The hitbox the creature's hitbox will be collided with
Hitbox otherHitbox;
// Check everything it can possibly collide with
// For every hitbox in the whole block grid
for (unsigned int x = 0; x != grid.size (); ++x)
{
for (unsigned int y = 0; y != grid[x].size (); ++y)
{
// If the creature is colliding with it, add its hitbox to the other hitbox
if (creatureMap[id].hitbox.isOverlapping (grid[x][y].hitbox))
{
otherHitbox.addHitbox (grid[x][y].hitbox);
}
}
}
if (!otherHitbox.isEmpty ())
{
double overlapDepth = creatureMap[id].hitbox.getOverlapDepth (otherHitbox, movement);
// Move the creature back by the overlap depth
creatureMap[id].setPosition (creatureMap[id].getPosition () - movement.direction () * overlapDepth);
// The new movement vector is the cut movement projected onto the plane tangent to the collision
Plane3d newPlaneOfMotion = creatureMap[id].hitbox.getCollisionTangentPlane (otherHitbox);
movement = (movement.direction () * overlapDepth).projectionOnto (newPlaneOfMotion);
}
else // If the other hitbox is empty
{
movement = Vector3d (0, 0, 0);
}
}
return;
}
|
/*
* msg
*/
#ifndef MSG_H_
#define MSG_H_
class Msg {
public:
// unicode
static void Error(const wchar_t *msg, ... );
static void Warning(const wchar_t *msg, ... );
static void Info(const wchar_t *msg, ... );
// ansi
static void Error(const char *msg, ... );
static void Warning(const char *msg, ... );
static void Info(const char *msg, ... );
};
#endif
|
#ifndef WBPENEG_H
#define WBPENEG_H
#include "wbpeunaryop.h"
class WBPENeg : public WBPEUnaryOp
{
public:
WBPENeg();
virtual ~WBPENeg();
DEFINE_WBPE_FACTORY( Neg );
virtual void Evaluate( const WBParamEvaluator::SPEContext& Context, WBParamEvaluator::SEvaluatedParam& EvaluatedParam ) const;
};
#endif // WBPENEG_H
|
#include "iter.h"
bool ContOctree::Iter::at_leaf() const { return !at_node; }
bool ContOctree::Iter::at_bottom() const { return level == 0; }
bool ContOctree::Iter::at_top() const { return level == top_level; }
|
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
for (int i = 0; i <10 ; i++)
{
//incremento//
cout<<i<<" ";
}
cout<<endl;
cout<<endl;
for (int i = 9; i >=0 ; i--)
{
//decremento//
cout<<i<<" ";
}
cout<<endl;
cout<<endl;
for (int i = 0; i <=10 ; i++)
{
//roptura de un ciclo for//
cout<<i<<" ";
if(i==115)
{
break;
}
}
cout<<endl;
cout<<endl;
for (int i = 0; i <=10 ; i++)
{
//continue en for//
if(i==5)
{
continue;
}
cout<<i<<" ";
}
return 0;
}
|
#pragma once
#include "analysis/physics/Physics.h"
#include "analysis/utils/Fitter.h"
#include "analysis/utils/particle_tools.h"
#include "analysis/plot/PromptRandomHist.h"
#include "base/WrapTTree.h"
#include "root-addons/cbtaps_display/TH2CB.h"
#include "TLorentzVector.h"
namespace ant {
namespace analysis {
namespace physics {
class PID_Energy_etaDalitz : public Physics {
protected:
TH2* h_eegPID = nullptr;
TH1D* h_counts = nullptr;
TH1D* h_pTheta = nullptr;
TH1D* h_protonVeto = nullptr;
TH2* h_eta = nullptr;
TH2* h_proton = nullptr;
static constexpr double ETA_IM = 547.853;
static constexpr double ETA_SIGMA = 50.;
struct Tree_t : WrapTTree {
Tree_t();
ADD_BRANCH_T(TLorentzVector, eta)
ADD_BRANCH_T(TLorentzVector, eta_fit)
ADD_BRANCH_T(TLorentzVector, missing_momentum)
ADD_BRANCH_T(double, copl)
ADD_BRANCH_T(double, copl_final)
ADD_BRANCH_T(double, TaggW)
ADD_BRANCH_T(double, TaggE)
ADD_BRANCH_T(double, TaggT)
ADD_BRANCH_T(unsigned, TaggCh)
ADD_BRANCH_T(double, chi2)
ADD_BRANCH_T(double, probability)
ADD_BRANCH_T(unsigned, iterations)
ADD_BRANCH_T(unsigned, nCands)
ADD_BRANCH_T(double, CBSumE)
ADD_BRANCH_T(double, CBAvgTime)
};
struct PerChannel_t {
std::string title;
TH2* eegPID = nullptr;
TH1D* steps = nullptr;
TH1D* etaIM = nullptr;
TH1D* etaIM_fit = nullptr;
TH1D* etaIM_cand = nullptr;
TH1D* etaIM_final = nullptr;
TH1D* MM = nullptr;
TH1D* hCopl = nullptr;
TH1D* hCopl_final = nullptr;
TH1D* hChi2 = nullptr;
TH1D* hProb = nullptr;
TH1D* hIter = nullptr;
TH2* proton_E_theta = nullptr;
PerChannel_t(const std::string& Title, HistogramFactory& hf);
void Show();
void Fill(const TEventData& d);
};
std::map<std::string, PerChannel_t> channels;
Tree_t t;
PromptRandom::Switch promptrandom;
utils::KinFitter kinfit;
using uncertainty_model_t = utils::UncertaintyModels::Optimized_Oli1;
template<typename T>
void shift_right(std::vector<T>&);
public:
PID_Energy_etaDalitz(const std::string& name, OptionsPtr opts);
static APLCON::Fit_Settings_t MakeFitSettings(unsigned);
virtual void ProcessEvent(const TEvent& event, manager_t& manager) override;
virtual void ShowResult() override;
};
}}} // namespace ant::analysis::physics
|
#ifndef EXPORTCURVEDIALOG_H
#define EXPORTCURVEDIALOG_H
#include <QDialog>
#include <QMovie>
#include "qstring.h"
#include "exportCurveThread.h"
namespace Ui {
class ExportCurveDialog;
}
class ExportCurveDialog : public QDialog
{
Q_OBJECT
public:
explicit ExportCurveDialog(QWidget *parent = 0);
~ExportCurveDialog();
void DisplayMovie(QString MovieMsg);
ExportCurveThread* exportThreadPtr;
private:
Ui::ExportCurveDialog *ui;
QMovie *movie;
private slots:
void slot_changeExportText(QString MovieMsg);
// void stopMovie();
// void keyPressEvent(QKeyEvent *event);
void on_pushButton_clicked();
signals:
void sig_stopFileExport();
};
#endif // REPORTFILEDIALOG_H
|
/*
* SPDX-FileCopyrightText: (C) 2013-2022 Daniel Nicoletti <dantti12@gmail.com>
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "common.h"
#include "controller.h"
#include "dispatchtypepath_p.h"
#include "utils.h"
#include <QBuffer>
#include <QDebug>
#include <QRegularExpression>
using namespace Cutelyst;
DispatchTypePath::DispatchTypePath(QObject *parent)
: DispatchType(parent)
, d_ptr(new DispatchTypePathPrivate)
{
}
DispatchTypePath::~DispatchTypePath()
{
delete d_ptr;
}
QByteArray DispatchTypePath::list() const
{
Q_D(const DispatchTypePath);
QRegularExpression multipleSlashes(QLatin1String("/{1,}"));
QVector<QStringList> table;
QStringList keys = d->paths.keys();
keys.sort(Qt::CaseInsensitive);
for (const QString &path : keys) {
const auto paths = d->paths.value(path);
for (Action *action : paths) {
QString _path = QLatin1Char('/') + path;
if (action->attribute(QLatin1String("Args")).isEmpty()) {
_path.append(QLatin1String("/..."));
} else {
for (int i = 0; i < action->numberOfArgs(); ++i) {
_path.append(QLatin1String("/*"));
}
}
_path.replace(multipleSlashes, QLatin1String("/"));
QString privateName = action->reverse();
if (!privateName.startsWith(QLatin1Char('/'))) {
privateName.prepend(QLatin1Char('/'));
}
table.append({_path, privateName});
}
}
return Utils::buildTable(table, {QLatin1String("Path"), QLatin1String("Private")}, QLatin1String("Loaded Path actions:"));
}
Cutelyst::DispatchType::MatchType DispatchTypePath::match(Context *c, const QString &path, const QStringList &args) const
{
Q_D(const DispatchTypePath);
QString _path = path;
if (_path.isEmpty()) {
_path = QStringLiteral("/");
}
const auto it = d->paths.constFind(_path);
if (it == d->paths.constEnd()) {
return NoMatch;
}
MatchType ret = NoMatch;
int numberOfArgs = args.size();
for (Action *action : it.value()) {
// If the number of args is -1 (not defined)
// it will slurp all args so we don't care
// about how many args was passed
if (action->numberOfArgs() == numberOfArgs) {
Request *request = c->request();
request->setArguments(args);
request->setMatch(_path);
setupMatchedAction(c, action);
return ExactMatch;
} else if (action->numberOfArgs() == -1 &&
!c->action()) {
// Only setup partial matches if no action is
// currently set
Request *request = c->request();
request->setArguments(args);
request->setMatch(_path);
setupMatchedAction(c, action);
ret = PartialMatch;
}
}
return ret;
}
bool DispatchTypePath::registerAction(Action *action)
{
Q_D(DispatchTypePath);
bool ret = false;
const auto attributes = action->attributes();
const auto range = attributes.equal_range(QLatin1String("Path"));
for (auto i = range.first; i != range.second; ++i) {
if (d->registerPath(*i, action)) {
ret = true;
}
}
// We always register valid actions
return ret;
}
bool DispatchTypePath::inUse()
{
Q_D(const DispatchTypePath);
return !d->paths.isEmpty();
}
QString DispatchTypePath::uriForAction(Cutelyst::Action *action, const QStringList &captures) const
{
QString ret;
if (captures.isEmpty()) {
const auto attributes = action->attributes();
auto it = attributes.constFind(QStringLiteral("Path"));
if (it != attributes.constEnd()) {
const QString &path = it.value();
if (path.isEmpty()) {
ret = QStringLiteral("/");
} else if (!path.startsWith(QLatin1Char('/'))) {
ret = QLatin1Char('/') + path;
} else {
ret = path;
}
}
}
return ret;
}
bool DispatchTypePathPrivate::registerPath(const QString &path, Action *action)
{
QString _path = path;
if (_path.startsWith(QLatin1Char('/')) && !_path.isEmpty()) {
_path.remove(0, 1);
}
if (_path.isEmpty()) {
_path = QStringLiteral("/");
}
auto it = paths.find(_path);
if (it != paths.end()) {
int actionNumberOfArgs = action->numberOfArgs();
for (const Action *regAction : it.value()) {
if (regAction->numberOfArgs() == actionNumberOfArgs) {
qCCritical(CUTELYST_DISPATCHER_PATH) << "Not registering Action"
<< action->name()
<< "of controller"
<< action->controller()->objectName()
<< "because it conflicts with"
<< regAction->name()
<< "of controller"
<< regAction->controller()->objectName();
return false;
}
}
it.value().push_back(action);
std::sort(it.value().begin(), it.value().end(), [](Action *a, Action *b) -> bool {
return a->numberOfArgs() < b->numberOfArgs();
});
} else {
paths.insert(_path, {action});
}
return true;
}
#include "moc_dispatchtypepath.cpp"
|
/*******************************************************************************
* Cristian Alexandrescu *
* 2163013577ba2bc237f22b3f4d006856 *
* 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 *
* bc9a53289baf23d369484f5343ed5d6c *
*******************************************************************************/
/* Problem 12853 - The Pony Cart Problem */
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
int nNoCases;
cin >> nNoCases;
for (int nCaseLoop = 1; nCaseLoop <= nNoCases; nCaseLoop++) {
double fD, fN;
cin >> fD >> fN;
cout << "Case " << nCaseLoop << ": " << setprecision(3) << fixed << atan(static_cast<double>(1.0)) * 8 * (fD / (fN - 1) + fD) << endl;
}
return 0;
}
|
#include <iostream>
#include <mpi.h>
#include <vector>
#include <future>
using namespace std;
int N = 5;
bool pred(vector<int> &v)
{
return (v[0] % 2 == 0) && (v[v.size() - 1] % 2 == 0);
}
vector< pair<int, int> > splitWorkload(int n, int t) {
vector< pair<int, int> > intervals;
int index = 0;
int step = n / t;
int mod = n % t;
while (index < n) {
intervals.push_back(pair<int, int>(index, index + step + (mod > 0)));
index += step + (mod > 0);
mod--;
}
return intervals;
}
vector< pair<int, int> > splitWorkload2(int n, int t) {
vector< pair<int, int> > intervals;
int index = 0;
int step = n / t;
int mod = n % t;
while (index < n) {
intervals.push_back(pair<int, int>(index, index + step + (mod > 0)));
index += step + (mod > 0);
mod--;
}
return intervals;
}
vector<int> backtracking(vector<int> prefix, int T) {
if (prefix.size() == N)
{
if (pred(prefix))
return prefix;
return vector<int>();
}
int branches = N - prefix.size();
if (T == 1 || T < branches)
{
for (int i = 0; i < N; i++)
{
if (find(prefix.begin(), prefix.end(), i) == prefix.end())
{
prefix.push_back(i);
vector<int> ret = backtracking(prefix, T);
if (!ret.empty())
return ret;
prefix.pop_back();
}
}
}
else
{
for (int i = 0; i < N; i++)
{
if (find(prefix.begin(), prefix.end(), i) == prefix.end())
{
vector<int> next_prefix(prefix);
next_prefix.push_back(i);
vector<int> ret = backtracking(next_prefix, T / branches);
if (!ret.empty())
return ret;
next_prefix.pop_back();
}
}
}
return vector<int>();
}
int main()
{
// Initialize the MPI environment
MPI_Init(NULL, NULL);
// Get the number of processes
int np;
MPI_Comm_size(MPI_COMM_WORLD, &np);
// Get the rank of the process
int pid;
MPI_Comm_rank(MPI_COMM_WORLD, &pid);
if (pid == 0)
{
vector<vector<int>> solutions;
if (np == 1)
{
// master face si drege
vector<int> ret = backtracking(vector<int>(), np);
if (!ret.empty())
solutions.push_back(ret);
}
else if (np <= N)
{
vector<pair<int, int>> intervals = splitWorkload(N, np);
for (int p = 1; p < np; p++)
{
// send data to child
int begin = intervals[p].first;
int end = intervals[p].second;
int metadata[2];
metadata[0] = begin;
metadata[1] = end;
MPI_Ssend(metadata, 2, MPI_INT, p, 0, MPI_COMM_WORLD);
}
// master does its part
for (int i = intervals[0].first; i < intervals[0].second; i++)
{
cout << "Master doing his stuff" << endl;
vector<int> prefix;
prefix.push_back(i);
vector<int> ret = backtracking(prefix, 1);
if (!ret.empty())
solutions.push_back(ret);
prefix.pop_back();
}
MPI_Status status;
for (int p = 1; p < np; p++)
{
cout << "Master wants data from " << p << endl;
// receive data from children
int result[10];
MPI_Recv(result, N, MPI_INT, p, 1, MPI_COMM_WORLD, &status);
cout << "Master received data from " << p << endl;
vector<int> recv;
for (int i = 0; i < N; i++)
{
recv.push_back(result[i]);
cout << result[i] << " ";
}
cout << endl;
solutions.push_back(recv);
}
}
else if (np > N)
{
for (int p = 1; p < N; p++)
{
int metadata[] = { -1, -1, -1, -1, -1 };
if (p < np - N)
metadata[2] = floor(np / N);
else
metadata[2] = 0;
metadata[3] = 1;
cout << pid << ": set metadata[4] = " << metadata[4] << endl;
metadata[4] = p;
MPI_Ssend(metadata, 5, MPI_INT, p, 0, MPI_COMM_WORLD);
}
// master does work
////////////////////////////
vector<int> prefix;
prefix.push_back(0);
int extraProcs = floor(np / N);
if (extraProcs == 0)
{
for (int i = 0; i < N; i++)
{
if (find(prefix.begin(), prefix.end(), i) == prefix.end())
{
prefix.push_back(i);
vector<int> ret = backtracking(prefix, 1);
if (!ret.empty())
solutions.push_back(ret);
prefix.pop_back();
}
}
}
else
{
vector<pair<int, int>> intervals = splitWorkload(N, extraProcs + 1);
for (pair<int, int> p : intervals) {
cout << pid << ": intervals for extra: " << p.first << " " << p.second << endl;
}
int siblingProc = pid + N;
for (int p = 0; p < extraProcs; p++)
{
// send data to child
int begin = intervals[p + 1].first;
int end = intervals[p + 1].second;
int metadata[] = { -1, -1, -1, -1, -1 };
metadata[2] = 0;
metadata[3] = prefix.size();
for (int i = 0; i < prefix.size(); i++)
metadata[4 + i] = prefix[i];
cout << pid << ": sending data to " << siblingProc << " " << begin << " " << end << endl;
MPI_Ssend(metadata, 5, MPI_INT, siblingProc, 0, MPI_COMM_WORLD);
siblingProc += N;
}
}
////////////////////////
for (int p = 1; p < np; p++)
{
cout << "Master wants data from " << p << endl;
int result[10];
MPI_Status status;
MPI_Recv(result, N, MPI_INT, p, 1, MPI_COMM_WORLD, &status);
cout << "Master received data from " << p << endl;
vector<int> recv;
for (int i = 0; i < N; i++)
{
recv.push_back(result[i]);
cout << result[i] << " ";
}
cout << endl;
solutions.push_back(recv);
}
}
for (vector<int> vec : solutions)
{
cout << "> ";
for (int i : vec)
cout << i << " ";
cout << endl;
}
cout << "Master is ded" << endl;
}
else
{
MPI_Status status;
if (np <= N)
{
int metadata[2];
MPI_Recv(metadata, 2, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
cout << pid << ": " << metadata[0] << " " << metadata[1] << endl;
vector<vector<int>> solutions;
for (int i = metadata[0]; i < metadata[1]; i++)
{
vector<int> prefix;
prefix.push_back(i);
vector<int> ret = backtracking(prefix, 1);
if (!ret.empty())
solutions.push_back(ret);
prefix.pop_back();
}
if (!solutions.empty())
{
cout << pid << ": found " << solutions[0][0] << endl;
int result[10];
for (int i = 0; i < N; i++)
result[i] = solutions[0][i];
MPI_Ssend(result, N, MPI_INT, 0, 1, MPI_COMM_WORLD);
}
else
{
cout << pid << ": could not find any solutions" << endl;
int result[10];
for (int i = 0; i < N; i++)
result[i] = 0;
MPI_Ssend(result, N, MPI_INT, 0, 1, MPI_COMM_WORLD);
}
}
else
{
int metadata[] = { -1, -1, -1, -1, -1 };
cout << pid << ": waiting metadata" << endl;
MPI_Recv(metadata, 5, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status);
int extraProcs = metadata[2];
int prefix_len = metadata[3];
vector<int> prefix;
for (int i = 0; i < prefix_len; i++)
{
prefix.push_back(metadata[4 + i]);
}
cout << pid << ": received " << metadata[2] << " " << metadata[3] << endl;
vector<vector<int>> solutions;
cout << pid << " extra procs: " << extraProcs << endl;
if (extraProcs == 0)
{
for (int i = 0; i < N; i++)
{
if (find(prefix.begin(), prefix.end(), i) == prefix.end())
{
prefix.push_back(i);
vector<int> ret = backtracking(prefix, 1);
if (!ret.empty())
solutions.push_back(ret);
prefix.pop_back();
}
}
if (!solutions.empty())
{
cout << pid << ": found " << endl;
for (int i = 0; i < solutions.size(); i++)
{
for (int j = 0; j < solutions[i].size(); j++)
cout << solutions[i][j] << " ";
cout << endl;
}
int result[10];
for (int i = 0; i < N; i++)
result[i] = solutions[0][i];
MPI_Ssend(result, N, MPI_INT, 0, 1, MPI_COMM_WORLD);
}
else
{
cout << pid << ": could not find any solutions" << endl;
int result[10];
for (int i = 0; i < N; i++)
result[i] = 0;
MPI_Ssend(result, N, MPI_INT, 0, 1, MPI_COMM_WORLD);
}
}
else
{
vector<pair<int, int>> intervals = splitWorkload(N, extraProcs + 1);
for (pair<int, int> p : intervals) {
cout << pid << ": intervals for extra: " << p.first << " " << p.second << endl;
}
int siblingProc = pid + N;
for (int p = 0; p < extraProcs; p++)
{
// send data to child
int begin = intervals[p + 1].first;
int end = intervals[p + 1].second;
int metadata[] = { -1, -1, -1, -1, -1 };
metadata[2] = 0;
metadata[3] = prefix.size();
for (int i = 0; i < prefix.size(); i++)
metadata[4 + i] = prefix[i];
cout << pid << ": sending data to " << siblingProc << " " << begin << " " << end << endl;
MPI_Ssend(metadata, 5, MPI_INT, siblingProc, 0, MPI_COMM_WORLD);
siblingProc += N;
}
}
}
}
// Finalize the MPI environment.
MPI_Finalize();
return 0;
}
|
// Copyright [2015] <lgb (LiuGuangBao)>
//=====================================================================================
//
// Filename: kvStore.cpp
//
// Description: key/value 数据库
//
// Version: 1.0
// Created: 2015年03月16日 14时46分37秒
// Revision: none
// Compiler: gcc
//
// Author: lgb (LiuGuangBao), easyeagel@gmx.com
// Organization: ezbty.org
//
//=====================================================================================
//
#include"kvStore.hpp"
#include"gccWaringDisable.hpp"
#include"leveldb/include/leveldb/c.h"
#include"leveldb/include/leveldb/cache.h"
#include"leveldb/include/leveldb/comparator.h"
#include"leveldb/include/leveldb/db.h"
#include"leveldb/include/leveldb/env.h"
#include"leveldb/include/leveldb/filter_policy.h"
#include"leveldb/include/leveldb/iterator.h"
#include"leveldb/include/leveldb/options.h"
#include"leveldb/include/leveldb/slice.h"
#include"leveldb/include/leveldb/status.h"
#include"leveldb/include/leveldb/table.h"
#include"leveldb/include/leveldb/table_builder.h"
#include"leveldb/include/leveldb/write_batch.h"
#include"gccWaringEnable.hpp"
namespace core
{
class KVStoreLeveldb: public KVStore
{
static leveldb::Slice cast(const char* key, size_t keySize)
{
return leveldb::Slice(key , keySize);
}
static inline ErrorCode cast(const leveldb::Status& )
{
return ErrorCode();
}
public:
KVStoreLeveldb(const char* dir)
{
options_.create_if_missing = true;
options_.write_buffer_size = 64*1024*1024;
options_.block_cache=leveldb::NewLRUCache(128*1024);
leveldb::Status status = leveldb::DB::Open(options_, dir, &db_);
};
void get(const char* key, size_t keySize, GetCall&& call) final
{
const auto& lkey=cast(key, keySize);
std::string dest;
leveldb::Status st=db_->Get(leveldb::ReadOptions(), lkey, &dest);
call(cast(st), dest.data(), dest.size());
}
void set(ErrorCode& ec, const char* key, size_t keySize, const char* val, size_t valSize) final
{
const auto& lkey=cast(key, keySize);
const auto& lval=cast(val, valSize);
leveldb::Status st=db_->Put(leveldb::WriteOptions(), lkey, lval);
ec=cast(st);
}
void remove(ErrorCode& ec, const char* key, size_t keySize) final
{
const auto& lkey=cast(key, keySize);
leveldb::Status st=db_->Delete(leveldb::WriteOptions(), lkey);
ec=cast(st);
}
private:
leveldb::DB* db_=nullptr;
leveldb::Options options_;
};
KVStore::~KVStore()=default;
}
|
#include "TCPServer.h"
#include <chrono>
#include <pthread.h>
TCPServer::TCPServer(const uint16_t port, _handler_function handler) : port(port), handler(handler) {};
TCPServer::~TCPServer(){
if(_status == status::up){
stop();
}
}
void TCPServer::setHandler(_handler_function handler){this->handler = handler;}
uint16_t TCPServer::getPort() const {return port;}
uint16_t TCPServer::setPort(const uint16_t port){
this->port = port;
restart();
return port;
}
TCPServer::status TCPServer::restart(){
if(_status == status::up){
stop();
}
return start();
}
void TCPServer::joinLoop() {handler_thread.join();}
int TCPServer::Client::loadData() {return recv(socket, buffer, buffer_size, 0);}
char* TCPServer::Client::getData() {return buffer;}
bool TCPServer::Client::sendData(const char* buffer, const size_t size) const {
if(send(socket, buffer, size, 0) < 0) {return false;}
return true;
}
TCPServer::status TCPServer::start(){
struct sockaddr_in server;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(port);
server.sin_family = AF_INET;
serv_socket = socket(AF_INET, SOCK_STREAM, 0);
if(serv_socket == -1) return _status = status::error_socket_init;
if(bind(serv_socket, (struct sockaddr*)&server, sizeof(server)) < 0) return _status = status::error_socket_bind;
if(listen(serv_socket, 3) < 0) return _status = status::error_socket_listening;
return _status;
}
void TCPServer::stop() {
_status = status::close;
close(serv_socket);
joinLoop();
for(std::thread& cl_thr : client_handler_threads){
cl_thr.join();
}
client_handler_threads.clear();
client_handling_end.clear();
}
void TCPServer::handlingLoop(){
while(_status == status::up){
int client_socket;
struct sockaddr_in client_addr;
int addrlen = sizeof(struct sockaddr_in);
if((client_socket = accept(serv_socket, (struct sockaddr*)&client_addr, (socklen_t*)&addrlen)) >= 0 && _status == status::up){
client_handler_threads.push_back(std::thread([this, &client_socket, &client_addr]{
handler(Client(client_socket, client_addr));
client_handling_end.push_back(std::this_thread::get_id());
}));
}
if(!client_handling_end.empty()){
for(std::list<std::thread::id>::iterator id_it = client_handling_end.begin(); !client_handling_end.empty(); id_it = client_handling_end.begin()){
for(std::list<std::thread>::iterator thr_it = client_handler_threads.begin(); thr_it == client_handler_threads.end(); ++thr_it){
if(thr_it->get_id() == *id_it){
thr_it->join();
client_handler_threads.erase(thr_it);
client_handling_end.erase(id_it);
break;
}
}
}
}
std::this_thread::sleep_for(std::chrono::microseconds(50));
}
}
TCPServer::Client::Client(int socket, struct sockaddr_in address) : socket(socket), address(address) {}
TCPServer::Client::~Client(){
shutdown(socket, 0);
close(socket);
}
uint32_t TCPServer::Client::getHost() { return address.sin_addr.s_addr;}
uint16_t TCPServer::Client::getPort() {return address.sin_port;}
|
/*************************************************************
* > File Name : P2419.cpp
* > Author : Tony_Wong
* > Created Time : 2019/11/13 07:14:00
* > Algorithm :
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0; int f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
return x * f;
}
const int maxn = 110;
int n, m, G[maxn][maxn], ans;
int main() {
n = read(); m = read();
for (int i = 1; i <= m; ++i) {
int u = read(), v = read();
G[u][v] = 1;
}
for (int k = 1; k <= n; ++k)
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
G[i][j] |= G[i][k] & G[k][j];
for (int i = 1; i <= n; ++i) {
int cnt = 1;
for (int j = 1; j <= n; ++j)
if (i != j) cnt &= G[i][j] | G[j][i];
ans += cnt;
}
printf("%d\n", ans);
return 0;
}
|
/*
YAHA SE MAT CHAPNA BC. IIIT KA HU. COPYCASE AAYEGA.
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
#define rep(i,l,r) for(int i=l;i<r;i++)
#define rep2(i,r,l) for(int i=r;i>l;i--)
#define sz(a) (int)a.size()
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
#define nl "\n"
#define pii pair<int,int>
const int c=2e5+5;
int strength[c],level[c],sizee[c],visited[c],tree_even[4*c],tree_odd[4*c],M;
std::vector<int> v[c],preorder;
map <int,int> Map;
ll st[c], ft[c], tim;
void dfs(int n,int p,int lev=0)
{
st[n]=++tim;
level[n]=lev;
for(auto x:v[n])
{
if(x==p) continue;
dfs(x,n,lev+1);
}
ft[n]=tim;
}
void update(int index,int s,int e,int l,int r,int val)
{
if(e<l || s>r) return;
if(s>=l && e<=r)
{
if(M==0) tree_even[index]+=val , cout<<"index ev "<<index<<endl;
else tree_odd[index]+=val , cout<<"index od "<<index<<endl;;
return;
}
int mid=(s+e)/2;
update(2*index,s,mid,l,r,val);
update(2*index+1,mid+1,e,l,r,val);
return;
}
int sum;
int query(int index,int l,int r,int i)
{
if(i<l || i>r) return 0;
if(l<=i && i<=r)
{
if(M==0) sum+= tree_even[index]-tree_odd[index];
else sum+= tree_odd[index]-tree_even[index];
}
if(l==r) return 0;
int mid=(l+r)/2;
query(2*index,l,mid,i);
query(2*index+1,mid+1,r,i);
return 0;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL),cout.tie(NULL);
int n,m,v1,v2,type,node,upd,start;
cin>>n>>m;
rep(i,1,n+1) cin>>strength[i];
rep(i,0,n-1)
{
cin>>v1>>v2;
v[v1].pb(v2);
v[v2].pb(v1);
}
preorder.pb(0);
dfs(1,0);
cout<<endl;
// for(ll i=0; i<preorder.size(); i++)cout<<preorder[i]<<" ";
for(ll i=0; i<=n; i++)cout<<i<<" "<<st[i]<<" "<<ft[i]<<endl;//;
// for(auto now : Map) cout<<now.first<<" "<<now.second<<endl;
while(m--)
{
cin>>type;
if(type==1)
{
cin>>node>>upd;
M=level[node]%2;
cout<<node<<" - "<<M<<endl;
update(1,1,n,st[node],ft[node],upd);
cout<<endl;
}
else
{
cin>>node;
M=level[node]%2;
sum=strength[node];
query(1,1,n,st[node]);
cout<<sum<<nl;
}
}
return 0;
}
|
/*
* Plan.h
*
* Created on: Jun 21, 2015
* Author: colman
*/
#ifndef PLAN_H_
#define PLAN_H_
#include "wayPoint.h"
#include "Behavior.h"
#include "Globals.h"
class Plan {
public:
Plan(vector<wayPoint*> *Wplst);
vector<PositionState*> _plan;
virtual ~Plan();
};
#endif /* PLAN_H_ */
|
// https://codility.com/programmers/lessons/4-counting_elements/perm_check/
// you can use includes, for example:
// #include <algorithm>
#include <algorithm> // std::find
#include <vector>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
std::vector<int> count(A.size(), 0);
// Count the elements
for (int i : A)
{
// If the number's way too big
// it surely is not a part of permutation
if (static_cast<unsigned>(i) > count.size())
return 0;
else
count[i-1]++;
// If there's a value that's not unique
if (count[i-1] > 1)
return 0;
}
// If there's a number that's missing
if(std::find(count.begin(), count.end(), 0) != count.end())
return 0;
// If the given vector A contains a valid permutation
return 1;
}
|
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cstring>
#include <string>
#include <queue>
#include <deque>
#include <vector>
#include <stack>
#include <map>
#include <regex>
#include <math.h>
#define MAX 11
#define INF 987654321
using namespace std;
typedef pair<int, int> pii;
struct ground
{
int r; int c; int d; int line; int corner;
ground(int rr, int cc, int dd, int ll, int cor)
{
r = rr; c = cc; d = dd; line = ll; corner = cor;
}
};
bool is_corner(int a, int b)
{
if(a == -1) return false;
else if(a == 0 || a == 1)
{
if(b == 3 || b == 2) return true;
else return false;
}
else
{
if(b == 0 || b == 1) return true;
else return false;
}
}
bool is_reverse(int a, int b)
{
if(a == 0 && b == 1) return true;
else if(a == 1 && b == 0) return true;
else if(a == 2 && b == 3) return true;
else if(a == 3 && b == 2) return true;
return false;
}
int solution(vector<vector<int>> board) {
int answer = 999999999;
int dr[4] = {1, -1, 0, 0};
int dc[4] = {0, 0, -1, 1};
int cost[25][25] = {0,};
for(int i = 0; i < board.size(); i++)
{
for(int j = 0; j < board.size(); j++)
{
cost[i][j] = 99999999;
}
}
queue<ground> q;
q.push(ground(0,0,-1,0,0));
cost[0][0] = 0;
while (!q.empty())
{
int r = q.front().r;
int c = q.front().c;
int d = q.front().d;
int l = q.front().line;
int cor = q.front().corner;
q.pop();
// 직선 도로 하나를 만들 때는 100원이 소요되며, 코너를 하나 만들 때는 500원이
if(r == board.size()-1 && c == board.size()-1)
{
if(answer > cost[board.size()-1][board.size()-1])
answer = cost[board.size()-1][board.size()-1];
}
for(int i = 0; i < 4; i++)
{
if(is_reverse(d, i)) continue;
int nr = r + dr[i];
int nc = c + dc[i];
if(nr < 0 || nr > board.size()-1 || nc < 0 || nc > board.size()-1 || board[nr][nc] == 1) continue;
int corner = cor;
if(d != i) corner++;
int money = corner*500 + (l+1)*100;
if(nr == board.size()-1 && nc == board.size()-1)
{
cout << "dd";
}
if(cost[nr][nc] >= money)
{
cost[nr][nc] = money;
q.push(ground(nr,nc,i,l+1,corner));
}
}
}
answer = cost[board.size()-1][board.size()-1];
return answer;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
//[0, 0, 1, 0], [0, 0, 0, 0], [0, 1, 0, 1], [1, 0, 0, 0]
solution({{0, 0, 0, 0, 0, 0, 0, 1}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 1}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 1, 0, 0, 0, 1, 0, 0}, {1, 0, 0, 0, 0, 0, 0, 0}});
return 0;
}
|
#include <iostream>
#include <string>
#include "Encryptor.h"
using namespace std;
string min (string ms){
for (int i = 0; i <ms.length();i++){
ms[i]=tolower(ms[i]);
}
return ms;
};
int main() {
string ms;
int key;
cout<<"Ingrese una oracion"<<endl;
getline(cin, ms);
ms=min(ms);
cout<<"Ingrese la clave"<<endl;
cin>>key;
encryptor user(key);
ms=user.encrypted(ms);
cout<<"Mensaje encriptado"<<endl;
cout<<ms<<endl;
ms=user.decrypted(ms);
cout<<"Mensaje desencriptado"<<endl;
cout<<ms<<endl;
return 0;
}
|
#pragma once
#include <iostream>
#include<string>
void hello(std::ostream& out, const std::string& helloee, const int times);
|
#include <cstdio>
#include <cstring>
int month[13][2] = {
{0, 0},
{31, 31},
{28, 29},
{31, 31},
{30, 30},
{31, 31},
{30, 30},
{31, 31},
{31, 31},
{30, 30},
{31, 31},
{30, 30},
{31, 31}};
bool isLeap(int y)
{
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
char mdict[12 + 1][16] = {" ", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
char ddict[7][16] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday"};
int cal(int dsmall, int msmall, int ysmall, int dbig, int mbig, int ybig)
{
int ans = 0;
while (ysmall < ybig || msmall < mbig || dsmall < dbig)
{
dsmall++;
if (dsmall == month[msmall][isLeap(ysmall)] + 1)
{
dsmall = 1;
msmall++;
}
if (msmall == 12 + 1)
{
msmall = 1;
ysmall++;
}
ans++;
}
return ans;
}
int main()
{
int d;
char cm[16];
int m;
int y;
while (scanf("%d %s %d", &d, cm, &y) != EOF)
{
for (int i = 1; i <= 12; i++)
{
if (strcmp(cm, mdict[i]) == 0)
m = i;
}
int ans;
// 注意这里日期前后的判断,不是三个||
if (y * 10000 + m * 100 + d < (2019 * 10000 + 9 * 100 + 23))
{
ans = cal(d, m, y, 23, 9, 2019);
// printf("%d\n", ans);
if (ans % 7)
{
printf("%s\n", ddict[7 - ans % 7]);
}
else
{
printf("%s\n", ddict[0]);
}
}
else
{
ans = cal(23, 9, 2019, d, m, y);
// printf("%d\n", ans);
printf("%s\n", ddict[ans % 7]);
}
}
}
|
#ifndef LINEAR_PROBE
#define LINEAR_PROBE
#include<iostream>
using namespace std;
template<typename K, typename V, typename T>
class LinearProbe : public HashTable<K, V, T> {
private:
HashEntry<K, V> **entry;
public:
LinearProbe(K key):HashTable(key)
{
this->entry = new HashEntry*[this->size];
for(int i = 0; i < size; i++)
this->entry[i] = NULL;
}
int hashFunc(K key)
{
return key % size;
}
void insert(K key, V value)
{
HashEntry<K, V> *temp = new HashEntry<K, V>(key, value);
int index = HashFunc(key);
while(entry[index]!= NULL && entry[index]->key!=key)
{
index = this->HashFunc(index+1);
index %= size;
}
entry[index] = temp;
}
V search(K key)
{
int index = this->HashFunc(key);
int h = 1;
while(entry[index]!= NULL)
{
if(h++ > size)
return NULL;
if(entry[index]->key == key)
return entry[index];
index ++;
index %= size;
}
return NULL;
}
void remove(K key)
{
int index = this->HashFunc(key);
while( this->entry[index] != NULL)
{
if(this->entry[index]->key == key)
break;
index = this->HashFunc(index+1);
}
if (this->entry[index] == NULL)
{
cout<<"No Element found at key "<<index<<endl;
return;
}
else
{
delete this->entry[index];
}
cout<<"Element Deleted";
}
virtual LinearProbe<K, V, T> *clone()
{
return new LinearProbe(*this);
}
};
#endif
|
#include <bits/stdc++.h>
using namespace std;
bool isPal(long long int);
int main()
{
freopen("in", "r", stdin);
freopen("out", "w", stdout);
vector<long long int> pre;
for(long long int i=1; i<=10000000; i++)
{
if(isPal(i) && isPal(i*i)) pre.push_back(i);
}
int T;
cin>>T;
for(int tt=1; tt<=T; tt++)
{
cout<<"Case #"<<tt<<": ";
long long int a, b;
cin>>a>>b;
int ans = 0;
for(vector<long long int>::iterator it=pre.begin(); it!=pre.end(); it++)
{
long long int v = *it;
v *= v;
if(v>=a && v<=b) ans++;
}
cout<<ans<<endl;
}
}
bool isPal(long long int n)
{
string a = "", b;
while(n!=0)
{
a += n%10+'0';
n /= 10;
}
b = a;
reverse(b.begin(), b.end());
if(a==b) return 1;
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve(){
ll n;
cin>>n;
vector<ll>a(n);
for(int i=0;i<n;i++){
cin>>a[i];
}
ll ans=0;
for(ll i=1;i<n;i++)
ans=max(ans,a[i]*a[i-1]);
for(ll i=0;i<n-1;i++)
ans=max(ans,a[i]*a[i+1]);
cout<<ans<<"\n";
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("op.txt","w",stdout);
#endif
int t=1;
cin>>t;
while(t--){
solve();
}
}
|
/*
Copyright (c) 2014 NicoHood
See the readme for credit to other people.
HoodLoader2 NoUSB Blink example
This sketch demonstrates how to use HoodLoader2 without USB Core.
This might be useful to keep ram/flash usage at a very low level.
Select Tools->USB Core->No USB functions to get rid of the USB Core.
Blinks Leds and shows what workaround is needed to get the timing correct.
You can still use the normal digitalWrite(LED_BUILTIN_TX, LOW); for updating Leds.
Keep in mind that the logic is inverted then! LOW=HIGH and vice versa.
*/
#ifndef USBCON
// workaround for undefined USBCON has to be placed in every sketch
// otherwise the timings wont work correctly
ISR(USB_GEN_vect)
{
UDINT = 0;
}
#endif
void setup() {
TX_RX_LED_INIT;
}
void loop() {
TXLED0;
delay(100);
TXLED1;
delay(100);
RXLED0;
delay(100);
RXLED1;
delay(100);
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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 University of Oxford 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.
*/
#ifndef SIMPLEBATHPROBLEMSETUP_HPP_
#define SIMPLEBATHPROBLEMSETUP_HPP_
/**
* @file
*
* Some helper classes and functions for setting up a simple bath problem for testing.
*/
#include "AbstractCardiacCellFactory.hpp"
#include "SimpleStimulus.hpp"
#include "LuoRudy1991.hpp"
#include "HeartRegionCodes.hpp"
/**
* A simple cell factory for bath problems, applying a SimpleStimulus for
* 0.5ms at a single point.
*/
template<unsigned DIM, class CELLTYPE=CellLuoRudy1991FromCellML>
class BathCellFactory : public AbstractCardiacCellFactory<DIM>
{
private:
/** The stimulus to apply */
boost::shared_ptr<SimpleStimulus> mpStimulus;
/** and where to apply it */
c_vector<double,DIM> mStimulatedPoint;
public:
/**
* @return a newly created cell factory.
* @param stimulusMagnitude
* @param stimulatedPoint spatial co-ordinates of where to stimulate.
* Must correspond to a node location.
*/
BathCellFactory(double stimulusMagnitude, c_vector<double,DIM> stimulatedPoint)
: AbstractCardiacCellFactory<DIM>(),
mpStimulus(new SimpleStimulus(stimulusMagnitude, 0.5)),
mStimulatedPoint(stimulatedPoint)
{
}
/**
* @return a newly created new cell.
* @param pNode pointer to Node object for cell.
*/
AbstractCardiacCellInterface* CreateCardiacCellForTissueNode(Node<DIM>* pNode)
{
// paranoia - check this is really a tissue node
assert(HeartRegionCode::IsRegionTissue( pNode->GetRegion() ));
// stimulate centre node normally..
bool is_centre;
if (DIM==1)
{
is_centre = (fabs(pNode->GetPoint()[0]-mStimulatedPoint(0)) < 1e-6);
}
else if (DIM==2)
{
is_centre = ( (fabs(pNode->GetPoint()[0]-mStimulatedPoint(0)) < 1e-6)
&& (fabs(pNode->GetPoint()[1]-mStimulatedPoint(1)) < 1e-6) );
}
else
{
is_centre = ( (fabs(pNode->GetPoint()[0]-mStimulatedPoint(0)) < 1e-6)
&& (fabs(pNode->GetPoint()[1]-mStimulatedPoint(1)) < 1e-6)
&& (fabs(pNode->GetPoint()[2]-mStimulatedPoint(2)) < 1e-6) );
}
if (is_centre)
{
return new CELLTYPE(this->mpSolver, mpStimulus);
}
else
{
return new CELLTYPE(this->mpSolver, this->mpZeroStimulus);
}
}
};
/**
* Set everything outside a central circle in the given 2d mesh to be bath.
*
* @param pMesh the mesh
* @param centreX X co-ord of tissue centre
* @param centreY Y co-ord of tissue centre
* @param radius radius of tissue
*/
template<class MeshType>
void SetCircularTissueIn2dMesh(MeshType* pMesh,
double centreX, double centreY, double radius)
{
for (typename MeshType::ElementIterator it = pMesh->GetElementIteratorBegin();
it != pMesh->GetElementIteratorEnd();
++it)
{
double x = it->CalculateCentroid()[0];
double y = it->CalculateCentroid()[1];
if ((x-centreX)*(x-centreX) + (y-centreY)*(y-centreY) > radius*radius)
{
it->SetAttribute(HeartRegionCode::GetValidBathId());
}
}
pMesh->SetMeshHasChangedSinceLoading();
}
/**
* Load a 2d mesh, and set everything outside a central circle to be bath.
*
* @param rMeshPath relative path to the mesh
* @param centreX X co-ord of tissue centre
* @param centreY Y co-ord of tissue centre
* @param radius radius of tissue
* @return the new mesh
*/
template<class MeshType>
MeshType* Load2dMeshAndSetCircularTissue(const std::string& rMeshPath,
double centreX, double centreY, double radius)
{
TrianglesMeshReader<2,2> reader(rMeshPath);
MeshType* p_mesh = new MeshType;
p_mesh->ConstructFromMeshReader(reader);
SetCircularTissueIn2dMesh(p_mesh, centreX, centreY, radius);
return p_mesh;
}
/**
* Specialization for a parallel mesh.
*
* @param rMeshPath relative path to the mesh
* @param centreX X co-ord of tissue centre
* @param centreY Y co-ord of tissue centre
* @param radius radius of tissue
* @return the new mesh
*/
template<>
DistributedTetrahedralMesh<2,2>* Load2dMeshAndSetCircularTissue(const std::string& rMeshPath,
double centreX, double centreY, double radius)
{
TrianglesMeshReader<2,2> reader(rMeshPath);
// Force dumb partitioning so migration tests pass!
DistributedTetrahedralMesh<2,2>* p_mesh = new DistributedTetrahedralMesh<2,2>(DistributedTetrahedralMeshPartitionType::DUMB);
p_mesh->ConstructFromMeshReader(reader);
SetCircularTissueIn2dMesh(p_mesh, centreX, centreY, radius);
return p_mesh;
}
#endif /*SIMPLEBATHPROBLEMSETUP_HPP_*/
|
#include "UpAndOutEurCall.h"
#include <cmath>
#include <vector>
using namespace std;
UpAndOutEurCall::UpAndOutEurCall(double B, double S0, double K, double r, double sigma, double T)
{
m_S0 = S0;
m_K = K;
m_r = r;
m_sigma = sigma;
m_T = T;
m_B = B;
}
double N(double x)
{
double gamma = 0.2316419; double a1 = 0.319381530;
double a2 = -0.356563782; double a3 = 1.781477937;
double a4 = -1.821255978; double a5 = 1.330274429;
double pi = 4.0*atan(1.0); double k = 1.0 / (1.0 + gamma*x);
if (x >= 0.0)
{
return 1.0 - ((((a5*k + a4)*k + a3)*k + a2)*k + a1)
*k*exp(-x*x / 2.0) / sqrt(2.0*pi);
}
else return 1.0 - N(-x);
}
double D(double x, double r, double sigma, double Time)
{
return (log(x) + (r + 0.5*sigma*sigma)*Time) / (sigma*sqrt(Time));
}
double UpAndOutEurCall::PriceByBSFormula()
{
double d1 = D(m_S0 / m_K, m_r, m_sigma, m_T);
double d2 = d1 - m_sigma*sqrt(m_T);
double d3 = D(m_S0 / m_B, m_r, m_sigma, m_T);
double d4 = d3 - m_sigma*sqrt(m_T);
double d5 = D(m_S0 / m_B, -m_r, m_sigma, m_T);
double d6 = d5 - m_sigma*sqrt(m_T);
double d7 = D(m_S0*m_K / (m_B*m_B), -m_r, m_sigma, m_T);
double d8 = d7 - m_sigma*sqrt(m_T);
double IndexA = 2 * m_r / (m_sigma*m_sigma);
return m_S0*(N(d1) - N(d3) - (N(d6) - N(d8))*pow(m_B / m_S0, 1 + IndexA)) -
m_K*exp(-m_r*m_T)*(N(d2) - N(d4) - (N(d5) - N(d7))*pow(m_B / m_S0, -1 + IndexA));
}
double UpAndOutEurCall::PriceByCRR(BinModel Model)
{
double q = Model.RiskNeutralProb();
vector<double> Price;
for (int i = 0; i <= m_N; i++)
{
Price.push_back(PayOff(Model.S(m_N, i)));
}
for (int n = m_N - 1; n >= 0; n--)
{
for (int i = 0; i <= n; i++)
{
Price[i] = (q*Price[i + 1] + (1 - q)*Price[i]) / (1 + Model.GetR());
if (Model.S(n, i) >= m_B)
{
Price[i] = 0;
}
}
}
return Price[0];
}
double UpAndOutEurCall::PayOff(double z)
{
if (z > m_K && z < m_B) return z - m_K;
return 0.0;
}
BinModel::BinModel(double S0, double U, double D, double R)
{
mB_S0 = S0;
m_U = U;
m_D = D;
m_R = R;
}
double BinModel::RiskNeutralProb()
{
return (m_R - m_D) / (m_U - m_D);
}
double BinModel::S(int n, int i)
{
return mB_S0*pow(1 + m_U, i)*pow(1 + m_D, n - i);
}
double BinModel::GetR()
{
return m_R;
}
|
#include <benchmark/benchmark.h>
#include "PerformanceTestsUtil.hpp"
#include <deus/unicode_view_impl/ASCIIImpl.hpp>
//------------------------------------------------------------------------------
// SHORT
//------------------------------------------------------------------------------
//------------------------------------NAIVE-------------------------------------
static void BM_ascii_compute_byte_length_short_naive(benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kShort
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_naive(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_short_naive);
//------------------------------------STRLEN------------------------------------
static void BM_ascii_compute_byte_length_short_strlen(benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kShort
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_strlen(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_short_strlen);
//----------------------------------STD STRING----------------------------------
static void BM_ascii_compute_byte_length_short_std_string(
benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kShort
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_std_string(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_short_std_string);
//--------------------------------WORD BATCHING---------------------------------
static void BM_ascii_compute_byte_length_short_word_batching(
benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kShort
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_word_batching(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_short_word_batching);
//------------------------------------------------------------------------------
// MEDIUM
//------------------------------------------------------------------------------
//------------------------------------NAIVE-------------------------------------
static void BM_ascii_compute_byte_length_medium_naive(benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kMedium
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_naive(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_medium_naive);
//------------------------------------STRLEN------------------------------------
static void BM_ascii_compute_byte_length_medium_strlen(benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kMedium
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_strlen(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_medium_strlen);
//----------------------------------STD STRING----------------------------------
static void BM_ascii_compute_byte_length_medium_std_string(
benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kMedium
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_std_string(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_medium_std_string);
//--------------------------------WORD BATCHING---------------------------------
static void BM_ascii_compute_byte_length_medium_word_batching(
benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kMedium
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_word_batching(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_medium_word_batching);
//------------------------------------------------------------------------------
// LONG
//------------------------------------------------------------------------------
//------------------------------------NAIVE-------------------------------------
static void BM_ascii_compute_byte_length_long_naive(benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kLong
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_naive(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_long_naive);
//------------------------------------STRLEN------------------------------------
static void BM_ascii_compute_byte_length_long_strlen(benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kLong
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_strlen(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_long_strlen);
//----------------------------------STD STRING----------------------------------
static void BM_ascii_compute_byte_length_long_std_string(
benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kLong
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_std_string(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_long_std_string);
//--------------------------------WORD BATCHING---------------------------------
static void BM_ascii_compute_byte_length_long_word_batching(
benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kLong
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_word_batching(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_long_word_batching);
//------------------------------------------------------------------------------
// EXTRA LONG
//------------------------------------------------------------------------------
//------------------------------------NAIVE-------------------------------------
static void BM_ascii_compute_byte_length_xlong_naive(benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kExtraLong
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_naive(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_xlong_naive);
//------------------------------------STRLEN------------------------------------
static void BM_ascii_compute_byte_length_xlong_strlen(benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kExtraLong
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_strlen(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_xlong_strlen);
//----------------------------------STD STRING----------------------------------
static void BM_ascii_compute_byte_length_xlong_std_string(
benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kExtraLong
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_std_string(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_xlong_std_string);
//--------------------------------WORD BATCHING---------------------------------
static void BM_ascii_compute_byte_length_xlong_word_batching(
benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kExtraLong
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_word_batching(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_xlong_word_batching);
//------------------------------------------------------------------------------
// MIXED
//------------------------------------------------------------------------------
//------------------------------------NAIVE-------------------------------------
static void BM_ascii_compute_byte_length_mixed_naive(benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kMixed
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_naive(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_mixed_naive);
//------------------------------------STRLEN------------------------------------
static void BM_ascii_compute_byte_length_mixed_strlen(benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kMixed
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_strlen(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_mixed_strlen);
//----------------------------------STD STRING----------------------------------
static void BM_ascii_compute_byte_length_mixed_std_string(
benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kMixed
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_std_string(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_mixed_std_string);
//--------------------------------WORD BATCHING---------------------------------
static void BM_ascii_compute_byte_length_mixed_word_batching(
benchmark::State& state)
{
deus_perf_util::gen_rand_dyn_strs(
deus::Encoding::kASCII,
deus_perf_util::StringSize::kMixed
);
for(auto _ : state)
{
// generate
std::size_t dummy = 0;
const char* s = deus_perf_util::get_next_rand_dyn_str(dummy);
// call
std::size_t byte_length = 0;
deus::ascii_inl::compute_byte_length_word_batching(s, byte_length);
}
}
BENCHMARK(BM_ascii_compute_byte_length_mixed_word_batching);
|
#if (defined HAS_VTK && defined HAS_CONTRIB)
#include <stdio.h>
#include <string.h>
#include <irtkImage.h>
#include <irtkEigenAnalysis.h>
#include <irtkTransformation.h>
// Minimum norm of an eigenvector
#define MIN_NORM 0.01
// vtk includes
#include <vtkPoints.h>
#include <vtkPointData.h>
#include <vtkStructuredGrid.h>
#include <vtkPolyData.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkStructuredGridReader.h>
#include <vtkStructuredGridWriter.h>
#include <vtkUnstructuredGrid.h>
#include <vtkUnstructuredGridReader.h>
#include <vtkUnstructuredGridWriter.h>
vtkPointSet *data;
vtkPoints *points;
vtkDataArray *vectors;
char* componentsFile = NULL;
char* evecsFile = NULL;
char* evalsFile = NULL;
char* meanFile = NULL;
vtkPointSet *read(char *file)
{
int i;
char buffer[256];
vtkPointSet *pset;
ifstream is(file);
if (!is){
cerr << "Can't open file " << file << endl;
exit(1);
}
for (i = 0; i < 3; i++){
is.getline(buffer, 256);
}
is >> buffer >> buffer;
if (strcmp(buffer, "POLYDATA") == 0) {
// Read vtkPolyData object
vtkPolyDataReader *reader = vtkPolyDataReader::New();
reader->SetFileName(file);
reader->Update();
pset = reader->GetOutput();
pset->Register(pset);
reader->Delete();
} else {
if (strcmp(buffer, "UNSTRUCTURED_GRID") == 0) {
// Read vtkUnstructuredGrid object
vtkUnstructuredGridReader *reader = vtkUnstructuredGridReader::New();
reader->SetFileName(file);
reader->Update();
pset = reader->GetOutput();
pset->Register(pset);
reader->Delete();
} else {
if (strcmp(buffer, "STRUCTURED_GRID") == 0) {
// Read vtkStructuredGrid object
vtkStructuredGridReader *reader = vtkStructuredGridReader::New();
reader->SetFileName(file);
reader->Update();
pset = reader->GetOutput();
pset->Register(pset);
reader->Delete();
} else {
cerr << "Unknown VTK data type" << endl;
exit(1);
}
}
}
return pset;
}
void write(char *file, vtkPointSet *pset)
{
if (pset->IsA("vtkStructuredGrid")){
vtkStructuredGridWriter *writer = vtkStructuredGridWriter::New();
writer->SetInputData((vtkStructuredGrid *)pset);
writer->SetFileName(file);
writer->SetFileTypeToBinary();
writer->Update();
} else {
if (pset->IsA("vtkUnstructuredGrid")){
vtkUnstructuredGridWriter *writer = vtkUnstructuredGridWriter::New();
writer->SetInputData((vtkUnstructuredGrid *)pset);
writer->SetFileName(file);
writer->SetFileTypeToBinary();
writer->Update();
} else {
if (pset->IsA("vtkPolyData")){
vtkPolyDataWriter *writer = vtkPolyDataWriter::New();
writer->SetInputData((vtkPolyData *)pset);
writer->SetFileName(file);
writer->SetFileTypeToBinary();
writer->Update();
} else {
cerr << "Unknown VTK data type" << endl;
exit(1);
}
}
}
}
int main(int argc, char **argv)
{
int i, j, k, m, iNoOfLandmarks, iNoOfDatasets;
irtkMatrix T, Eigenvector;
irtkVector Da, Db, MeanShape, Eigenvalues;
double p[3], v[3];
int maxModes = 10;
if ((argc < 5)){
cout << "usage: pcanalysis landmarks1 ... landmarks_N landmarks_mean "
<< "eigen_values eigen_vectors maxModes componentMatrix \n";
return 1;
}
componentsFile = argv[argc-1];
maxModes = atoi(argv[argc-2]);
evecsFile = argv[argc-3];
evalsFile = argv[argc-4];
meanFile = argv[argc-5];
cout << "Using " << maxModes << " modes\n";
iNoOfDatasets = argc-6;
iNoOfLandmarks = 0;
cerr << " There are " << iNoOfDatasets << " data sets for training"
<< endl;
// Read all landmarks in matrix M
for (i = 0; i < iNoOfDatasets; i++){
cerr << " Including landmarks in " << argv[i+1] << endl;
data = read(argv[i+1]);
points = data->GetPoints();
vectors = data->GetPointData()->GetVectors();
if (i == 0){
iNoOfLandmarks = points->GetNumberOfPoints();
// M.Initialize(3*iNoOfLandmarks,iNoOfDatasets);
Da.Initialize(3*iNoOfLandmarks);
Db.Initialize(3*iNoOfLandmarks);
MeanShape.Initialize(3*iNoOfLandmarks);
for (j = 0; j < 3*iNoOfLandmarks; j++){
MeanShape(j) = 0.0;
}
cerr << " There are " << iNoOfDatasets
<< " datasets with "
<< points->GetNumberOfPoints()
<< " landmarks." << endl;
} else {
if ((points->GetNumberOfPoints()) != iNoOfLandmarks){
cerr << "Datasets must contain the same number of landmarks" << endl;
exit(1);
}
}
for (j = 0; j < iNoOfLandmarks; j++){
if (vectors == NULL){
points->GetPoint(j,p);
MeanShape(3*j) += p[0];
MeanShape(3*j+1) += p[1];
MeanShape(3*j+2) += p[2];
} else {
vectors->GetTuple(j,v);
MeanShape(3*j) += v[0];
MeanShape(3*j+1) += v[1];
MeanShape(3*j+2) += v[2];
}
}
}
MeanShape = MeanShape*(1.0/iNoOfDatasets);
cout << "Calculated mean." << endl;
// Form matrix T = (1/iNoOfDatasets) M^T * M which has
// dimensions iNoOfDatasets x iNoOfDatasets after subtracting
// the mean from each dataset.
T.Initialize(iNoOfDatasets,iNoOfDatasets);
for (i = 0; i < iNoOfDatasets; ++i){
data = read(argv[i+1]);
points = data->GetPoints();
vectors = data->GetPointData()->GetVectors();
for (k = 0; k < iNoOfLandmarks; ++k){
if (vectors == NULL){
points->GetPoint(k,p);
Da(3*k) = p[0] - MeanShape(3*k);
Da(3*k+1) = p[1] - MeanShape(3*k+1);
Da(3*k+2) = p[2] - MeanShape(3*k+2);
} else {
vectors->GetTuple(k,v);
Da(3*k) = v[0] - MeanShape(3*k);
Da(3*k+1) = v[1] - MeanShape(3*k+1);
Da(3*k+2) = v[2] - MeanShape(3*k+2);
}
}
data->Delete();
for (j = i; j < iNoOfDatasets; ++j){
data = read(argv[j + 1]);
points = data->GetPoints();
vectors = data->GetPointData()->GetVectors();
for (k = 0; k < iNoOfLandmarks; ++k){
if (vectors == NULL){
points->GetPoint(k,p);
Db(3*k) = p[0] - MeanShape(3*k);
Db(3*k+1) = p[1] - MeanShape(3*k+1);
Db(3*k+2) = p[2] - MeanShape(3*k+2);
} else {
vectors->GetTuple(k,v);
Db(3*k) = v[0] - MeanShape(3*k);
Db(3*k+1) = v[1] - MeanShape(3*k+1);
Db(3*k+2) = v[2] - MeanShape(3*k+2);
}
}
data->Delete();
// Covariance matrix entry
T(i, j) = 0.0;
for (k = 0; k < 3 * iNoOfLandmarks; k++){
T(i, j) += Da(k) * Db(k);
}
// Symmetric covariance matrix
T(j, i) = T(i, j);
}
}
T /= iNoOfDatasets;
// Compute the eigen decomposition
irtkEigenAnalysis ea(iNoOfDatasets);
for (i = 0; i < iNoOfDatasets; i++){
for(int j=0; j < iNoOfDatasets; j++){
ea.Matrix(i,j) = T(i,j);
}
}
ea.DecrSortEigenStuff();
// Convert the eigenvectors of T to true eigenvectors of the
// covariance matrix C = M*M^T.
Eigenvector.Initialize(3*iNoOfLandmarks, maxModes);
Eigenvector *= 0.0;
for (k = 0; k < iNoOfDatasets; k++){
data = read(argv[k+1]);
points = data->GetPoints();
vectors = data->GetPointData()->GetVectors();
for (m = 0; m < iNoOfLandmarks; ++m){
if (vectors == NULL){
points->GetPoint(m,p);
Da(3*m) = p[0] - MeanShape(3*m);
Da(3*m+1) = p[1] - MeanShape(3*m+1);
Da(3*m+2) = p[2] - MeanShape(3*m+2);
} else {
vectors->GetTuple(m,v);
Da(3*m) = v[0] - MeanShape(3*m);
Da(3*m+1) = v[1] - MeanShape(3*m+1);
Da(3*m+2) = v[2] - MeanShape(3*m+2);
}
}
data->Delete();
for (i = 0; i < 3*iNoOfLandmarks; ++i){
for (j = 0; j < maxModes; ++j){
Eigenvector(i, j) += Da(i) * ea.Eigenvector(k, j);
}
}
}
Eigenvalues.Initialize(iNoOfDatasets);
for (i = 0; i < iNoOfDatasets ; i++){
Eigenvalues(i) = ea.Eigenvalue(i);
}
float fTotalVar = 0;
float fCummulated = 0;
for (i = 0; i < iNoOfDatasets; i++){
fTotalVar += ea.Eigenvalue(i);
}
for (i = 0; i < maxModes; i++){
cout<< "Mode:" << i << " Eigenvalue:"<<ea.Eigenvalue(i)<<endl;
fCummulated += 100 * ea.Eigenvalue(i) / fTotalVar;
cout << " Mode [" << i << "] explains "
<< 100 * ea.Eigenvalue(i) / fTotalVar
<< " % ("
<< fCummulated
<< " %) of shape variance." << endl;
}
// Normalize eigenvectors
for (i = 0; i < maxModes ; i++){
float fNorm = 0.0;
for (j = 0; j < 3*iNoOfLandmarks; j++){
fNorm += Eigenvector(j,i) * Eigenvector(j,i);
}
fNorm = sqrt(fNorm);
if (100 * ea.Eigenvalue(i) / fTotalVar > MIN_NORM){
for (j = 0; j < 3*iNoOfLandmarks; j++){
Eigenvector(j,i) /= fNorm;
}
} else {
for (j = 0; j < 3*iNoOfLandmarks; j++){
Eigenvector(j,i) = 0;
}
Eigenvalues(i) = 0;
}
}
cout << "Eigenvectors normalised" << endl;
// Find components matrix.
irtkMatrix comps;
comps.Initialize(maxModes, iNoOfDatasets);
for (k = 0; k < iNoOfDatasets; k++){
data = read(argv[k+1]);
points = data->GetPoints();
vectors = data->GetPointData()->GetVectors();
for (m = 0; m < iNoOfLandmarks; ++m){
if (vectors == NULL){
points->GetPoint(m,p);
Da(3*m) = p[0] - MeanShape(3*m);
Da(3*m+1) = p[1] - MeanShape(3*m+1);
Da(3*m+2) = p[2] - MeanShape(3*m+2);
} else {
vectors->GetTuple(m,v);
Da(3*m) = v[0] - MeanShape(3*m);
Da(3*m+1) = v[1] - MeanShape(3*m+1);
Da(3*m+2) = v[2] - MeanShape(3*m+2);
}
}
data->Delete();
for (j = 0; j < maxModes; ++j){
comps(j, k) = 0;
for (i = 0; i < 3*iNoOfLandmarks; ++i){
comps(j, k) += Eigenvector(i,j) * Da(i);
}
}
}
cerr << " Writing eigenvalues to " << evalsFile << endl;
Eigenvalues.Write(evalsFile);
cerr << " Writing eigenshapes to " << evecsFile << endl;
Eigenvector.Write(evecsFile);
cout << "Writing components to " << componentsFile << endl;
comps.Write(componentsFile);
// Read the first dataset for its structure.
data = read(argv[1]);
points = data->GetPoints();
vectors = data->GetPointData()->GetVectors();
// Convert mean back to VTK
for (j = 0; j < iNoOfLandmarks; j++){
double p[3], v[3];
if (vectors == NULL){
p[0] = MeanShape(3*j);
p[1] = MeanShape(3*j+1);
p[2] = MeanShape(3*j+2);
points->SetPoint(j,p);
} else {
v[0] = MeanShape(3*j);
v[1] = MeanShape(3*j+1);
v[2] = MeanShape(3*j+2);
vectors->SetTuple(j,v);
}
}
data->SetPoints(points);
cerr << " Writing mean shape to " << meanFile << endl;
write(meanFile, data);
}
#else
#include <irtkImage.h>
int main( int argc, char *argv[] ){
cerr << argv[0] << " needs to be compiled with the contrib and VTK library"
<< endl;
}
#endif
|
/*********************************************************************
Matt Marchant 2014 - 2016
http://trederia.blogspot.com
xygine - Zlib license.
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.
*********************************************************************/
//allows transforming a view of the scene based on the parent entity
#ifndef XY_CAMERA_HPP_
#define XY_CAMERA_HPP_
#include <xygine/components/Component.hpp>
#include <SFML/Graphics/Color.hpp>
namespace xy
{
/*!
\brief Camera Component
Cameras are used to define the view of the scene to be rendered
on screen. The scene class contains a default camera, which can be
overriden by attaching a camera component to an entity, and setting
the scene's active camera to the component (see Scene class). Cameras
attached to entities take on the entities transform, both translation
and rotation. This allows a camera to easily follow a player or other
in game entity.
*/
class XY_EXPORT_API Camera final : public Component
{
public:
using Ptr = std::unique_ptr<Camera>;
Camera(MessageBus&, const sf::View& initialView);
~Camera() = default;
Camera(const Camera&) = delete;
const Camera& operator = (const Camera&) = delete;
Component::Type type() const override { return Component::Type::Script; }
void entityUpdate(Entity&, float) override;
enum class TransformLock
{
AxisX = 0x1,
AxisY = 0x2,
Rotation = 0x4
};
/*!
\brief Locks or unlocks a degree of camera movement
It may be desirable to lock the motion of the camera,
either horizontally, vertically or rotation.
\param TransformLock Axis or rotation to lock or unlock
\param bool whether to lock or unlock the given degree of motion
*/
void lockTransform(TransformLock, bool = true);
/*!
\brief Lock the camera within specific bounds
The cameras motion can be bound within a given area
so that it can be prevented from moving out the bounds
of a game map for example
\param bounds An sf::FloatRect describing the area in world
coordinates within which to bind the camera.
\param bool lock or unlock the camera to the specified bounds
*/
void lockBounds(const sf::FloatRect& bounds, bool = true);
/*!
\brief Set the zoom level of the camera
Increasing the zoom value of the camera increases the zoom
(and therefore reduces the visible area) of the rendered scene
\param float Zoom amount. Must be greter than zero, but can be
values less than one, which zoom out. Note zooming out doesn't
respects any locked bounds, which always assumes a zoom value
of one (the defalt value).
*/
void setZoom(float);
/*!
\brief Returns the current camera zoom amount
\see setZoom
*/
float getZoom() const;
/*!
\brief Set which part of the render target this camera covers
\param sf::FloatRect depecting the area of the screen to be
rendered. Note that these are normalised values (0-1) as a ratio
of the screen resolution
*/
void setViewport(const sf::FloatRect&);
/*!
\brief Returns the current view of the camera
Use this to set the view of any render target to which
you wish to render the scene as it appears to the camera
*/
sf::View getView() const;
/*!
\brief Sets the initial view of the camera
This includes setting the resolution in world units of the camera
as well as the viewport. This is normally set with the default view
of the current game state's context, as it is automatically set to
correctly letterbox the camera to match the current window resolution.
This is the view seen when the camera zoom is set to one.
\param sf::View to apply to the camera's initial state
*/
void setView(const sf::View&);
/*!
\brief Sets the colour with which to clear the scene buffer
This is the clear colour applied when using this camera to render
with a PostProcess effect. Useful for debugging.
\param sf::Color colour to use.
*/
void setClearColour(const sf::Color&);
/*!
\brief Gets the current clear colour for this camera
\see setClearColour
*/
const sf::Color& getClearColour() const;
private:
float m_zoom;
sf::Uint8 m_lockMask;
float m_rotation;
sf::View m_initialView;
sf::Vector2f m_position;
sf::FloatRect m_bounds;
bool m_lockToBounds;
sf::Color m_clearColour;
};
}
#endif //XY_CAMERA_HPP_
|
/*
* @lc app=leetcode.cn id=127 lang=cpp
*
* [127] 单词接龙
*/
// @lc code=start
class Solution {
public:
// int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
// unordered_set<string> s;
// for (auto i : wordList) s.insert(i);
// queue<pair<string, int>> q;
// // first 表示单词
// // second 表示走过的步数
// q.push(make_pair(beginWord, 1));
// string tmp;
// int step;
// while (!q.empty()) {
// if (q.front().first == endWord) {
// return q.front().second;
// }
// tmp = q.front().first;
// step = q.front().second;
// q.pop();
// char ch;
// for (int i = 0; i < tmp.length(); ++ i) {
// ch = tmp[i];
// for (char c = 'a'; c <= 'z'; ++ c) {
// if (ch == c) continue;
// tmp[i] = c;
// if (s.find(tmp) != s.end()) {
// q.push(make_pair(tmp, step + 1));
// s.erase(tmp);
// }
// tmp[i] = ch;
// }
// }
// }
// return 0;
// }
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> dict(wordList.begin(), wordList.end());
if (dict.find(endWord) == dict.end() ) return 0;
// 初始化起始和终点
unordered_set<string> beginSet, endSet, tmp, visited;
beginSet.insert(beginWord);
endSet.insert(endWord);
int len = 1;
while (!beginSet.empty() && !endSet.empty()){
if (beginSet.size() > endSet.size()){
tmp = beginSet;
beginSet = endSet;
endSet = tmp;
}
tmp.clear();
for ( string word : beginSet){
for (int i = 0; i < word.size(); i++){
char old = word[i];
for ( char c = 'a'; c <= 'z'; c++){
if ( old == c) continue;
word[i] = c;
if (endSet.find(word) != endSet.end()){
return len+1;
}
if (visited.find(word) == visited.end() && dict.find(word) != dict.end()){
tmp.insert(word);
visited.insert(word);
}
}
word[i] = old;
}
}
beginSet = tmp;
len++;
}
return 0;
}
};
// @lc code=end
|
#ifndef SIMULATIONMODEL_H
#define SIMULATIONMODEL_H
#include "ModelBase.h"
#include "CustomParameterModel.h"
#include "Common.h"
namespace FastCAEDesigner
{
class SimulationModel : public CustomParameterModel
{
Q_OBJECT
public:
SimulationModel(QString nameEng, QString nameChn, QString iconName, QObject *parent);
~SimulationModel();
};
}
#endif
|
#include <bits/stdc++.h>
#define ll long long
using namespace std;
typedef tuple<ll, ll, ll> tp;
typedef pair<ll, ll> pr;
const ll MOD = 1000000007;
const ll INF = 1e18;
template <typename T> void print(const T &t) {
std::copy(t.cbegin(), t.cend(),
std::ostream_iterator<typename T::value_type>(std::cout, " "));
cout << endl;
}
template <typename T> void print2d(const T &t) {
std::for_each(t.cbegin(), t.cend(), print<typename T::value_type>);
}
void setIO(string s) { // the argument is the filename without the extension
freopen((s + ".in").c_str(), "r", stdin);
freopen((s + ".out").c_str(), "w", stdout);
}
int main() {
cin.tie(0)->sync_with_stdio(0);
cin.exceptions(cin.failbit);
ll t; cin >> t;
string check = "0123456789ACDEFHJKLMNPRTVWX";
map<char, char> special = {
{'B', '8'},
{'G', 'C'},
{'I', '1'},
{'O', '0'},
{'Q', '0'},
{'S', '5'},
{'U', 'V'},
{'Y', 'V'},
{'Z', '2'},
};
for(ll i = 0; i < t; i++){
ll id; cin >> id;
string num; cin >> num;
ll temp = 2*(check.find(num[0])) + 4*(check.find(num[1])) + 5*(check.find(num[2])) + 7*(check.find(num[3])) + 8*(check.find(num[4])) + 10*(check.find(num[5])) + 11*(check.find(num[6])) + 13*(check.find(num[7]));
temp %= 27;
ll find = check.find(num[8]);
if(find == -1){
find = check.find(special[num[8]]);
}
//cout << find << " " << temp << endl;
if(find == temp){
ll res = 0;
for(ll j = 0; j < 8; j++){
ll curr = check.find(num[j]);
res += curr * pow(27, 7 - j);
}
cout << id << " " << res << endl;
} else{
cout << id << " " << "Invalid" << endl;
}
}
}
|
// This file has been generated by Py++.
#include "boost/python.hpp"
#include "generators/include/python_CEGUI.h"
#include "PropertySet.pypp.hpp"
namespace bp = boost::python;
void register_PropertySet_class(){
{ //::CEGUI::PropertySet
typedef bp::class_< CEGUI::PropertySet, bp::bases< CEGUI::PropertyReceiver > > PropertySet_exposer_t;
PropertySet_exposer_t PropertySet_exposer = PropertySet_exposer_t( "PropertySet", "*!\n\
\n\
Interface providing introspection capabilities\n\
\n\
CEGUI uses this interface for introspection and serialisation, especially in\n\
CEGUI.Window and classes that inherit it.\n\
\n\
If you are just a user of an existing PropertySet class there are just 2 methods\n\
that you should be aware of - PropertySet.setProperty and PropertySet.getProperty.\n\
Both methods are available in 2 variants - string fallback mode and templated\n\
native mode. It is recommended to use the native mode. Code example:\n\
\n\
.{.cpp}\n\
CEGUI.Window* wnd = ...;\n\
native mode property set\n\
wnd.setProperty<float>(Alpha, 0.5f); set Alpha to 50%\n\
string fallback mode\n\
wnd.setProperty(Alpha, 0.5); set Alpha to 50%\n\
\n\
native mode property get\n\
const float alpha = wnd.getProperty<float>(Alpha);\n\
string fallback mode\n\
const String alphaString = wnd.getProperty(Alpha);\n\
\n\n\
\n\
If you use native mode with the wrong type CEGUI will resort to string fallback\n\
and will try to convert the type to whatever you requested.\n\
\n\
.{.cpp}\n\
CEGUI.Window* wnd = ...;\n\
will set Alpha to 100% but is slower due to the casts\n\
wnd.setProperty<int>(Alpha, 1);\n\
retrieves Alpha as string, then proceeds to convert that to int\n\
beware of rounding errors!\n\
wnd.getProperty<int>(Alpha);\n\
\n\n\
\n\
We will always offer string fallback mode because it is necessary for serialisation\n\
and scripting. Scripting languages are often duck typed and cannot use C++\n\
templated code.\n\
\n\
The CEGUI.Property instances hold pointers to getter and setter of\n\
a given property. They are designed in such a way that multiple PropertySets\n"
"(multiple widgets) can share the Property instances to save memory. This means\n\
that PropertySets don't own the Properties themselves. The Property instances\n\
are usually static members of the PropertySet classes or static local\n\
variables in the scope of the constructor or a method called from there.\n\
\n\
It's unusual but multiple instances of the same class can have different\n\
Properties added to them.\n\
\n\
It is recommended to use the CEGUI_DEFINE_PROPERTY macro instead of using\n\
PropertySet.addProperty directly. This takes care of property initialisation\n\
as well as it's addition to the PropertySet instance.\n\
*\n\
", bp::init< >("*!\n\
\n\
Constructs a new PropertySet object\n\
*\n") );
bp::scope PropertySet_scope( PropertySet_exposer );
{ //::CEGUI::PropertySet::addProperty
typedef void ( ::CEGUI::PropertySet::*addProperty_function_type )( ::CEGUI::Property * ) ;
PropertySet_exposer.def(
"addProperty"
, addProperty_function_type( &::CEGUI::PropertySet::addProperty )
, ( bp::arg("property") )
, "*!\n\
\n\
Adds a new Property to the PropertySet\n\
\n\
@param property\n\
Pointer to the Property object to be added to the PropertySet.\n\
\n\
@exception NullObjectException Thrown if property is NULL.\n\
@exception AlreadyExistsException Thrown if a Property with the same name as property already\
exists in the PropertySet\n\
\n\
\note\n\
You most likely don't want to use this method unless you are implementing\n\
a custom Property class. Please see CEGUI_DEFINE_PROPERTY instead.\n\
*\n" );
}
{ //::CEGUI::PropertySet::clearProperties
typedef void ( ::CEGUI::PropertySet::*clearProperties_function_type )( ) ;
PropertySet_exposer.def(
"clearProperties"
, clearProperties_function_type( &::CEGUI::PropertySet::clearProperties )
, "*!\n\
\n\
Removes all Property objects from the PropertySet.\n\
*\n" );
}
{ //::CEGUI::PropertySet::getProperty
typedef ::CEGUI::String ( ::CEGUI::PropertySet::*getProperty_function_type )( ::CEGUI::String const & ) const;
PropertySet_exposer.def(
"getProperty"
, getProperty_function_type( &::CEGUI::PropertySet::getProperty )
, ( bp::arg("name") )
, "*!\n\
\n\
Gets the current value of the specified Property.\n\
\n\
@param name\n\
String containing the name of the Property who's value is to be returned.\n\
\n\
@return\n\
String object containing a textual representation of the requested Property.\n\
\n\
@exception UnknownObjectException Thrown if no Property named name is in the PropertySet.\n\
*\n" );
}
{ //::CEGUI::PropertySet::getPropertyDefault
typedef ::CEGUI::String ( ::CEGUI::PropertySet::*getPropertyDefault_function_type )( ::CEGUI::String const & ) const;
PropertySet_exposer.def(
"getPropertyDefault"
, getPropertyDefault_function_type( &::CEGUI::PropertySet::getPropertyDefault )
, ( bp::arg("name") )
, "*!\n\
\n\
Returns the default value of a Property as a String.\n\
\n\
@param name\n\
String containing the name of the Property who's default string is to be returned.\n\
\n\
@return\n\
String object containing a textual representation of the default value for this property.\n\
*\n" );
}
{ //::CEGUI::PropertySet::getPropertyHelp
typedef ::CEGUI::String const & ( ::CEGUI::PropertySet::*getPropertyHelp_function_type )( ::CEGUI::String const & ) const;
PropertySet_exposer.def(
"getPropertyHelp"
, getPropertyHelp_function_type( &::CEGUI::PropertySet::getPropertyHelp )
, ( bp::arg("name") )
, bp::return_value_policy< bp::copy_const_reference >()
, "*!\n\
\n\
Return the help text for the specified Property.\n\
\n\
@param name\n\
String holding the name of the Property who's help text is to be returned.\n\
\n\
@return\n\
String object containing the help text for the Property name.\n\
\n\
@exception UnknownObjectException Thrown if no Property named name is in the PropertySet.\n\
*\n" );
}
{ //::CEGUI::PropertySet::getPropertyInstance
typedef ::CEGUI::Property * ( ::CEGUI::PropertySet::*getPropertyInstance_function_type )( ::CEGUI::String const & ) const;
PropertySet_exposer.def(
"getPropertyInstance"
, getPropertyInstance_function_type( &::CEGUI::PropertySet::getPropertyInstance )
, ( bp::arg("name") )
, bp::return_value_policy< bp::reference_existing_object >()
, "*!\n\
\n\
Retrieves a property instance (that was previously added)\n\
\n\
@param name\n\
String containing the name of the Property to be retrieved. If Property name is not in the\
set, exception is thrown.\n\
\n\
@return\n\
Pointer to the property instance\n\
*\n" );
}
{ //::CEGUI::PropertySet::getPropertyIterator
typedef ::CEGUI::ConstMapIterator< std::map<CEGUI::String, CEGUI::Property*, CEGUI::StringFastLessCompare, std::allocator<std::pair<CEGUI::String const, CEGUI::Property*> > > > ( ::CEGUI::PropertySet::*getPropertyIterator_function_type )( ) const;
PropertySet_exposer.def(
"getPropertyIterator"
, getPropertyIterator_function_type( &::CEGUI::PropertySet::getPropertyIterator )
, "*!\n\
\n\
Return a PropertySet.PropertyIterator object to iterate over the available\n\
Properties.\n\
*\n" );
}
{ //::CEGUI::PropertySet::isPropertyDefault
typedef bool ( ::CEGUI::PropertySet::*isPropertyDefault_function_type )( ::CEGUI::String const & ) const;
PropertySet_exposer.def(
"isPropertyDefault"
, isPropertyDefault_function_type( &::CEGUI::PropertySet::isPropertyDefault )
, ( bp::arg("name") )
, "*!\n\
\n\
Returns whether a Property is at it's default value.\n\
\n\
@param name\n\
String containing the name of the Property who's default state is to be tested.\n\
\n\
@return\n\
- true if the property has it's default value.\n\
- false if the property has been modified from it's default value.\n\
*\n" );
}
{ //::CEGUI::PropertySet::isPropertyPresent
typedef bool ( ::CEGUI::PropertySet::*isPropertyPresent_function_type )( ::CEGUI::String const & ) const;
PropertySet_exposer.def(
"isPropertyPresent"
, isPropertyPresent_function_type( &::CEGUI::PropertySet::isPropertyPresent )
, ( bp::arg("name") )
, "*!\n\
\n\
Checks to see if a Property with the given name is in the PropertySet\n\
\n\
@param name\n\
String containing the name of the Property to check for.\n\
\n\
@return\n\
true if a Property named name is in the PropertySet. false if no Property named name is in\
the PropertySet.\n\
*\n" );
}
{ //::CEGUI::PropertySet::removeProperty
typedef void ( ::CEGUI::PropertySet::*removeProperty_function_type )( ::CEGUI::String const & ) ;
PropertySet_exposer.def(
"removeProperty"
, removeProperty_function_type( &::CEGUI::PropertySet::removeProperty )
, ( bp::arg("name") )
, "*!\n\
\n\
Removes a Property from the PropertySet.\n\
\n\
@param name\n\
String containing the name of the Property to be removed. If Property name is not in the\
set, nothing happens.\n\
*\n" );
}
{ //::CEGUI::PropertySet::setProperty
typedef void ( ::CEGUI::PropertySet::*setProperty_function_type )( ::CEGUI::String const &,::CEGUI::String const & ) ;
PropertySet_exposer.def(
"setProperty"
, setProperty_function_type( &::CEGUI::PropertySet::setProperty )
, ( bp::arg("name"), bp::arg("value") )
, "*!\n\
\n\
Sets the current value of a Property.\n\
\n\
@param name\n\
String containing the name of the Property who's value is to be set.\n\
\n\
@param value\n\
String containing a textual representation of the new value for the Property\n\
\n\
@exception UnknownObjectException Thrown if no Property named name is in the PropertySet.\n\
@exception InvalidRequestException Thrown when the Property was unable to interpret the content\
of value.\n\
*\n" );
}
}
}
|
/**
* Copyright (C) 2017 Alibaba Group Holding Limited. 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 <multimedia/component.h>
#include "multimedia/media_meta.h"
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <cstdlib>
#include <unistd.h>
#include <multimedia/mmmsgthread.h>
#include "multimedia/mm_debug.h"
#include "multimedia/media_buffer.h"
#include "multimedia/component_factory.h"
#include "multimedia/media_attr_str.h"
#include "multimedia/media_monitor.h"
#include "components/av_demuxer.h"
MM_LOG_DEFINE_MODULE_NAME("RTP_MUXER_TEST");
using namespace YUNOS_MM;
static bool releaseOutputBuffer(MediaBuffer* mediaBuffer)
{
uint8_t *buffer = NULL;
if (!(mediaBuffer->getBufferInfo((uintptr_t *)&buffer, NULL, NULL, 1))) {
WARNING("error in release mediabuffer");
return false;
}
MM_RELEASE_ARRAY(buffer);
return true;
}
/////////////////////FakeVideoDecode/////////////
class FakeVideoDecode : public FilterComponent
{
public:
class DecodeThreadV;
typedef MMSharedPtr <DecodeThreadV> DecodeThreadVSP;
class DecodeThreadV : public MMThread
{
public:
DecodeThreadV(FakeVideoDecode *decoder) : MMThread("FakeVideoDecodeThd")
{
mDecoder = decoder;
return ;
}
~DecodeThreadV() { return ; }
void signalExit() { return; }
void signalContinue() { return; }
protected:
virtual void main()
{
int32_t frameIdx = 0;
while(1) {
MediaBufferSP mediaInputBuffer;
{
if (mDecoder->mIsExit) {
INFO("now to exit\n");
break;
}
mDecoder->mReader->read(mediaInputBuffer);
}
if (mediaInputBuffer) {
uint8_t *buffer = NULL;
int decodedSize = 0;
int64_t pts = ((int64_t)frameIdx * 1000 *1000) / 23976, dts;
mediaInputBuffer->getBufferInfo((uintptr_t *)&buffer, NULL, NULL, 1);
decodedSize = mediaInputBuffer->size();
pts = mediaInputBuffer->pts();
dts = mediaInputBuffer->dts();
uint8_t * buffer2 = new uint8_t [decodedSize];
memcpy(buffer2, buffer, decodedSize);
MediaBufferSP mediaOutputBuffer = MediaBuffer::createMediaBuffer(MediaBuffer::MBT_RawVideo);
mediaOutputBuffer->setBufferInfo((uintptr_t *)&buffer2, NULL, &decodedSize, 1);
mediaOutputBuffer->setSize(decodedSize);
mediaOutputBuffer->setPts(pts);
mediaOutputBuffer->setDts(dts);
mediaOutputBuffer->setDuration(mediaInputBuffer->duration());
mediaOutputBuffer->addReleaseBufferFunc(releaseOutputBuffer);
mediaOutputBuffer->setMonitor(mDecoder->mMonitorWrite);
INFO("video info:buffer:%p,size:%d,pts:%" PRId64 ",dts:%" PRId64 ",duration:%" PRId64 "\n",
buffer2, decodedSize, pts, dts, mediaInputBuffer->duration());
mm_status_t status = mDecoder->mWriter->write(mediaOutputBuffer);
if (status != MM_ERROR_SUCCESS && status != MM_ERROR_ASYNC) {
ERROR("decoder fail to write Sink");
break;
}
frameIdx++;
TrafficControl * trafficControlWrite = static_cast<TrafficControl*>(mDecoder->mMonitorWrite.get());
trafficControlWrite->waitOnFull();
}else { //if (mediaBuffer) {
//INFO("read NULL buffer from demuxer\n");
usleep(10*1000);
}
usleep(5*1000);
}
INFO("Video Output thread exited\n");
return;
}
private:
FakeVideoDecode *mDecoder;
};
FakeVideoDecode(const char *mimeType = NULL, bool isEncoder = false)
{
mIsExit = true;
mMonitorWrite.reset(new TrafficControl(1,10,"FakeVideoDecodeWrite"));
return;
}
virtual ~FakeVideoDecode() { return ; }
virtual const char * name() const { return "FakeVideoDecoder"; }
COMPONENT_VERSION;
virtual mm_status_t addSource(Component * component, MediaType mediaType)
{
if (component && mediaType == kMediaTypeVideo) {
mReader = component->getReader(kMediaTypeVideo);
if (mReader) {
MediaMetaSP metaData;
metaData = mReader->getMetaData();
if (metaData) {
mMetaData = metaData->copy();
return MM_ERROR_SUCCESS;
}
}
}
return MM_ERROR_IVALID_OPERATION;
}
virtual mm_status_t addSink(Component * component, MediaType mediaType)
{
//#0 set the write meta data
if (component && mediaType == kMediaTypeVideo) {
mWriter = component->getWriter(kMediaTypeVideo);
//#0 Width|Height|pixFmt|gopSize|bitRate
mMetaData->setInt32(MEDIA_ATTR_CODECID, 'H264');
mMetaData->setInt32(MEDIA_ATTR_WIDTH, 640);
mMetaData->setInt32(MEDIA_ATTR_HEIGHT, 360);
mMetaData->setInt32(MEDIA_ATTR_COLOR_FOURCC, 'YV12');
mMetaData->setInt32(MEDIA_ATTR_GOP_SIZE, 12);
mMetaData->setInt32(MEDIA_ATTR_BIT_RATE, 764836);
//#1 timeBase|extraData
mMetaData->setFraction(MEDIA_ATTR_TIMEBASE, 16384, 785645);
mMetaData->setFraction(MEDIA_ATTR_TIMEBASE2, 1, 1000000);
unsigned char buf[40];
FILE *fp;
fp = fopen("/home/haibinwuhb/work/cow_player/39.bin", "rb");
fread(buf,1,39,fp);
fclose(fp);
mMetaData->setByteBuffer(MEDIA_ATTR_CODEC_DATA, buf, 39);
INFO("now start to send video parameters\n");
mWriter->setMetaData(mMetaData);
}
return MM_ERROR_SUCCESS;
}
virtual mm_status_t start()
{
mIsExit = false;
if (!mDecodeThread) {
// create thread to decode buffer
mDecodeThread.reset (new DecodeThreadV(this), MMThread::releaseHelper);
mDecodeThread->create();
}
usleep(500*1000);
return MM_ERROR_SUCCESS;
}
virtual mm_status_t stop()
{
TrafficControl * trafficControlWrite = static_cast<TrafficControl*>(mMonitorWrite.get());
trafficControlWrite->unblockWait();
mIsExit = true;
usleep(500*1000);
if (mDecodeThread) {
mDecodeThread.reset();
}
return MM_ERROR_SUCCESS;
}
virtual mm_status_t release() { return MM_ERROR_SUCCESS; }
virtual mm_status_t init() { return MM_ERROR_SUCCESS; }
virtual void uninit() { return; }
virtual mm_status_t prepare() { return MM_ERROR_SUCCESS; }
virtual mm_status_t resume() { return MM_ERROR_SUCCESS; }
virtual mm_status_t pause() { return MM_ERROR_SUCCESS; }
virtual mm_status_t seek(int msec, int seekSequence) { return MM_ERROR_SUCCESS; }
virtual mm_status_t reset() { return MM_ERROR_SUCCESS; }
virtual mm_status_t flush() { return MM_ERROR_SUCCESS; }
virtual mm_status_t setParameter(const MediaMetaSP & meta) { return MM_ERROR_SUCCESS; }
virtual ReaderSP getReader(MediaType mediaType) { return ReaderSP((Reader*)NULL); }
virtual WriterSP getWriter(MediaType mediaType) { return WriterSP((Writer*)NULL); }
virtual mm_status_t drain() { return MM_ERROR_UNSUPPORTED; }
virtual mm_status_t read(MediaBufferSP & buf) { return MM_ERROR_UNSUPPORTED; }
virtual mm_status_t write(MediaBufferSP & buf) { return MM_ERROR_UNSUPPORTED; }
virtual MediaMetaSP getMetaData() {return MediaMetaSP((MediaMeta*)NULL);}
virtual mm_status_t setMetaData(const MediaMetaSP & metaData) { return MM_ERROR_UNSUPPORTED; }
private:
MediaMetaSP mMetaData;
DecodeThreadVSP mDecodeThread;
MonitorSP mMonitorWrite;
ReaderSP mReader;
WriterSP mWriter;
bool mIsExit;
MM_DISALLOW_COPY(FakeVideoDecode);
};
///////////AudioDecode////////////////////////////
class FakeAudioDecode : public FilterComponent
{
public:
class DecodeThreadA;
typedef MMSharedPtr <DecodeThreadA> DecodeThreadASP;
class DecodeThreadA : public MMThread
{
public:
DecodeThreadA(FakeAudioDecode *decoder) : MMThread("FakeAudioDecodeThd")
{
mDecoder = decoder;
}
~DecodeThreadA() { return; }
protected:
virtual void main()
{
while(1) {
MediaBufferSP mediaInputBuffer;
{
if (mDecoder->mIsExit) {
INFO("now to exit\n");
break;
}
mDecoder->mReader->read(mediaInputBuffer);
}
if (mediaInputBuffer) {
uint8_t *buffer = NULL;
int decodedSize = 0;
int64_t pts,dts;
mediaInputBuffer->getBufferInfo((uintptr_t *)&buffer, NULL, NULL, 1);
decodedSize = mediaInputBuffer->size();
pts = mediaInputBuffer->pts();
dts = mediaInputBuffer->dts();
uint8_t *buffer2 = new uint8_t [decodedSize];
memcpy(buffer2, buffer, decodedSize);
MediaBufferSP mediaOutputBuffer = MediaBuffer::createMediaBuffer(MediaBuffer::MBT_RawAudio);
mediaOutputBuffer->setBufferInfo((uintptr_t *)&buffer2, NULL, &decodedSize, 1);
mediaOutputBuffer->setSize(decodedSize);
mediaOutputBuffer->setPts(pts);
mediaOutputBuffer->setDts(dts);
mediaOutputBuffer->setDuration(mediaInputBuffer->duration());
mediaOutputBuffer->addReleaseBufferFunc(releaseOutputBuffer);
mediaOutputBuffer->setMonitor(mDecoder->mMonitorWrite);
INFO("audio info:buffer:%p, size:%d, pts:%" PRId64 ", dts:%" PRId64 ",duration:%" PRId64 "\n",
buffer2, decodedSize, pts, dts, mediaInputBuffer->duration());
mm_status_t status = mDecoder->mWriter->write(mediaOutputBuffer);
if (status != MM_ERROR_SUCCESS && status != MM_ERROR_ASYNC) {
ERROR("decoder fail to write Sink");
break;
}
TrafficControl * trafficControlWrite = static_cast<TrafficControl*>(mDecoder->mMonitorWrite.get());
trafficControlWrite->waitOnFull();
}else { //if (mediaBuffer) {
//INFO("read NULL buffer from demuxer\n");
usleep(10*1000);
}
usleep(5*1000);
}
INFO("Audio Output thread exited\n");
return;
}
private:
FakeAudioDecode *mDecoder;
};
public:
FakeAudioDecode(const char *mimeType = NULL, bool isEncoder = false)
{
mIsExit = false;
mMonitorWrite.reset(new TrafficControl(1, 64, "FakeAudioDecodeWrite"));
return;
}
virtual ~FakeAudioDecode() { return; }
virtual const char * name() const { return "TestAudioDecoder"; }
COMPONENT_VERSION;
virtual mm_status_t addSource(Component * component, MediaType mediaType)
{
if (component && mediaType == kMediaTypeAudio) {
mReader = component->getReader(kMediaTypeAudio);
if (mReader) {
MediaMetaSP metaData;
metaData = mReader->getMetaData();
if (metaData) {
mMetaData = metaData->copy();
return MM_ERROR_SUCCESS;
}
}
}
return MM_ERROR_IVALID_OPERATION;
}
virtual mm_status_t addSink(Component * component, MediaType mediaType)
{
//#0 set the write meta data
if (component && mediaType == kMediaTypeAudio) {
mWriter = component->getWriter(kMediaTypeAudio);
mMetaData->setInt32(MEDIA_ATTR_CODECID, 'AAC');
mMetaData->setInt32(MEDIA_ATTR_SAMPLE_FORMAT, 'FLTP');
mMetaData->setInt32(MEDIA_ATTR_SAMPLE_RATE, 44100);
mMetaData->setInt32(MEDIA_ATTR_CHANNEL_COUNT, 2);
mMetaData->setInt32(MEDIA_ATTR_BIT_RATE, 128175);
mMetaData->setFraction(MEDIA_ATTR_TIMEBASE2, 1, 1000000);
//#1 extraData
unsigned char buf[40];
FILE *fp;
fp = fopen("/home/haibinwuhb/work/cow_player/5.bin", "rb");
fread(buf,1,5,fp);
fclose(fp);
mMetaData->setByteBuffer(MEDIA_ATTR_CODEC_DATA, buf, 5);
INFO("now start to send audio parameters\n");
mWriter->setMetaData(mMetaData);
}
return MM_ERROR_SUCCESS;
}
virtual mm_status_t start()
{
mIsExit = false;
if (!mDecodeThread) {
// create thread to decode buffer
mDecodeThread.reset (new DecodeThreadA(this), MMThread::releaseHelper);
mDecodeThread->create();
}
usleep(500*1000);
return MM_ERROR_SUCCESS;
}
virtual mm_status_t stop()
{
TrafficControl * trafficControlWrite = static_cast<TrafficControl*>(mMonitorWrite.get());
trafficControlWrite->unblockWait();
mIsExit = true;
usleep(500*1000);
if (mDecodeThread) {
mDecodeThread.reset();
}
return MM_ERROR_SUCCESS;
}
virtual mm_status_t prepare() { return MM_ERROR_SUCCESS; }
virtual mm_status_t release() { return MM_ERROR_SUCCESS; }
virtual mm_status_t init() { return MM_ERROR_SUCCESS; }
virtual void uninit() { return; }
virtual mm_status_t resume() { return MM_ERROR_SUCCESS; }
virtual mm_status_t pause() { return MM_ERROR_SUCCESS; }
virtual mm_status_t seek(int msec, int seekSequence) { return MM_ERROR_SUCCESS; }
virtual mm_status_t reset() { return MM_ERROR_SUCCESS; }
virtual mm_status_t flush() { return MM_ERROR_SUCCESS; }
virtual mm_status_t setParameter(const MediaMetaSP & meta) { return MM_ERROR_SUCCESS; }
virtual ReaderSP getReader(MediaType mediaType) { return ReaderSP((Reader*)NULL); }
virtual WriterSP getWriter(MediaType mediaType) { return WriterSP((Writer*)NULL); }
virtual mm_status_t drain() { return MM_ERROR_UNSUPPORTED; }
virtual mm_status_t read(MediaBufferSP & buf) { return MM_ERROR_UNSUPPORTED; }
virtual mm_status_t write(MediaBufferSP & buf) { return MM_ERROR_UNSUPPORTED; }
virtual MediaMetaSP getMetaData() { return MediaMetaSP((MediaMeta*)NULL); }
virtual mm_status_t setMetaData(const MediaMetaSP & metaData) { return MM_ERROR_UNSUPPORTED; }
private:
MediaMetaSP mMetaData;
DecodeThreadASP mDecodeThread;
MonitorSP mMonitorWrite;
ReaderSP mReader;
WriterSP mWriter;
bool mIsExit;
MM_DISALLOW_COPY(FakeAudioDecode);
};
static const char *input_url = NULL;
static const char *output_url = NULL;
int main(int argc, char *argv[])
{
PlaySourceComponent *avDemuxer;
ComponentSP rtpMuxer;
FakeAudioDecode *audioDecoder;
FakeVideoDecode *videoDecoder;
mm_status_t status;
//#0 parse the command
if (argc == 3) {
input_url = argv[1];
output_url = argv[2];
} else {
INFO("input parameters are failed\n");
return -1;
}
INFO("input file:%s,output file:%s\n", input_url,output_url);
//#1 create the avDemuxer plugin
avDemuxer = new AVDemuxer();
status = avDemuxer->init();
if (status != MM_ERROR_SUCCESS) {
INFO("init source fail %d", status);
return -1;
}
if (input_url)
avDemuxer->setUri(input_url);
INFO("avDemuxer had been created,input_url:%s\n",input_url);
//#2 create the video decoder plugin
videoDecoder = new FakeVideoDecode();
status = videoDecoder->init();
INFO("video decoder had been created\n");
//#3 create the audio decoder plugin
audioDecoder = new FakeAudioDecode();
status = audioDecoder->init();
INFO("audio decoder had been created\n");
//#4 create the upload stream plugin
rtpMuxer = ComponentFactory::create(NULL, YUNOS_MM::MEDIA_MIMETYPE_MEDIA_RTP_MUXER, false);
if (!rtpMuxer.get()) {
INFO("cannot load decoder");
return -1;
}
status = rtpMuxer->init();
MediaMetaSP paramSP(MediaMeta::create());
paramSP->setString(YUNOS_MM::MEDIA_ATTR_FILE_PATH, output_url);
INFO("ggggggggggggg:%s\n", output_url);
status = rtpMuxer->setParameter(paramSP);
//#5 link every plugin
//video::addSource
status = videoDecoder->addSource(avDemuxer, Component::kMediaTypeVideo);
if (status != MM_ERROR_SUCCESS) {
if (status != MM_ERROR_ASYNC) {
INFO("video decoder add source fail %d", status);
return -1;
}
INFO("video decoder add source ASYNC");
usleep(10*1000);
}
INFO("video decoder had been addSource\n");
//video::addSink
status = videoDecoder->addSink(rtpMuxer.get(), Component::kMediaTypeVideo);
if (status != MM_ERROR_SUCCESS) {
if (status != MM_ERROR_ASYNC) {
INFO("video decoder add sink fail %d", status);
return -1;
}
INFO("video decoder add addSink ASYNC");
usleep(10*1000);
}
INFO("video decoder had been addSink\n");
//audio::addSource
status = audioDecoder->addSource(avDemuxer, Component::kMediaTypeAudio);
if (status != MM_ERROR_SUCCESS) {
if (status != MM_ERROR_ASYNC) {
INFO("audio decoder add source fail %d", status);
return -1;
}
INFO("audio decoder add source ASYNC");
usleep(10*1000);
}
INFO("audio decoder had been addSource\n");
//audio::addSink
status = audioDecoder->addSink(rtpMuxer.get(), Component::kMediaTypeAudio);
if (status != MM_ERROR_SUCCESS) {
if (status != MM_ERROR_ASYNC) {
INFO("audio decoder add sink fail %d", status);
return -1;
}
INFO("audio decoder add addSink ASYNC");
usleep(10*1000);
}
INFO("audio decoder had been addSink\n");
//#6 start rtpMuxer
status = rtpMuxer->prepare();
if (status != MM_ERROR_SUCCESS) {
if (status != MM_ERROR_ASYNC) {
INFO("rtpMuxer prepare fail %d", status);
return -1;
}
INFO("rtpMuxer prepare ASYNC");
usleep(10*1000);
}
INFO("rtpMuxer had been prepare\n");
status = rtpMuxer->start();
if (status != MM_ERROR_SUCCESS) {
if (status != MM_ERROR_ASYNC) {
INFO("rtpMuxer start fail %d\n", status);
return -1;
}
INFO("rtpMuxer start ASYNC");
usleep(10*1000);
}
INFO("rtpMuxer had been start\n");
//#7 start videoDecoder
status = videoDecoder->prepare();
if (status != MM_ERROR_SUCCESS) {
if (status != MM_ERROR_ASYNC) {
INFO("videoDecoder prepare fail %d", status);
return -1;
}
INFO("videoDecoder prepare ASYNC");
usleep(10*1000);
}
INFO("videoDecoder had been prepare\n");
status = videoDecoder->start();
if (status != MM_ERROR_SUCCESS) {
if (status != MM_ERROR_ASYNC) {
INFO("videoDecoder start fail %d\n", status);
return -1;
}
INFO("videoDecoder start ASYNC");
usleep(10*1000);
}
INFO("videoDecoder had been start\n");
//#8 start audioDecoder
status = audioDecoder->prepare();
if (status != MM_ERROR_SUCCESS) {
if (status != MM_ERROR_ASYNC) {
INFO("audioDecoder prepare fail %d", status);
return -1;
}
INFO("audioDecoder prepare ASYNC");
usleep(10*1000);
}
INFO("audioDecoder had been prepare\n");
status = audioDecoder->start();
if (status != MM_ERROR_SUCCESS) {
if (status != MM_ERROR_ASYNC) {
INFO("audioDecoder start fail %d\n", status);
return -1;
}
INFO("audioDecoder start ASYNC");
usleep(10*1000);
}
INFO("audioDecoder had been start\n");
//#9 start avDemuxer
status = avDemuxer->prepare();
if (status != MM_ERROR_SUCCESS) {
if (status != MM_ERROR_ASYNC) {
INFO("avDemuxer prepare fail %d\n", status);
return -1;
}
INFO("avDemuxer prepare\n");
usleep(10*1000);
}
INFO("avDemuxer had been prepare\n");
status = avDemuxer->start();
if (status != MM_ERROR_SUCCESS) {
if (status != MM_ERROR_ASYNC) {
INFO("avDemuxer start fail %d\n", status);
return -1;
}
INFO("avDemuxer start ASYNC");
usleep(10*1000);
}
INFO("avDemuxer had been start\n");
//#10 stop the plugins
INFO("wait to end \n");
usleep(1000*1000*1000);
avDemuxer->stop();
usleep(100*1000);
INFO("avDemuxer had been stop\n");
videoDecoder->stop();
usleep(100*1000);
INFO("videoDecoder had been stop\n");
audioDecoder->stop();
usleep(100*1000);
INFO("audioDecoder had been stop\n");
rtpMuxer->stop();
usleep(100*1000);
INFO("rtpMuxer had been stop\n");
//#11 release
avDemuxer->uninit();
videoDecoder->uninit();
audioDecoder->uninit();
rtpMuxer->uninit();
INFO("all had been uninit\n");
delete avDemuxer;
delete videoDecoder;
delete audioDecoder;
rtpMuxer.reset();
INFO("all had been delete\n");
return 0;
}
|
#include<iostream>
#include<cmath>
#include<cstring>
using namespace std;
const int MAX_M=10;
const int MAX_N=100;
const int MAX_STEP=MAX_M*MAX_N;
int m,n;
bool reversed;
bool light[MAX_M][MAX_N];
bool _light[MAX_M][MAX_N];
bool __light[MAX_M][MAX_N];
int dfsArray[MAX_STEP][2],dfsStep;
int ans=-1;
int process(int i,int j)
{
light[i][j]=!light[i][j];
if(i-1>=0)
{
light[i-1][j]=!light[i-1][j];
}
if(j-1>=0)
{
light[i][j-1]=!light[i][j-1];
}
if(i+1<m)
{
light[i+1][j]=!light[i+1][j];
}
if(j+1<n)
{
light[i][j+1]=!light[i][j+1];
}
return 0;
}
int _process(int i,int j)
{
_light[i][j]=!_light[i][j];
if(i-1>=0)
{
_light[i-1][j]=!_light[i-1][j];
}
if(j-1>=0)
{
_light[i][j-1]=!_light[i][j-1];
}
if(i+1<m)
{
_light[i+1][j]=!_light[i+1][j];
}
if(j+1<n)
{
_light[i][j+1]=!_light[i][j+1];
}
return 0;
}
int copyto()
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
_light[i][j]=light[i][j];
}
}
return 0;
}
int _copyto()
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
__light[i][j]=light[i][j];
}
}
return 0;
}
int _copyfrom()
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
light[i][j]=__light[i][j];
}
}
return 0;
}
int print()
{
/*
ans++;
cout <<"Ans"<<ans<<":"<<endl;
for(int i=0;i<dfsStep;i++)
{
if(!reversed)
{
cout <<"Step "<<i+1<<": "<<dfsArray[i][0]<<","<<dfsArray[i][1]<<endl;
}
else
{
cout <<"Step "<<i+1<<": "<<dfsArray[i][1]<<","<<dfsArray[i][0]<<endl;
}
}
*/
if(ans==-1 || ans>dfsStep)
{
ans=dfsStep;
}
return 0;
}
int paint()
{
bool flag=false;
copyto();
for(int i=1;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(_light[i-1][j]==false)
{
dfsArray[dfsStep][0]=i;
dfsArray[dfsStep][1]=j;
dfsStep++;
_process(i,j);
}
}
}
for(int j=0;j<n;j++)
{
if(_light[m-1][j]==false)
{
flag=true;
break;
}
}
if(!flag)
{
print();
}
return 0;
}
int dfs(int i)
{
if(i>=n)
{
int tmpdfsStep=dfsStep;
paint();
dfsStep=tmpdfsStep;
return 0;
}
dfs(i+1);
dfsArray[dfsStep][0]=0;
dfsArray[dfsStep][1]=i;
if(reversed)swap(dfsArray[dfsStep][0],dfsArray[dfsStep][1]);
dfsStep++;
process(0,i);
dfs(i+1);
process(0,i);
dfsStep--;
return 0;
/*
_copyto();
for(int i=0;i<=pow(2,n);i++)
{
_copyfrom();
int j=i;
memset(dfsArray,0,sizeof(dfsArray));
dfsStep=0;
for(int k=0;k<n;k++)
{
if((j&(1<<k))==true)
{
dfsArray[dfsStep][0]=0;
dfsArray[dfsStep][1]=k;
process(0,k);
if(reversed)swap(dfsArray[dfsStep][0],dfsArray[dfsStep][1]);
dfsStep++;
}
}
int tmpdfsStep=dfsStep;
paint();
dfsStep=tmpdfsStep;
}
*/
//return 0;
}
int main()
{
//cin >>m>>n;
m=n=4;
if(m<n)reversed=true;
else reversed=false;
//reversed=false;
char tmp;
_copyto();
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin >>tmp;
if(tmp=='w')
{
if(reversed)
{
light[j][i]=false;
}
else
{
light[i][j]=false;
}
}
if(tmp=='b')
{
if(reversed)
{
light[j][i]=true;
}
else
{
light[i][j]=true;
}
}
}
}
if(reversed)
{
swap(m,n);
}
dfsStep=0;
dfs(0);
_copyfrom();
for(int i=0;i<m;i++)for(int j=0;j<n;j++)
{
light[i][j]=!light[i][j];
}
dfsStep=0;
dfs(0);
if(ans==-1)cout <<"Impossible"<<endl;
else cout <<ans<<endl;
return 0;
}
|
//
// Copyright Jason Rice 2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
//
#include "../game.hpp"
#include <catch.hpp>
TEST_CASE("Move tile to left.", "[tiles][game_apply_move]")
{
tiles::game x{
3, 3,
{{
1, 1, 1,
1, 0, 2,
1, 1, 1
}}
};
tiles::game expected{
3, 3,
{{
1, 1, 1,
1, 2, 0,
1, 1, 1
}}
};
CHECK(tiles::detail::apply_game_move(x, tiles::game_move{5}));
CHECK(x.board == expected.board);
}
TEST_CASE("Move tile to right.", "[tiles][game_apply_move]")
{
tiles::game x{
3, 3,
{{
1, 1, 1,
1, 2, 0,
1, 1, 1
}}
};
tiles::game expected{
3, 3,
{{
1, 1, 1,
1, 0, 2,
1, 1, 1
}}
};
CHECK(tiles::detail::apply_game_move(x, tiles::game_move{4}));
CHECK(x.board == expected.board);
}
TEST_CASE("Move tile up.", "[tiles][game_apply_move]")
{
tiles::game x{
3, 3,
{{
1, 1, 1,
1, 1, 0,
1, 1, 2
}}
};
tiles::game expected{
3, 3,
{{
1, 1, 1,
1, 1, 2,
1, 1, 0
}}
};
CHECK(tiles::detail::apply_game_move(x, tiles::game_move{8}));
CHECK(x.board == expected.board);
}
TEST_CASE("Move tile down.", "[tiles][game_apply_move]")
{
tiles::game x{
3, 3,
{{
2, 1, 1,
0, 1, 1,
1, 1, 1
}}
};
tiles::game expected{
3, 3,
{{
0, 1, 1,
2, 1, 1,
1, 1, 1
}}
};
CHECK(tiles::detail::apply_game_move(x, tiles::game_move{0}));
CHECK(x.board == expected.board);
}
TEST_CASE("An invalid move should not change state.", "[tiles][game_apply_move]")
{
{
tiles::game x{
3, 3,
{{
0, 1, 1,
1, 1, 1,
1, 1, 1
}}
};
tiles::game expected = x;
CHECK(false == tiles::detail::apply_game_move(x, tiles::game_move{0}));
CHECK(x.board == expected.board);
}
{
tiles::game x{
3, 3,
{{
1, 1, 1,
0, 1, 1,
1, 1, 1
}}
};
tiles::game expected = x;
CHECK(false == tiles::detail::apply_game_move(x, tiles::game_move{2}));
CHECK(x.board == expected.board);
}
}
|
#pragma once
#include "WShape.h"
class WCircle : public WShape
{
protected:
int Radius;//圆的半径
public:
WCircle();
WCircle(int x, int y,int r);
void Draw(CDC*pDC);
bool IsMatched(CPoint pnt);
void Serialize(CArchive& ar);
void SetAttribute(int nX, int nY, COLORREF nBoderColor, int nBoderType, int BoderWidth, COLORREF FillColor, int nFillType);
~WCircle();
DECLARE_SERIAL(WCircle)//声明类WRectangle是支持序列化
};
|
#pragma once
#include <GL/freeglut.h>
#include <math.h>
#include <time.h>
#define PI 3.141592
#define FPS_TIME 60
// 비트연산 동시키 입력
#define DIR_X_CCW 0x01 // 반시계
#define DIR_Y_CCW 0x02
#define DIR_Z_CCW 0x04
#define DIR_X_CW 0x08 // 시계
#define DIR_Y_CW 0x10
#define DIR_Z_CW 0x20
struct Shape {
float rotate = 0;
float position[3] = { 0,350,0 };
float size = 70;
float line = 4;
float t = 0;
GLfloat identity[16];
};
struct Camera {
float degree[3] = { -180,-90,90 };
float x = 0;
float y = 0;
float zoom = 0;
};
class CRun_time_Framework {
private:
static CRun_time_Framework* myself;
int m_nWidth;
int m_nHeight;
GLfloat point[10][10][3];
bool camera_is_front;
bool depth;
bool culling;
bool ground_line;
int ani_step;
float ball_rotate;
float ball_radius;
GLUquadricObj *qobj = gluNewQuadric();
GLfloat identity[16];
Shape ball;
Camera camera;
GLfloat Prevtime = 0;
GLfloat current_time;
GLint current_frame = 0;
unsigned char dir = 0; // 비트연산 동시키 입력
public:
CRun_time_Framework();
~CRun_time_Framework();
// 필수 함수
GLvoid Init();
GLvoid Reshape(int w, int h);
GLvoid draw();
GLvoid KeyboardDown(unsigned char key, int x, int y);
GLvoid KeyboardUp(unsigned char key, int x, int y);
GLvoid Mouse(int button, int state, int x, int y);
GLvoid Update();
// 만든 함수
GLvoid background(float r, float g, float b);
GLvoid ground();
GLvoid Piramid();
GLvoid Ball();
bool collide(RECT, RECT);
// 콜백 함수
static GLvoid Resize(int w, int h);
static GLvoid drawscene();
static GLvoid KeyDowninput(unsigned char key, int x, int y);
static GLvoid KeyUpinput(unsigned char key, int x, int y);
static GLvoid Mouseaction(int button, int state, int x, int y);
static GLvoid Updatecallback();
};
|
#include "Vector2.h"
Vector2::Vector2( )
{
m_posX = 0;
m_posY = 0;
}
Vector2::Vector2( int newX, int newY )
{
m_posX = newX;
m_posY = newY;
}
|
#include "secret_handshake.h"
namespace secret_handshake {
std::vector<std::string> commands(int num) {
std::vector<unsigned int> digitArray;
std::vector<std::string> stringArray;
while (num > 0) {
unsigned int res = num % 2;
num /= 2;
digitArray.push_back(res);
}
for (int i = 0; i < digitArray.size(); ++i) {
if (i == 0 && digitArray[i] == 1)
stringArray.push_back("wink");
if (i == 1 && digitArray[i] == 1)
stringArray.push_back("double blink");
if (i == 2 && digitArray[i] == 1)
stringArray.push_back("close your eyes");
if (i == 3 && digitArray[i] == 1)
stringArray.push_back("jump");
if (i == 4 && digitArray[i] == 1)
std::reverse(stringArray.begin(), stringArray.end());
}
return stringArray;
}
} // namespace secret_handshake
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QVector>
#include <QtMath>
#include <QSpinBox>
#include <QSpinBox>
#include <QRandomGenerator>
#include <QtGlobal>
#include <QAbstractButton>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_clicked();
void on_RandomHarmonicRadioButton_clicked();
void on_GivenHarmonicRadioButton_clicked();
void on_LimitHarmonicCheckBox_stateChanged(int arg1);
void on_RandomCarRadioButton_clicked();
void on_GivenCarRadioButton_clicked();
void on_LimitCarCheckBox_stateChanged(int arg1);
void on_RandomPlaneRadioButton_clicked();
void on_GivenPlaneRadioButton_clicked();
void on_LimitPlaneCheckBox_stateChanged(int arg1);
private:
Ui::MainWindow *ui;
double xBegin, xEnd, X;
QVector<double> x,y;
};
#endif // MAINWINDOW_H
|
#pragma once
struct GENS
{
short Index;
BYTE Rate;
short gen;
};
class cGens
{
public:
void ClearNewGensHealthBar();
void InsertNewGensHealthBar(short Index, BYTE Rate, short gen);
GENS* GetNewGensHealthBar(short Index);
static void DrawGensHealthBar();
static void DrawGensHealthBarOri();
};
extern cGens GensHPBar;
|
#include "heap.h"
#include <iostream>
class HeapNode{
int v;
int dist;
public:
HeapNode(int v_, int dist_):v(v_), dist(dist_){}
};
int main(){
MinHeap<int> minheap(12);
minheap.insert(3);
minheap.insert(6);
minheap.insert(9);
minheap.insert(7);
minheap.insert(4);
minheap.insert(13);
minheap.insert(8);
minheap.print_minheap();
int a = minheap.delete_min();
//std::cout << "The minimum value in the heap is " << a << std::endl;
minheap.print_minheap();
// std::cout << "The capacity of the min heap is.. " << minheap.getCapacity() << std::endl;
// std::cout << "The size of the min heap is.. " << minheap.getSize() << std::endl;
// std::cout << "the minimum element of the min heap is " << minheap.min_element() << std::endl;
}
|
#define NOMINMAX
#include "GSPlay.h"
#include "Shader.h"
#include "Texture.h"
#include "Model.h"
#include "Camera.h"
#include "Font.h"
#include "Sprite2D.h"
#include "Sprite3D.h"
#include "Text.h"
#include "GameButton.h"
#include "AnimationSprite.h"
#include <string>
#include "Application.h"
GSPlay::GSPlay()
{
}
GSPlay::~GSPlay()
{
}
void GSPlay::Init()
{
auto model = ResourceManagers::GetInstance()->GetModel("Sprite2D.nfg");
auto texture = ResourceManagers::GetInstance()->GetTexture("bg_main_menu1.tga");
// background
auto shader = ResourceManagers::GetInstance()->GetShader("TextureShader");
m_background = std::make_shared<ParallelBG>(model, shader, texture,100.0f);
// button close
texture = ResourceManagers::GetInstance()->GetTexture("btn_close.tga");
std::shared_ptr<GameButton> button = std::make_shared<GameButton>(model, shader, texture);
button->Set2DPosition(Globals::screenWidth - 50, 50);
button->SetSize(50, 50);
button->SetOnClick([]() {
GameStateMachine::GetInstance()->PopState();
});
m_listButton.push_back(button);
//main character
texture = ResourceManagers::GetInstance()->GetTexture("mcTextures/knight_downatk.tga");
shader = ResourceManagers::GetInstance()->GetShader("AnimationShader");
m_mainchar = std::make_shared<AnimationSprite>(model, shader, texture, 7, 0.1f);
m_mainchar->Set2DPosition(200, (float)Globals::screenHeight / 2);
m_mainchar->SetSize(200, 200);
this->aniState = ANIMATION_STATE::IDLE;
//camera
m_camera = m_mainchar->GetCamera();
//map initialization
for (int row = 0; row < 100; row++) {
for (int column = 0; column < 10; column++) {
type = lvl[row][column];
//type 0: nothing
if (type == 0) {
std::cout << "NO TEXTURES";
}
//type 1-5: platform
if (type == 1) {
shader = ResourceManagers::GetInstance()->GetShader("TextureShader");
texture = ResourceManagers::GetInstance()->GetTexture("tileset/grass03.tga");
m_platform = std::make_shared<Sprite2D>(model, shader, texture);
m_platform->Set2DPosition(row * 80, column * 80);
m_platform->SetSize(80, 80);
m_listplatform.push_back(m_platform);
}
if (type == 2) {
shader = ResourceManagers::GetInstance()->GetShader("TextureShader");
texture = ResourceManagers::GetInstance()->GetTexture("tileset/grass01.tga");
m_platform = std::make_shared<Sprite2D>(model, shader, texture);
m_platform->Set2DPosition(row * 80, column * 80);
m_platform->SetSize(80, 80);
m_listplatform.push_back(m_platform);
}
if (type == 3) {
shader = ResourceManagers::GetInstance()->GetShader("TextureShader");
texture = ResourceManagers::GetInstance()->GetTexture("tileset/grass20.tga");
m_platform = std::make_shared<Sprite2D>(model, shader, texture);
m_platform->Set2DPosition(row * 80, column * 80);
m_platform->SetSize(80, 80);
m_listplatform.push_back(m_platform);
}
if (type == 4) {
shader = ResourceManagers::GetInstance()->GetShader("TextureShader");
texture = ResourceManagers::GetInstance()->GetTexture("tileset/grass24.tga");
m_platform = std::make_shared<Sprite2D>(model, shader, texture);
m_platform->Set2DPosition(row * 80, column * 80);
m_platform->SetSize(80, 80);
m_listplatform.push_back(m_platform);
}
if (type == 5) {
shader = ResourceManagers::GetInstance()->GetShader("TextureShader");
texture = ResourceManagers::GetInstance()->GetTexture("tileset/grass27.tga");
m_platform = std::make_shared<Sprite2D>(model, shader, texture);
m_platform->Set2DPosition(row * 80, column * 80);
m_platform->SetSize(80, 80);
m_listplatform.push_back(m_platform);
}
//type 6-7: unknown
if (type == 6) {
}
if (type == 7) {
}
//type 8-10: enemy
if (type == 8) {
//stand enemy
shader = ResourceManagers::GetInstance()->GetShader("AnimationShader");
texture = ResourceManagers::GetInstance()->GetTexture("enemyTextures/skeleton_atk.tga");
m_enemyS = std::make_shared<AnimationSprite>(model, shader, texture, 18, 0.05f);
m_enemyS->Set2DPosition(row * 80, column * 80);
m_enemyS->SetSize(80, 80);
m_listenemy.push_back(m_enemyS);
}
if (type == 9) {
//moving enemy
shader = ResourceManagers::GetInstance()->GetShader("AnimationShader");
texture = ResourceManagers::GetInstance()->GetTexture("enemyTextures/skeleton_walk.tga");
m_enemyM = std::make_shared<AnimationSprite>(model, shader, texture, 13, 0.1f);
m_enemyM->Set2DPosition(row * 80, column * 80);
m_enemyM->SetSize(80, 80);
m_listenemyM.push_back(m_enemyM);
}
if (type == 10) {
//boss
shader = ResourceManagers::GetInstance()->GetShader("AnimationShader");
texture = ResourceManagers::GetInstance()->GetTexture("enemyTextures/king_fullcombo.tga");
m_boss = std::make_shared<AnimationSprite>(model, shader, texture, 58, 0.01f);
m_boss->Set2DPosition(row * 80, column * 80);
m_boss->SetSize(200, 400);
}
}
}
// score
std::string s = std::to_string(mainchar_hp);
shader = ResourceManagers::GetInstance()->GetShader("TextShader");
std::shared_ptr<Font> font = ResourceManagers::GetInstance()->GetFont("Caesar.otf");
m_score = std::make_shared<Text>(shader, font, s+"/20HP", TextColor::PURPLE, 1.0);
m_score->Set2DPosition(Vector2(5, 25));
}
void GSPlay::Exit()
{
}
void GSPlay::Pause()
{
}
void GSPlay::Resume()
{
}
void GSPlay::HandleEvents()
{
}
void GSPlay::HandleKeyEvents(int key, bool bIsPressed)
{
if (bIsPressed == true) {
switch (key) {
case 'A':
keyPressed |= KEY_MOVE_LEFT;
case 'D':
keyPressed |= KEY_MOVE_RIGHT;
case 'J':
keyPressed |= KEY_ATTACK;
case 'K':
keyPressed |= KEY_JUMP;
case 'L':
keyPressed |= KEY_ROLL;
default:
break;
}
}
else {
switch (key) {
case 'A':
keyPressed ^= KEY_MOVE_LEFT;
case 'D':
keyPressed ^= KEY_MOVE_RIGHT;
case 'J':
keyPressed ^= KEY_ATTACK;
case 'K':
keyPressed ^= KEY_JUMP;
case 'L':
keyPressed ^= KEY_ROLL;
default:
break;
}
}
}
void GSPlay::HandleTouchEvents(int x, int y, bool bIsPressed)
{
for (auto button : m_listButton)
{
if(button->HandleTouchEvents(x, y, bIsPressed))
{
break;
}
}
}
void GSPlay::HandleMouseMoveEvents(int x, int y)
{
}
void GSPlay::Update(float deltaTime)
{
//gravity update
m_mainchar->updatePhysics(100.0f, deltaTime);
m_boss->updatePhysics(100.0f, deltaTime);
//handle key events
if (keyPressed & KEY_MOVE_LEFT) {
m_mainchar->move(-1.0f, 0.0f, deltaTime);
this->aniState = ANIMATION_STATE::MOVING_LEFT;
movingRight = false;
m_camera->MoveLeft(deltaTime * 10.0f);
}
else if (keyPressed & KEY_MOVE_RIGHT) {
m_mainchar->move(1.0f, 0.0f, deltaTime);
this->aniState = ANIMATION_STATE::MOVING_RIGHT;
movingRight = true;
m_camera->MoveLeft(-deltaTime * 10.0f);
}
else if (keyPressed & KEY_JUMP && canJump == true) {
canJump = false;
m_mainchar->jump(deltaTime, 10.0f, jumpHeight);
this->aniState = ANIMATION_STATE::JUMP;
}
else if (keyPressed & KEY_ATTACK) {
this->aniState = ANIMATION_STATE::ATTACK;
}
else if (keyPressed & KEY_ROLL) {
this->aniState = ANIMATION_STATE::ROLL;
}
else {
this->aniState = ANIMATION_STATE::IDLE;
}
/*switch mainchar animation
this->updateAnimation(deltaTime);*/
//update Health Points
//list update
m_mainchar->Update(deltaTime);
m_boss->Update(deltaTime);
for (auto it : m_listenemy)
{
it->updatePhysics(100.0f, deltaTime);
it->Update(deltaTime);
for (auto pl : m_listplatform) {
checkCollisionPlatformE(it, pl, 0.0f,2.0f,2.0f, direction);
}
}
for (auto it : m_listenemyM)
{
it->updatePhysics(100.0f, deltaTime);
it->Update(deltaTime);
it->enemyPatrol(deltaTime);
for (auto pl : m_listplatform) {
checkCollisionPlatformE(it, pl, 0.0f, 2.0f, 2.0f, direction);
}
}
for (auto it : m_listButton)
{
it->Update(deltaTime);
}
for (auto it : m_listplatform) {
checkCollisionPlatform(m_mainchar, it, 0.0f,5.0f,2.0f,direction);
checkCollisionPlatformE(m_boss, it, 0.0f, 10.0f, 2.0f, direction);
}
}
bool GSPlay::checkCollisionCombat(std::shared_ptr<AnimationSprite> obj1, std::shared_ptr<AnimationSprite> obj2, GLfloat push,GLfloat hs1,GLfloat hs2) {
Vector3 Pos1 = obj1->GetPosition();
Vector3 HalfSize1 = obj1->GetScale().operator/(hs1);
Vector3 Pos2 = obj2->GetPosition();
Vector3 HalfSize2 = obj2->GetScale().operator/(hs2);
GLfloat dX = Pos1.x - Pos2.x;
GLfloat dY = Pos1.y - Pos2.y;
GLfloat iX = abs(dX) - (HalfSize1.x + HalfSize2.x);
GLfloat iY = abs(dY) - (HalfSize1.y + HalfSize2.y);
if (iX < 0.0f && iY < 0.0f) {
return true;
}
return false;
}
bool GSPlay::checkCollisionPlatform(std::shared_ptr<AnimationSprite> obj1, std::shared_ptr<Sprite2D> obj2, GLfloat push, GLfloat hs1, GLfloat hs2, Vector3 direction) {
Vector3 Pos1 = obj1->GetPosition();
Vector3 HalfSize1 = obj1->GetScale().operator/(hs1);
Vector3 Pos2 = obj2->GetPosition();
Vector3 HalfSize2 = obj2->GetScale().operator/(hs2);
GLfloat dX = Pos1.x - Pos2.x;
GLfloat dY = Pos1.y - Pos2.y;
GLfloat iX = abs(dX) - (HalfSize1.x + HalfSize2.x);
GLfloat iY = abs(dY) - (HalfSize1.y + HalfSize2.y);
if (iX < 0.0f && iY < 0.0f) {
push = std::min(std::max(0.0f, push), 1.0f);
if (abs(iX) < abs(iY)) {
if (dX > 0.0f) {
obj1->Set2DPosition(Pos1.x + (-iX * (1.0f - push)), Pos1.y);
obj2->Set2DPosition(Pos2.x + (iX * push), Pos2.y);
direction.x = 1.0f;
direction.y = 0.0f;
}
else {
obj1->Set2DPosition(Pos1.x + (iX * (1.0f - push)), Pos1.y);
obj2->Set2DPosition(Pos2.x + (-iX * push), Pos2.y);
direction.x = -1.0f;
direction.y = 0.0f;
}
}
else {
if (dY > 0.0f) {
obj1->Set2DPosition(Pos1.x, Pos1.y + (-iY * (1.0f - push)));
obj2->Set2DPosition(Pos2.x, Pos2.y + (iY * push));
direction.x = 0.0f;
direction.y = 1.0f;
}
else {
obj1->Set2DPosition(Pos1.x, Pos1.y + (iY * (1.0f - push)));
obj2->Set2DPosition(Pos2.x, Pos2.y + (-iY * push));
direction.x = 0.0f;
direction.y = -1.0f;
canJump = true;
}
}
return true;
}
return false;
}
bool GSPlay::checkCollisionPlatformE(std::shared_ptr<AnimationSprite> obj1, std::shared_ptr<Sprite2D> obj2, GLfloat push, GLfloat hs1, GLfloat hs2, Vector3 direction) {
Vector3 Pos1 = obj1->GetPosition();
Vector3 HalfSize1 = obj1->GetScale().operator/(hs1);
Vector3 Pos2 = obj2->GetPosition();
Vector3 HalfSize2 = obj2->GetScale().operator/(hs2);
GLfloat dX = Pos1.x - Pos2.x;
GLfloat dY = Pos1.y - Pos2.y;
GLfloat iX = abs(dX) - (HalfSize1.x + HalfSize2.x);
GLfloat iY = abs(dY) - (HalfSize1.y + HalfSize2.y);
if (iX < 0.0f && iY < 0.0f) {
push = std::min(std::max(0.0f, push), 1.0f);
if (abs(iX) < abs(iY)) {
if (dX > 0.0f) {
obj1->Set2DPosition(Pos1.x + (-iX * (1.0f - push)), Pos1.y);
obj2->Set2DPosition(Pos2.x + (iX * push), Pos2.y);
direction.x = 1.0f;
direction.y = 0.0f;
}
else {
obj1->Set2DPosition(Pos1.x + (iX * (1.0f - push)), Pos1.y);
obj2->Set2DPosition(Pos2.x + (-iX * push), Pos2.y);
direction.x = -1.0f;
direction.y = 0.0f;
}
}
else {
if (dY > 0.0f) {
obj1->Set2DPosition(Pos1.x, Pos1.y + (-iY * (1.0f - push)));
obj2->Set2DPosition(Pos2.x, Pos2.y + (iY * push));
direction.x = 0.0f;
direction.y = 1.0f;
}
else {
obj1->Set2DPosition(Pos1.x, Pos1.y + (iY * (1.0f - push)));
obj2->Set2DPosition(Pos2.x, Pos2.y + (-iY * push));
direction.x = 0.0f;
direction.y = -1.0f;
}
}
return true;
}
return false;
}
void GSPlay::updateHP(int &HP) {
}
void GSPlay::updateAnimation(GLfloat deltaTime) {
if (this->aniState == ANIMATION_STATE::IDLE) {
m_mainchar->setCurrentFrame(0);
auto model = ResourceManagers::GetInstance()->GetModel("Sprite2D.nfg");
auto texture = ResourceManagers::GetInstance()->GetTexture("mcTextures/Knight_idle.tga");
auto shader = ResourceManagers::GetInstance()->GetShader("AnimationShader");
Vector3 vec = m_mainchar->GetPosition();
m_mainchar = std::make_shared<AnimationSprite>(model, shader, texture, 15, 0.2f);
m_mainchar->Set2DPosition(vec.x, vec.y);
m_mainchar->SetSize(150, 150);
canJump = true;
}
else if (this->aniState == ANIMATION_STATE::MOVING_LEFT) {
m_mainchar->setCurrentFrame(0);
auto model = ResourceManagers::GetInstance()->GetModel("Sprite2D.nfg");
auto texture = ResourceManagers::GetInstance()->GetTexture("MC_idle_left.tga");
auto shader = ResourceManagers::GetInstance()->GetShader("AnimationShader");
Vector3 vec = m_mainchar->GetPosition();
m_mainchar = std::make_shared<AnimationSprite>(model, shader, texture, 6, 0.1f);
m_mainchar->Set2DPosition(vec.x, vec.y);
m_mainchar->SetSize(150, 150);
}
else if (this->aniState == ANIMATION_STATE::MOVING_RIGHT) {
m_mainchar->setCurrentFrame(0);
auto model = ResourceManagers::GetInstance()->GetModel("Sprite2D.nfg");
auto texture = ResourceManagers::GetInstance()->GetTexture("mcTextures/knight_move_right.tga");
auto shader = ResourceManagers::GetInstance()->GetShader("AnimationShader");
Vector3 vec = m_mainchar->GetPosition();
m_mainchar = std::make_shared<AnimationSprite>(model, shader, texture, 8, 0.1f);
m_mainchar->Set2DPosition(vec.x, vec.y);
m_mainchar->SetSize(150, 150);
}
else if (this->aniState == ANIMATION_STATE::ATTACK) {
m_mainchar->setCurrentFrame(0);
auto model = ResourceManagers::GetInstance()->GetModel("Sprite2D.nfg");
auto texture = ResourceManagers::GetInstance()->GetTexture("mcTextures/knight_downatk.tga");
auto shader = ResourceManagers::GetInstance()->GetShader("AnimationShader");
Vector3 vec = m_mainchar->GetPosition();
m_mainchar = std::make_shared<AnimationSprite>(model, shader, texture, 6, 0.1f);
m_mainchar->Set2DPosition(vec.x, vec.y);
m_mainchar->SetSize(200, 180);
}
else if (this->aniState == ANIMATION_STATE::JUMP) {
m_mainchar->setCurrentFrame(0);
auto model = ResourceManagers::GetInstance()->GetModel("Sprite2D.nfg");
auto texture = ResourceManagers::GetInstance()->GetTexture("MC_jump.tga");
auto shader = ResourceManagers::GetInstance()->GetShader("AnimationShader");
Vector3 vec = m_mainchar->GetPosition();
m_mainchar = std::make_shared<AnimationSprite>(model, shader, texture, 5, 0.1f);
m_mainchar->Set2DPosition(vec.x, vec.y);
m_mainchar->SetSize(150, 150);
}
else if (this->aniState == ANIMATION_STATE::ROLL) {
m_mainchar->setCurrentFrame(0);
auto model = ResourceManagers::GetInstance()->GetModel("Sprite2D.nfg");
auto texture = ResourceManagers::GetInstance()->GetTexture("MC_roll.tga");
auto shader = ResourceManagers::GetInstance()->GetShader("AnimationShader");
Vector3 vec = m_mainchar->GetPosition();
m_mainchar = std::make_shared<AnimationSprite>(model, shader, texture, 6, 0.1f);
m_mainchar->Set2DPosition(vec.x, vec.y);
m_mainchar->SetSize(150, 150);
}
}
void GSPlay::Draw()
{
m_background->Draw();
m_mainchar->Draw();
m_boss->Draw();
for (auto it : m_listenemy) {
it->Draw();
}
for (auto it : m_listenemyM) {
it->Draw();
}
for (auto it : m_listplatform) {
it->Draw();
}
for (auto it : m_listButton)
{
it->Draw();
}
m_score->Draw();
}
|
#ifndef MINITSC_ACTOR_HPP
#define MINITSC_ACTOR_HPP
/**
* Actor class. An actor is an entity in the level that somehow
* interacts with the player (or even does no interaction).
* Basically every level object is an actor. Not actors are
* graphics like the time display as they’re not level elements.
*
* This is an abstract class that is intended to be subclassed.
*/
class Actor
{
public:
Actor();
virtual ~Actor();
virtual void draw(sf::RenderWindow& stage);
virtual void update();
private:
};
#endif
|
#include "stru_cor.h"
#include "dao_cor.h"
#include <iostream>
#include <map>
#include <string.h>
using namespace std;
int coridMaker = 22222;
int getDashCnt(const char *content, char ch)
{
int cnt = 0;
for (int i = 0; i < strlen(content); ++i)
{
if (content[i] == ch)
{
cnt++;
}
}
return cnt;
} //获取某一字符串中,某一字符的出现个数
CorNode *makeCor(const char *content)
{
CorNode *corp = (CorNode *)malloc(sizeof(CorNode));
if (content == "")
{
map<int,int> lines;
corp->id = findCorLines(1,"",lines) + coridMaker;
corp->name = "";
corp->property = "默认";
corp->hours = 0;
corp->credit = 0;
corp->choosedBy = 0;
corp->maxChoose = 0;
return corp;
}
if (getDashCnt(content, '-') != 6)
{
free(corp);
return NULL;
}
char *corpros[10];
// sscanf(content,"%s-%s-%s-%s-%s-%s-%s",corpros);
char str[100] = {0};
strcpy(str, content);
const char *delim = "-";
char *p;
int i = 1;
do
{
p = (char *)malloc(30);
char *tmp = strtok(i == 1 ? str : NULL, delim);
if (tmp)
strcpy(p, tmp);
else
break;
corpros[i] = p;
++i;
} while (1);
corp->id = atoi(corpros[1]);
corp->name = corpros[2];
corp->property = corpros[3];
corp->hours = atoi(corpros[4]);
corp->credit = atoi(corpros[5]);
corp->choosedBy = atoi(corpros[6]);
corp->maxChoose = atoi(corpros[7]);
return corp;
} //通过字符串来构造课程节点指针。
CorNode *addCourse()
{
CorNode *corp = makeCor("");
if (corp == NULL)
{
puts("对不起,现在无法添加课程");
return NULL;
}
char corpros[10][50];
puts("请输入课程名:");
cin >> corpros[2];
puts("请输入课程类别:");
cin >> corpros[3];
puts("请输入课程学时:");
cin >> corpros[4];
puts("请输入课程学分:");
cin >> corpros[5];
puts("请输入课程最大选课人数:");
cin >> corpros[7];
corp->name = corpros[2];
corp->property = corpros[3];
corp->hours = atoi(corpros[4]);
corp->credit = atoi(corpros[5]);
corp->maxChoose = atoi(corpros[7]);
cout << corp->maxChoose << endl;
//将课程添加到数据库
char buff[100] = {0};
sprintf(buff, "%d-%s-%s-%d-%d-%d-%d",
corp->id,
corp->name,
corp->property,
corp->hours,
corp->credit,
corp->choosedBy,
corp->maxChoose);
cout << buff << endl;
if (insertCor(buff) == -1)
{
free(corp);
return NULL;
}
puts("addCourse");
return corp;
} //添加一个课程,命令行询问课程信息,返回添加的课程
CorNode *deleteCourse()
{
char corid[50] = {0};
puts("请输入要删除的课程号");
cin >> corid;
map<int, int> lines;
int lcnt = findCorLines(1, corid, lines);
cout << lines.size() << endl;
if (lcnt <= 0)
{
puts("没有找到您输入的课程号,删除终止");
return NULL;
}
else if (lcnt > 1)
{
puts("输入的课程号相似的找到不止一个,删除终止");
return NULL;
}
puts("您想要删除的课程是:");
cout << findCor(lines[1]) << endl;
puts("您确定要删除这个课程吗:(y/n)");
string check;
cin >> check;
if (check != "y" && check != "Y" && check != "yes")
{
puts("删除取消");
return NULL;
}
CorNode *corp = makeCor(findCor(lines[1]).data());
if (removeCor(lines[1]) < 0)
{
puts("删除失败");
return NULL;
}
puts("deleteCourse");
return corp;
} //根据id删除课程,返回删除的课程,失败返回0
CorNode *modifyCourse()
{
char corid[50] = {0};
puts("请输入要修改的课程号");
cin >> corid;
map<int, int> lines;
int lcnt = findCorLines(1, corid, lines);
cout << lines.size() << endl;
if (lcnt <= 0)
{
puts("没有找到您输入的课程号,修改终止");
return NULL;
}
else if (lcnt > 1)
{
puts("输入的课程号相似的找到不止一个,修改终止");
return NULL;
}
CorNode *corp = makeCor(findCor(lines[1]).data());
string input;
printf("课程名(输入\"u\"保持不变)(%s):", corp->name);
cin >> input;
cout << input << endl;
if (input != "u")
{
strcpy(corp->name, input.data());
}
printf("课程类型(输入\"u\"保持不变)(%s):", corp->property);
cin >> input;
cout << input << endl;
if (input != "u")
{
strcpy(corp->property, input.data());
}
printf("课程学时(输入\"u\"保持不变)(%d):", corp->hours);
cin >> input;
cout << input << endl;
if (input != "u")
{
corp->hours = atoi(input.data()) >= 0 ? atoi(input.data()) : corp->hours;
}
printf("课程学分(输入\"u\"保持不变)(%d):", corp->credit);
cin >> input;
cout << input << endl;
if (input != "u")
{
corp->credit = atoi(input.data()) >= 0 ? atoi(input.data()) : corp->credit;
}
printf("课程最大选课人数(输入\"u\"保持不变)(%d):", corp->maxChoose);
cin >> input;
cout << input << endl;
if (input != "u")
{
corp->maxChoose = atoi(input.data()) >= 0 ? atoi(input.data()) : corp->maxChoose;
}
//将课程修改到数据库
char buff[100] = {0};
sprintf(buff, "%d-%s-%s-%d-%d-%d-%d",
corp->id,
corp->name,
corp->property,
corp->hours,
corp->credit,
corp->choosedBy,
corp->maxChoose);
cout << buff << endl;
if (changeCor(lines[1], buff) == -1)
{
puts("修改失败");
free(corp);
return NULL;
}
puts("modifyCourse");
return corp;
} //根据id修改课程,命令行询问修改项目,返回修改后的,失败返回0
CorNode *lookCourse()
{
puts("请输入要查看的课程(课程号或课程名):");
string corkey;
cin >> corkey;
map<int, int> corlines;
//如果输入的是以不为零的数字开头,则在课程号中找,否则在课程名中查找
int col = atoi(corkey.data()) == 0 ? 2 : 1;
if(findCorLines(col, corkey.data(), corlines)<=0){
puts("没找到");
return NULL;
}
printf("课程编号\t课程名称\t课程类型\t课程学时\t课程学分\t已选人数\t最大人数\n");
for(int i = 1;i<=corlines.size();++i){
CorNode *corp = makeCor(findCor(corlines[i]).data());
printf("%10d\t%8s\t%8s\t%10d\t%10d\t%10d\t%10d\n",
corp->id,
corp->name,
corp->property,
corp->hours,
corp->credit,
corp->choosedBy,
corp->maxChoose
);
free(corp);
}
puts("lookCourse");
return NULL;
} //根据id查看课程,命令行打出,返回课程。失败返回0
int listCourses()
{
map<int, int> corlines;
//如果输入的是以不为零的数字开头,则在课程号中找,否则在课程名中查找
if(findCorLines(1, "", corlines)<=0){
puts("没有");
return 0;
}
printf("课程编号\t课程名称\t课程类型\t课程学时\t课程学分\t已选人数\t最大人数\n");
for(int i = 1;i<=corlines.size();++i){
CorNode *corp = makeCor(findCor(corlines[i]).data());
printf("%10d\t%10s\t%10s\t%10d\t%10d\t%10d\t%10d\n",
corp->id,
corp->name,
corp->property,
corp->hours,
corp->credit,
corp->choosedBy,
corp->maxChoose
);
}
puts("listCourse");
return 0;
} //列出所有课程,返回课程数量,异常返回-1
|
/***************************************************************************
Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
2010-2020 DADI ORISTAR TECHNOLOGY DEVELOPMENT(BEIJING)CO.,LTD
FileName: OSMutex.h
Description: Provide a abstraction mutex class.
Comment: copy from Darwin Streaming Server 5.5.5
Author: taoyunxing@dadimedia.com
Version: v1.0.0.1
CreateDate: 2010-08-16
LastUpdate: 2010-08-19
****************************************************************************/
#ifndef _OSMUTEX_H_
#define _OSMUTEX_H_
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include "SafeStdLib.h"
#include "OSHeaders.h"
#include "OSThread.h" /* 这个是必须包含的,Thread和Mutex密切相关 */
#include "MyAssert.h"
class OSCond;
/* OSMutex类中真正的执行函数是RecursiveLock()/RecursiveUnlock()/RecursiveTryLock() */
class OSMutex
{
public:
OSMutex();
~OSMutex();
/* 这两个函数在 OSMutexLocker中封装 */
inline void Lock();
inline void Unlock();
// Returns true on successful grab of the lock, false on failure
/* 判断是否成功获取到锁? */
inline Bool16 TryLock();
private:
pthread_mutex_t fMutex;
// These two platforms don't implement pthreads recursive mutexes, so
// we have to do it manually
pthread_t fHolder;
UInt32 fHolderCount;//进入临界区线程数
/* 递归锁/解锁/试锁? */
/* 假如我们已经有了互斥锁(上次刚用的),再次抢占进入时仅重新计数并返回;否则首先进入临界区,获取当前Thread ID并使线程计数增加1 */
void RecursiveLock();
/* 假如不是当前线程,无须解锁,返回;否则确保当前线程引用计数>0,多次调用使其变为0.当线程引用计数为0时,使线程ID为0并离开临界区 */
void RecursiveUnlock();
/* 除了函数返回的是Bool值而非void外,其它和OSMutex::RecursiveLock()相同 */
Bool16 RecursiveTryLock();
friend class OSCond;
};
/* 注意OSMutexLocker类是OSMutex类的封装,包括Lock()和Unlock(),是专门执行上锁/解锁的互斥锁类,在实际执行中,只使用该类即可! */
class OSMutexLocker
{
public:
/* 注意这个函数非常重要,在使用Mutex的地方经常使用 */
OSMutexLocker(OSMutex *inMutexP) : fMutex(inMutexP) { if (fMutex != NULL) fMutex->Lock(); }
~OSMutexLocker() { if (fMutex != NULL) fMutex->Unlock(); }
void Lock() { if (fMutex != NULL) fMutex->Lock(); }
void Unlock() { if (fMutex != NULL) fMutex->Unlock(); }
private:
/* define the critical region variable */
/* 唯一的数据成员,被多处引用到 */
OSMutex* fMutex;
};
//member functions definitions of class OSMutex
void OSMutex::Lock()
{
this->RecursiveLock();
}
void OSMutex::Unlock()
{
this->RecursiveUnlock();
}
Bool16 OSMutex::TryLock()
{
return this->RecursiveTryLock();
}
#endif //_OSMUTEX_H_
|
/* checksum.h
* CSCE 612 - 600 Spring 2017
* HW3 reliable data transfer
* by Mian Qin
*/
#include "stdafx.h"
class Checksum
{
public:
DWORD crc_table[256];
Checksum();
DWORD CRC32(unsigned char *buf, size_t len);
};
|
#include "sede.h"
#include <iostream>
using namespace std;
Sede::Sede(string nombre_sede,int tiempo_sede)
{
this->nombre_sede = nombre_sede;
this->tiempo_sede = tiempo_sede;
}
|
#include "weapon.hpp"
/*
Construct a weapon by having a vector of bullets with a given keyword
A weapon will have a given delay time between shooting with the weapon
A specific cooldown will be used based on the given keyword.
*/
// this is for player only
Weapon::Weapon():
keyword("single"), shootCooldownSet(120)
{
std::vector<BulletTemplate*> bullets;
bullets.push_back(new BulletTemplate("bulletPlayer",1, 15, false, 0));
bullet_list = bullets;
}
Weapon::Weapon(std::vector <BulletTemplate*> bullets, std::string key_name, int delay, std::vector<int> key_params) :
bullet_list(bullets), keyword(key_name), shootCooldownSet(delay)
{
// If none of the other keywords match, the program will close
if (keyword == "rapid_player" || keyword == "rapid_enemy"){
rapidWaitSet = key_params[0];
rapidDurationSet = key_params[1];
return;
}
if (keyword == "hold_player"){
holdDurationSet = key_params[0];
return;
}
if (keyword == "sequence_enemy"){
sequenceDelaySet = key_params[0];
return;
}
exit(1);
}
Weapon::Weapon(std::vector <BulletTemplate*> bullets, std::string key_name, int delay) :
bullet_list(bullets), keyword(key_name), shootCooldownSet(delay)
{
if (keyword != "single") {
exit(1);
}
}
// copy constructor
Weapon::Weapon(const Weapon& source){
shootCooldownSet = source.shootCooldownSet;
rapidWaitSet = source.rapidWaitSet;
rapidDurationSet = source.rapidDurationSet;
sequenceDelaySet = source.sequenceDelaySet;
sequence_idx = source.sequence_idx;
holdDurationSet = source.holdDurationSet;
spawnTime = source.spawnTime;
keyword = source.keyword;
enemydidShoot = source.enemydidShoot;
for (auto bullet : source.bullet_list){
bullet_list.push_back(new BulletTemplate(*bullet));
}
}
// assignment operator
Weapon& Weapon::operator=(const Weapon& source){
// self checking
if (this == &source) return *this;
// first delete dynamic objects
for (auto bullet : bullet_list){
delete bullet;
}
bullet_list.clear();
// then initalize
///*
shootCooldownSet = source.shootCooldownSet;
rapidWaitSet = source.rapidWaitSet;
rapidDurationSet = source.rapidDurationSet;
sequenceDelaySet = source.sequenceDelaySet;
sequence_idx = source.sequence_idx;
holdDurationSet = source.holdDurationSet;
spawnTime = source.spawnTime;
keyword = source.keyword;
enemydidShoot = source.enemydidShoot;
//bullet_list = source.bullet_list;
for (auto bullet : source.bullet_list){
bullet_list.push_back(new BulletTemplate(*bullet));
}
//*/
return *this;
}
Weapon::~Weapon(){
for (BulletTemplate* bullet : bullet_list){
delete bullet;
}
}
void Weapon::update(Entity& shooter){
lookupShoot(shooter, this->keyword);
}
Weapon* Weapon::replaceWeapon(Weapon* newWeapon){
return new Weapon(*newWeapon);
}
void Weapon::lookupShoot(Entity& shooter, std::string name){
static std::map < std::string, void (Weapon::*)(Entity&) > table
{
{ "single", &Weapon::singleShot},
{ "rapid_player", &Weapon::rapidPlayer},
{ "rapid_enemy", &Weapon::rapidEnemy },
{ "hold_player", &Weapon::holdPlayer },
{ "sequence_enemy", &Weapon::sequenceEnemy }
};
auto entry = table.find(name);
if (entry != table.end()){
(this->*(entry->second)) (shooter);
}
else {
std::cerr << "Cannot find movement with the name " << name << std::endl;
std::exit(1);
}
}
// When an entity shoots bullets, we will find out if its a player or enemy
// to determine who shot them
// Shoot all bullets at once
void Weapon::shootBullets(Entity& shooter){
if (Enemy* enemy = dynamic_cast<Enemy*> (&shooter)){
enemydidShoot = true;
}
else if (Player* player = dynamic_cast<Player*> (&shooter)){
enemydidShoot = false;
}
for (auto bullet_data : bullet_list){
Bullet* bullet_p = new Bullet(
TextureManager::instance()->getRef(bullet_data->getTex()),
bullet_data->getHP(),
bullet_data->getSpeed(),
bullet_data->getInvincible(),
enemydidShoot,
bullet_data->getRotation() + (180 * enemydidShoot));
int shootFlip = enemydidShoot ? -1 : 1;
bullet_p->setPosition(shooter.getPosition().x + (shootFlip * shooter.getGlobalBounds().width / 2),
shooter.getPosition().y);
shooter.getScene()->storeAddedEntity(bullet_p);
}
}
// Shoot a single bullet
void Weapon::shootBullet(Entity& shooter, BulletTemplate& bullet){
if (Enemy* enemy = dynamic_cast<Enemy*> (&shooter)){
enemydidShoot = true;
}
else if (Player* player = dynamic_cast<Player*> (&shooter)){
enemydidShoot = false;
}
else {
return;
}
Bullet* bullet_p = new Bullet(
TextureManager::instance()->getRef(bullet.getTex()),
bullet.getHP(),
bullet.getSpeed(),
bullet.getInvincible(),
enemydidShoot,
bullet.getRotation() + (180 * enemydidShoot));
int shootFlip = enemydidShoot ? -1 : 1;
bullet_p->setPosition(shooter.getPosition().x + (shootFlip * shooter.getGlobalBounds().width / 2),
shooter.getPosition().y);
shooter.getScene()->storeAddedEntity(bullet_p);
}
void Weapon::singleShot(Entity& shooter){
// If entity is player, then cooldown will activate when player holds down fire key
// otherwise cooldown will reset to 0, to allow rapid pressing.
if (Player* player = dynamic_cast<Player*> (&shooter)){
if (Input::instance()->pressKeybutton(sf::Keyboard::Space)){
if (shootCooldownTime == 0){
shootBullets(shooter);
shootCooldownTime = shootCooldownSet;
}
else {
shootCooldownTime--;
}
}
else {
shootCooldownTime = 0;
}
}
if (Enemy* enemy = dynamic_cast<Enemy*> (&shooter)){
if (shootCooldownTime == 0){
shootBullets(shooter);
shootCooldownTime = shootCooldownSet;
}
else {
shootCooldownTime--;
}
}
}
void Weapon::rapidFire(Entity& shooter){
if (rapidWait == 0){
shootBullets(shooter);
rapidWait = rapidWaitSet;
}
else {
rapidWait--;
}
}
void Weapon::rapidEnemy(Entity& shooter){
if (shootCooldownTime == 0){
if (rapidDuration == 0){
shootCooldownTime = shootCooldownSet;
rapidDuration = rapidDurationSet;
}
else {
rapidFire(shooter);
rapidDuration--;
}
}
else shootCooldownTime--;
}
void Weapon::rapidPlayer(Entity& shooter){
if (Input::instance()->pressKeybutton(sf::Keyboard::Space)){
if (shootCooldownTime == 0){
if (rapidDuration == 0){
shootCooldownTime = shootCooldownSet;
rapidDuration = rapidDurationSet;
}
else {
rapidFire(shooter);
rapidDuration--;
}
}
else shootCooldownTime--;
}
else {
shootCooldownTime = 0;
}
}
void Weapon::holdPlayer(Entity& shoter){}
void Weapon::sequenceFire(Entity& shooter){
if (sequenceDelayTime == 0){
if (sequence_idx < bullet_list.size()){
shootBullet(shooter, *bullet_list[sequence_idx]);
sequenceDelayTime = sequenceDelaySet;
sequence_idx++;
}
else {
shootCooldownTime = shootCooldownSet;
sequence_idx = 0;
}
}
else {
sequenceDelayTime--;
}
}
void Weapon::sequenceEnemy(Entity& shooter){
if (shootCooldownTime == 0){
sequenceFire(shooter);
}
else shootCooldownTime--;
}
|
/*!
* \file onlyserial.ino
*
*
* \date 2015/03/15
*
* \author Matthias Schibli (based on sketch from Sven Burkart and Christian Leder)
*
* \brief decode Piksi position, baseline and time
\details
-
*/
#include <SPI.h>
#include <Wire.h>
#include <Time.h>
const unsigned int MAX_INPUT = 2000;
const int chipSelect = 10;
const float pi = 3.14159265359;
void setup()
{
Serial.begin(115200); // serial to pc
Serial2.begin (115200); // GPS
Serial.println("init");
}
// Definition of SBP Protocol here: https://github.com/swift-nav/libswiftnav/raw/master/docs/sbp.pdf
#define EndofMessage 0x55
#define Byte0LatLon 0x01
#define Byte1LatLon 0x02
#define Byte0NED 0x03
#define Byte1NED 0x02
#define Byte0Time 0x00
#define Byte1Time 0x01
#define LengthLatLon 41
#define LengthNED 29
#define LengthTime 18
void loop()
{
static double north=0;
static double east=0;
static double latitude=0;
static double longitude=0;
static long timestamp=0;
int newdata=0;
float heading=0;
while (Serial2.available () > 0)
{
processIncomingByte (Serial2.read (),timestamp,north,east,latitude,longitude, newdata);
}
if (newdata==true)
{
Serial2.flush();
Serial.print("timestamp ");
Serial.print(timestamp);
Serial.print(" north ");
Serial.print(north);
Serial.print(" east ");
Serial.print(east);
Serial.print(" latitude ");
Serial.print(latitude,7);
Serial.print(" longitude ");
Serial.print(longitude,7);
Serial.println();
}
}
void processIncomingByte (const byte inByte,long& timestamp,double& north, double& east,double& latitude,double& longitude, int&newdata)
{
// Serial.println(inByte , HEX);
static byte input_msg [MAX_INPUT];
static unsigned int input_pos = 0; // nicht negativer int und immer der gleiche int
static int newdataTime=0;
static int newdataNED=0;
static int newdataLatLon=0;
if (inByte == EndofMessage)
{
/*
//print serial data from Piksi for debugging
for( int i = 0 ; i < input_pos ; i++)
{
Serial.print(input_msg [i],HEX); // wenn hex 55 print gesammter puffer [input_msg)
Serial.print(" ");
}
Serial.println();
*/
if (input_pos >=LengthTime || input_pos >=LengthNED || input_pos >=LengthLatLon)
{
// NED Message
if((input_msg[0] == Byte0NED) && (input_msg[1] == Byte1NED) && input_pos == LengthNED)
{
msg_analyse (input_msg,north,east);
newdataNED=1;
input_pos = 0;
}
// LatLon Message
else if((input_msg[0] == Byte0LatLon) && (input_msg[1] == Byte1LatLon)&& input_pos == LengthLatLon)
{
msg_analyse_latlon (input_msg,latitude,longitude);
newdataLatLon=1;
input_pos = 0;
}
// Time Message
else if((input_msg[0] == Byte0Time) && (input_msg[1] == Byte1Time)&& input_pos == LengthTime)
{
msg_analyse_time (input_msg,timestamp);
newdataTime=1;
input_pos = 0;
}
else {}
}
// after message is parsed, set back to beginning
input_pos = 0;
if (newdataTime == true && newdataLatLon==true && newdataNED ==true)
{
newdata=true;
newdataTime =false;
newdataLatLon==false;
newdataNED =false;
}
}
// if no complete message in buffer, read out again and fill up input_msg
else
{
if (input_pos < (MAX_INPUT - 1))
{
input_msg [input_pos] = inByte;
input_pos = input_pos + 1;
}
}
}
void msg_analyse_latlon (byte byte_msg[41],double& latitude, double& longitude)
{
latitude = Bytes2Double (byte_msg[16], byte_msg[15], byte_msg[14], byte_msg[13],byte_msg[12], byte_msg[11], byte_msg[10], byte_msg[9]);
longitude = Bytes2Double (byte_msg[24], byte_msg[23], byte_msg[22], byte_msg[21],byte_msg[20], byte_msg[19], byte_msg[18], byte_msg[17]);
}
void msg_analyse (byte byte_msg[40],double& north, double& east)
{
north = Bytes2Intu32 (byte_msg[12], byte_msg[11], byte_msg[10], byte_msg[9]);
east = Bytes2Intu32 (byte_msg[16], byte_msg[15], byte_msg[14], byte_msg[13]);
}
void msg_analyse_time (byte byte_msg[40],long& timestamp)
{
int nrofweek=0;
int timeofweek=0;
nrofweek = Bytes2Intu16 ( byte_msg[6], byte_msg[5]);
timeofweek = Bytes2Intu32 (byte_msg[10], byte_msg[9], byte_msg[8], byte_msg[7]);
timestamp=timeofweek+nrofweek*7*24*3600;
}
int Bytes2Intu32 (int b4, int b3, int b2, int b1)
{
int result=0;
result=(b4 << 24) | (b3<<16) | (b2<<8) | b1;
return result;
}
// convert 2 bytes to int
int Bytes2Intu16 (int b2, int b1)
{
int result=0;
result=(b2<<8) | b1;
return result;
}
// convert 8 bytes to double
double Bytes2Double (int b8,int b7,int b6,int b5,int b4, int b3, int b2, int b1)
{
union u_tag
{
byte b[8];
double fval;
} u;
u.b[0] = b1;
u.b[1] = b2;
u.b[2] = b3;
u.b[3] = b4;
u.b[4] = b5;
u.b[5] = b6;
u.b[6] = b7;
u.b[7] = b8;
return u.fval;
}
|
//
// BOJ_17143_RE_RE_RE.cpp
// Algorithm
//
// Created by 박세은 on 2020/06/02.
// Copyright © 2020 박세은. All rights reserved.
//
/*
2020.06.02
17143. 낚시왕 다시풀기3
40분
*/
#include <iostream>
#include <vector>
using namespace std;
struct fish_info
{
int r, c, speed, dir, size;
bool alive = true;
fish_info(){}
fish_info(int rr, int cc, int sp, int dd, int ss)
{
r = rr; c = cc; speed = sp; dir = dd; size = ss;
}
};
int R, C, M, rr, cc, s, d, z, score = 0;
vector<fish_info> fish_list;
vector<int> origin[101][101];
int dr[4] = {-1,1,0,0};
int dc[4] = {0,0,1,-1};
void catch_fish(int c)
{
for(int i = 1; i <= R; i++)
{
if(!origin[i][c].empty())
{
fish_list[origin[i][c][0]].alive = false;
origin[i][c].pop_back();
score += fish_list[origin[i][c][0]].size;
return;
}
}
}
int reverse_dir(int d)
{
//d가 1인 경우는 위, 2인 경우는 아래, 3인 경우는 오른쪽, 4인 경우는 왼쪽을 의미한다.
if(d == 0) return 1;
if(d == 1) return 0;
if(d == 2) return 3;
if(d == 3) return 2;
return -1;
}
void move_fish()
{
vector<int> board[101][101];
for(int f = 0; f < fish_list.size(); f++)
{
if(!fish_list[f].alive) continue;
int dir = fish_list[f].dir;
int r = fish_list[f].r;
int c = fish_list[f].c;
int speed = 0;
if(dir == 0 || dir == 1) speed = fish_list[f].speed % (R*2-2);
else if(dir == 2 || dir == 3) speed = fish_list[f].speed % (C*2-2);
int size = fish_list[f].size;
for(int i = 0; i < speed; i++)
{
dir = fish_list[f].dir;
r += dr[dir];
c += dc[dir];
if(r < 1 || r > R || c < 1 || c > C)
{
r -= dr[dir];
c -= dc[dir];
int new_dir = reverse_dir(dir);
fish_list[f].dir = new_dir;
i--; continue;
}
}
if(!board[r][c].empty())
{
int ss = fish_list[board[r][c][0]].size;
if(ss > size)
{
fish_list[f].alive = false;
}
else
{
fish_list[board[r][c][0]].alive = false;
board[r][c].pop_back();
board[r][c].push_back(f);
fish_list[f].r = r;
fish_list[f].c = c;
}
}
else
{
board[r][c].push_back(f);
fish_list[f].r = r;
fish_list[f].c = c;
}
}
for(int r = 1; r <= R; r++)
{
for(int c = 1; c <= C; c++)
{
origin[r][c] = board[r][c];
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cin >> R >> C >> M;
for(int i = 0; i < M ;i++)
{
cin >> rr >> cc >> s >> d >> z;
fish_info tmp = fish_info(rr, cc, s, d-1, z);
fish_list.push_back(tmp);
origin[rr][cc].push_back(i);
}
for(int c = 1; c <= C; c++)
{
// 물고기 잡기
catch_fish(c);
// 물고기 이동
if(c != C) move_fish();
}
cout << score;
return 0;
}
|
#include "IVectorImpl.h"
//add error logging!
/*IVector::vector_ptr IVectorImpl::createVector(opt::Logger const& l) {
opt::ReturnCode err;
STATIC_CONSTRUCTOR(IVectorImpl, l);
}*/
IVector* IVector::createVector(uint size)
{
return IVectorImpl::createVector(size);
}
IVector* IVector::copyVector(const IVector& v)
{
return IVectorImpl::copyVector(v);
}
IVectorImpl::IVectorImpl(const IVector& v){
_dim = v.getDimension();
_vals = QVector<double>(_dim);
this->copyVector(v);
}
IVectorImpl::IVectorImpl(uint dim){
_dim = dim;
_vals = QVector<double>(_dim);
}
IVector* IVectorImpl::copyVector(const IVector& v)
{
return new IVectorImpl(v);
}
IVector* IVectorImpl::createVector(uint dim)
{
return new IVectorImpl(dim);
}
opt::ReturnCode IVectorImpl::add(IVector const& added)
{
DIM_CHECK(added)
opt::ReturnCode err = opt::NO_ERRORS;
double tmp = 0;
for (uint i = 0; i < _dim; i++)
{
err = added.getElement(i, tmp);
if (err != opt::NO_ERRORS)
return err;
_vals[i] += tmp;
}
return err;
}
opt::ReturnCode IVectorImpl::dotProduct(const IVector& multiplier, double& res)
{
DIM_CHECK(multiplier)
opt::ReturnCode error = opt::NO_ERRORS;
res = 0;
for (uint i = 0; i < _dim; i++)
{
double tmp = 0;
error = multiplier.getElement(i, tmp);
if (error)
return error;
res += _vals[i] * tmp;
}
return error;
}
opt::ReturnCode IVectorImpl::multiplyByScalar(double multipler)
{
for (uint i = 0; i < _dim; i++)
{
_vals[i] *= multipler;
}
return opt::NO_ERRORS;
}
opt::ReturnCode IVectorImpl::getElement(size_t index, double& elem) const
{
RANGE_CHECK(index)
elem = _vals[index];
return opt::NO_ERRORS;
}
opt::ReturnCode IVectorImpl::setElement(size_t index, double elem)
{
RANGE_CHECK(index)
_vals[index] = elem;
return opt::NO_ERRORS;
}
opt::ReturnCode IVectorImpl::setVector(const IVector& v)
{
DIM_CHECK(v)
opt::ReturnCode err = opt::NO_ERRORS;
for (unsigned i = 0; i < _dim; i++)
{
err = v.getElement(i, _vals[i]);
}
return err;
}
double IVectorImpl::_norm_l2() const{
double res = 0;
for(unsigned i = 0; i < _dim; i++)
{
res += _vals[i] * _vals[i];
}
return std::sqrt(res);
}
double IVectorImpl::_norm_l1() const{
double res = 0;
for(unsigned i = 0; i < _dim; i++)
{
res += std::abs(_vals[i]);
}
return res;
}
double IVectorImpl::norm(opt::TypeNorm t) const
{
switch(t)
{
case opt::NORM1:
{
return _norm_l1();
}
case opt::NORM2:
{
return _norm_l1();
}
default:
return -1;
}
}
bool IVectorImpl::GT(opt::TypeNorm t, const IVector& v) const
{
return norm(t) > v.norm(t);
}
bool IVectorImpl::LT(opt::TypeNorm t, const IVector& v) const
{
return norm(t) < v.norm(t);
}
bool IVectorImpl::eq(opt::TypeNorm t, const IVector& v) const
{
return norm(t) == v.norm(t);
}
opt::ReturnCode IVectorImpl::substract(IVector const& substracted){
DIM_CHECK(substracted)
double buff = 0;
opt::ReturnCode err = opt::NO_ERRORS;
for (uint i = 0; i < _dim; i++)
{
err = substracted.getElement(i, buff);
if(err)
return err;
_vals[i] -= buff;
}
return err;
}
void IVectorImpl::unaryMinus()
{
for (uint i = 0; i < _dim; i++)
{
_vals[i] = -_vals[i];
}
}
opt::ReturnCode IVectorImpl::eq(const IVector& v, bool& res) const
{
DIM_CHECK(v)
double buff = 0;
opt::ReturnCode err = opt::NO_ERRORS;
for (uint i = 0; i < _dim; i++)
{
err = v.getElement(i, buff);
if(_vals[i] != buff)
{
res = false;
return err;
}
}
res = true;
return err;
}
|
/*
* Copyright (C) 2007-2015 Frank Mertens.
*
* Use of this source is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#include <flux/Singleton>
#include <flux/Process>
#include <flux/User>
#include <flux/IoMonitor>
#include <flux/SignalMaster>
#include "exceptions.h"
#include "ErrorLog.h"
#include "AccessLog.h"
#include "SystemLog.h"
#include "NodeConfig.h"
#include "WorkerPool.h"
#include "ServiceRegistry.h"
#include "DispatchInstance.h"
#include "ConnectionManager.h"
#include "NodeMaster.h"
namespace fluxnode {
NodeMaster* nodeMaster() { return Singleton<NodeMaster>::instance(); }
int NodeMaster::run(int argc, char **argv)
{
SystemLog::open(String(argv[0])->fileName(), 0, LOG_DAEMON);
nodeConfig()->load(argc, argv);
if (nodeConfig()->daemon() && !Process::isDaemonized())
Process::daemonize();
Thread::blockSignals(SignalSet::createFull());
nodeMaster()->signalMaster_->start();
nodeMaster()->start();
nodeMaster()->wait();
return nodeMaster()->exitCode_;
}
NodeMaster::NodeMaster():
signalMaster_(SignalMaster::create()),
exitCode_(0)
{}
void NodeMaster::run()
{
errorLog()->open(nodeConfig()->errorLogConfig());
while (true) {
try {
runNode();
}
catch (Interrupt &ex) {
if (ex.signal() == SIGINT || ex.signal() == SIGTERM || ex.signal() == SIGHUP) break;
exitCode_ = ex.signal() + 128;
}
#ifdef NDEBUG
catch (Exception &ex) {
FLUXNODE_ERROR() << ex.message() << nl;
exitCode_ = 1;
break;
}
#endif
}
}
void NodeMaster::runNode() const
{
FLUXNODE_NOTICE() << "Starting (pid = " << Process::currentId() << ")" << nl;
Ref<DispatchInstance> dispatchInstance;
for (int i = 0; i < nodeConfig()->serviceInstances()->count(); ++i) {
if (nodeConfig()->serviceInstances()->at(i)->serviceName() == "Dispatch") {
dispatchInstance = nodeConfig()->serviceInstances()->at(i);
nodeConfig()->serviceInstances()->pop(i);
--i;
}
}
if (!dispatchInstance) {
ServiceDefinition *dispatchService = serviceRegistry()->serviceByName("Dispatch");
MetaObject *config = dispatchService->configPrototype();
dispatchInstance = dispatchService->createInstance(config);
}
if (nodeConfig()->directoryPath() != "") {
ServiceDefinition *directoryService = serviceRegistry()->serviceByName("Directory");
MetaObject *config = directoryService->configPrototype();
config->establish("host", "*");
config->establish("path", nodeConfig()->directoryPath());
Ref<ServiceInstance> directoryInstance = directoryService->createInstance(config);
nodeConfig()->serviceInstances()->append(directoryInstance);
}
if (nodeConfig()->serviceInstances()->count() == 0)
{
FLUXNODE_WARNING() << "No service configured, falling back to Echo service" << nl;
ServiceDefinition *echoService = serviceRegistry()->serviceByName("Echo");
MetaObject *config = echoService->configPrototype();
config->establish("host", "*");
Ref<ServiceInstance> echoInstance = echoService->createInstance(config);
nodeConfig()->serviceInstances()->append(echoInstance);
}
typedef List< Ref<StreamSocket> > ListeningSockets;
Ref<ListeningSockets> listeningSockets = ListeningSockets::create(nodeConfig()->address()->count());
for (int i = 0; i < nodeConfig()->address()->count(); ++i) {
SocketAddress *address = nodeConfig()->address()->at(i);
FLUXNODE_NOTICE() << "Start listening at " << address << nl;
Ref<StreamSocket> socket = StreamSocket::listen(address);
listeningSockets->at(i) = socket;
}
if (nodeConfig()->user() != "") {
Ref<User> user = User::lookup(nodeConfig()->user());
if (!user->exists()) throw UsageError("No such user: \"" + nodeConfig()->user() + "\"");
FLUXNODE_NOTICE() << "Switching to user " << user->name() << " (uid = " << user->id() << ")" << nl;
Process::setUserId(user->id());
}
Ref<ConnectionManager> connectionManager = ConnectionManager::create(nodeConfig()->serviceWindow());
dispatchInstance->workerPools_ = WorkerPools::create(nodeConfig()->serviceInstances()->count());
for (int i = 0; i < nodeConfig()->serviceInstances()->count(); ++i)
dispatchInstance->workerPools_->at(i) = WorkerPool::create(nodeConfig()->serviceInstances()->at(i), connectionManager->closedConnections());
Ref<WorkerPool> dispatchPool = WorkerPool::create(dispatchInstance, connectionManager->closedConnections());
FLUXNODE_NOTICE() << "Up and running (pid = " << Process::currentId() << ")" << nl;
Ref<IoMonitor> ioMonitor = IoMonitor::create(listeningSockets->count());
for (int i = 0; i < listeningSockets->count(); ++i)
ioMonitor->addEvent(listeningSockets->at(i), IoEvent::ReadyAccept);
FLUXNODE_DEBUG() << "Accepting connections" << nl;
while (true) {
Ref<IoActivity> activity = ioMonitor->wait(1);
if (activity->count() > 0) {
for (int i = 0; i < activity->count(); ++i) {
StreamSocket *socket = cast<StreamSocket>(activity->at(i)->stream());
Ref<StreamSocket> clientSocket = socket->accept();
Ref<SocketAddress> clientAddress = SocketAddress::create();
if (!clientSocket->getPeerAddress(clientAddress)) {
FLUXNODE_DEBUG() << "Failed to get peer address" << nl;
continue;
}
Ref<ClientConnection> client = ClientConnection::create(clientSocket, clientAddress);
connectionManager->prioritize(client);
FLUXNODE_DEBUG() << "Accepted connection from " << client->address() << " with priority " << client->priority() << nl;
dispatchPool->dispatch(client);
}
}
connectionManager->cycle();
if (signalMaster_->receivedSignals()->count() > 0) {
int signal = signalMaster_->receivedSignals()->popFront();
if (signal == SIGWINCH || signal == SIGPIPE) continue;
FLUXNODE_NOTICE() << "Received " << signalName(signal) << ", shutting down" << nl;
dispatchInstance->workerPools_ = 0;
dispatchPool = 0;
FLUXNODE_NOTICE() << "Shutdown complete" << nl;
throw Interrupt(signal);
}
}
}
} // namespace fluxnode
|
/// @file GbmSatEngineBinary.cc
/// @brief GbmSatEngineBinary の実装ファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// Copyright (C) 2013, 2014 Yusuke Matsunaga
/// All rights reserved.
#include "GbmSatEngineBinary.h"
BEGIN_NAMESPACE_YM
//////////////////////////////////////////////////////////////////////
// クラス GbmSatEngineBinary
//////////////////////////////////////////////////////////////////////
// @brief コンストラクタ
// @param[in] solver SATソルバ
GbmSatEngineBinary::GbmSatEngineBinary(SatSolver& solver) :
GbmSatEngine(solver)
{
}
// @brief デストラクタ
GbmSatEngineBinary::~GbmSatEngineBinary()
{
}
// @brief 変数の初期化を行う.
// @param[in] network 対象の LUT ネットワーク
// @param[in] rep 関数の対称変数の代表番号を収める配列
// rep[pos] に pos 番めの入力の代表番号が入る.
void
GbmSatEngineBinary::init_vars(const RcfNetwork& network,
const vector<ymuint>& rep)
{
init_conf_vars(network);
mInputNum = network.input_num();
ymuint m = 0;
for (ymuint t = 1; t < mInputNum; t <<= 1, ++ m) ;
mIorderBitWidth = m;
mIorderVarArray.resize(mInputNum * m);
for (ymuint i = 0; i < mInputNum; ++ i) {
ymuint base = i * mIorderBitWidth;
for (ymuint j = 0; j < mIorderBitWidth; ++ j) {
VarId vid = new_var();
mIorderVarArray[base + j] = vid;
if ( debug() ) {
cout << "Iorder[" << i << "][" << j << "] = " << vid << endl;
}
}
}
for (ymuint i = 0; i < mInputNum; ++ i) {
ymuint base_i = i * mIorderBitWidth;
// 使っていない変数の組み合わせを禁止する.
vector<Literal> tmp_lits2(mIorderBitWidth);
for (ymuint b = mInputNum; b < (1U << mIorderBitWidth); ++ b) {
for (ymuint k = 0; k < mIorderBitWidth; ++ k) {
VarId kvar = mIorderVarArray[base_i + k];
if ( b & (1U << k) ) {
tmp_lits2[k] = Literal(kvar, true);
}
else {
tmp_lits2[k] = Literal(kvar, false);
}
}
add_clause(tmp_lits2);
}
// 異なる LUT 入力におなじ入力が接続してはいけないというルール
for (ymuint j = 0; j < i; ++ j) {
ymuint base_j = j * mIorderBitWidth;
// 0ビット目が異なるときに真となる変数
VarId d0 = new_var();
if ( debug() ) {
cout << "diff[" << i << ", " << j << "][0] = " << d0 << endl;
}
Literal d0_lit(d0, false);
Literal xi0_lit(mIorderVarArray[base_i + 0], false);
Literal xj0_lit(mIorderVarArray[base_j + 0], false);
add_clause(~d0_lit, xi0_lit, xj0_lit);
add_clause(~d0_lit, ~xi0_lit, ~xj0_lit);
add_clause( d0_lit, xi0_lit, ~xj0_lit);
add_clause( d0_lit, ~xi0_lit, xj0_lit);
for (ymuint k = 1; k < mIorderBitWidth; ++ k) {
Literal xik_lit(mIorderVarArray[base_i + k], false);
Literal xjk_lit(mIorderVarArray[base_j + k], false);
if ( k == mIorderBitWidth - 1 ) {
add_clause( d0_lit, xik_lit, xjk_lit);
add_clause( d0_lit, ~xik_lit, ~xjk_lit);
}
else {
VarId dk = new_var();
if ( debug() ) {
cout << "diff[" << i << ", " << j << "][" << k << "] = " << dk << endl;
}
Literal dk_lit(dk, false);
add_clause(~dk_lit, d0_lit, xik_lit, xjk_lit);
add_clause(~dk_lit, d0_lit, ~xik_lit, ~xjk_lit);
add_clause( dk_lit, ~d0_lit, xik_lit, ~xjk_lit);
add_clause( dk_lit, ~d0_lit, ~xik_lit, xjk_lit);
d0_lit = dk_lit;
}
}
}
// LUT ネットワークの対称性を考慮したルール
ymuint pred;
if ( network.get_pred(i, pred) ) {
// 最上位ビットで Vi > Vj となる条件
VarId gm = new_var();
if ( debug() ) {
cout << "gt[" << i << ", " << pred << "][" << (mIorderBitWidth - 1) << "] = " << gm << endl;
}
Literal gm_lit(gm, false);
// 最上位ビットが等しい条件
VarId em = new_var();
if ( debug() ) {
cout << "eq[" << i << ", " << pred << "][" << (mIorderBitWidth - 1) << "] = " << em << endl;
}
ymuint base_j = pred * mIorderBitWidth;
Literal em_lit(em, false);
Literal xm_lit(mIorderVarArray[base_i + mIorderBitWidth - 1], false);
Literal lit(mIorderVarArray[base_j + mIorderBitWidth - 1], false);
add_clause(~gm_lit, xm_lit);
add_clause(~gm_lit, ~lit);
add_clause( gm_lit, ~xm_lit, lit);
add_clause(~em_lit, xm_lit, ~lit);
add_clause(~em_lit, ~xm_lit, lit);
add_clause( em_lit, xm_lit, lit);
add_clause( em_lit, ~xm_lit, ~lit);
for (ymuint k = mIorderBitWidth - 2; ; -- k) {
Literal xk_lit(mIorderVarArray[base_i + k], false);
Literal yk_lit(mIorderVarArray[base_j + k], false);
if ( k == 0 ) {
add_clause( gm_lit, em_lit);
add_clause( gm_lit, xk_lit);
add_clause( gm_lit, ~yk_lit);
break;
}
else {
// k ビット以上で Vi > Vj となる条件
VarId gk = new_var();
if ( debug() ) {
cout << "gt[" << i << ", " << pred << "][" << k << "] = " << gk << endl;
}
Literal gk_lit(gk, false);
// k ビット以上で Vi = Vj となる条件
VarId ek = new_var();
if ( debug() ) {
cout << "eq[" << i << ", " << pred << "][" << k << "] = " << ek << endl;
}
Literal ek_lit(ek, false);
add_clause(~gk_lit, gm_lit, em_lit);
add_clause(~gk_lit, gm_lit, xk_lit);
add_clause(~gk_lit, gm_lit, ~yk_lit);
add_clause( gk_lit, ~gm_lit);
add_clause( gk_lit, ~em_lit, ~xk_lit, yk_lit);
add_clause(~ek_lit, em_lit);
add_clause(~ek_lit, xk_lit, ~yk_lit);
add_clause(~ek_lit, ~xk_lit, yk_lit);
add_clause( ek_lit, ~em_lit, xk_lit, yk_lit);
add_clause( ek_lit, ~em_lit, ~xk_lit, ~yk_lit);
gm_lit = gk_lit;
em_lit = ek_lit;
}
}
}
// 関数の対称性に関するルール
for (ymuint j = 0; j < mInputNum; ++ j) {
ymuint cur_rep = rep[j];
if ( cur_rep == j ) {
continue;
}
// 0 - (i - 1) までの入力で cur_rep が選ばれていなければならない.
// ~X(i,j) + X(0, cur_rep) + X(1, cur_rep) + ...
// だが,X はビットベクタなので積項となり面倒くさい.
vector<Literal> tmp_lits(i + mIorderBitWidth);
vector<ymuint> pos_array(i);
for (ymuint k = 0; k < i; ++ k) {
pos_array[k] = 0;
}
for (ymuint l = 0; l < mIorderBitWidth; ++ l) {
bool inv = (j & (1U << l)) ? false : true;
Literal lit(mIorderVarArray[i * mIorderBitWidth + l], inv);
tmp_lits[i + l] = ~lit;
}
// 全部展開するとオーバーヘッドが大きい様なので mIorderBitWidth 個だけ展開する.
// 完全ではなくても枝刈りには使える.
#if 1
for (ymuint l = 0; l < mIorderBitWidth; ++ l) {
for (ymuint k = 0; k < i; ++ k) {
bool inv = (cur_rep & (1U << l)) ? false : true;
Literal lit(mIorderVarArray[k * mIorderBitWidth + l], inv);
tmp_lits[k] = lit;
}
add_clause(tmp_lits);
}
#else
for ( ; ; ) {
for (ymuint k = 0; k < i; ++ k) {
ymuint pos = pos_array[k];
bool inv = (cur_rep & (1U << pos)) ? false : true;
Literal lit(mIorderVarArray[k * mIorderBitWidth + pos], inv);
tmp_lits[k] = lit;
}
add_clause(tmp_lits);
bool end = true;
for (ymuint k = 0; k < i; ++ k) {
++ pos_array[k];
if ( pos_array[k] < mIorderBitWidth ) {
end = false;
break;
}
pos_array[k] = 0;
}
if ( end ) {
break;
}
}
#endif
}
}
}
// @brief 入力値を割り当てて CNF 式を作る.
// @param[in] network 対象の LUT ネットワーク
// @param[in] bit_pat 外部入力の割り当てを表すビットパタン
// @param[in] oval 出力の値
// @note 結果のCNF式は SAT ソルバに追加される.
bool
GbmSatEngineBinary::make_cnf(const RcfNetwork& network,
ymuint bit_pat,
bool oval)
{
for (ymuint i = 0; i < mInputNum; ++ i) {
const RcfNode* node = network.input_node(i);
ymuint id = node->id();
VarId vid = new_var();
set_node_var(id, GbmLit(vid));
if ( debug() ) {
cout << " lut_input#" << i << ": " << vid << endl;
}
ymuint base_i = i * mIorderBitWidth;
// 入力と外部入力の間の関係式を作る.
vector<Literal> tmp_lits(mIorderBitWidth + 1);
for (ymuint j = 0; j < mInputNum; ++ j) {
for (ymuint k = 0; k < mIorderBitWidth; ++ k) {
VarId kvar = mIorderVarArray[base_i + k];
// こちらは含意の左辺なので否定する.
if ( j & (1U << k) ) {
tmp_lits[k] = Literal(kvar, true);
}
else {
tmp_lits[k] = Literal(kvar, false);
}
}
if ( bit_pat & (1U << j) ) {
tmp_lits[mIorderBitWidth] = Literal(vid, false);
}
else {
tmp_lits[mIorderBitWidth] = Literal(vid, true);
}
add_clause(tmp_lits);
}
}
return make_nodes_cnf(network, oval);
}
// @brief SAT モデルから入力順を取り出す.
// @param[in] model SAT モデル
// @param[out] iorder 入力順
// iorder[pos] に network の pos 番めの入力に対応した
// 関数の入力番号が入る.
void
GbmSatEngineBinary::get_iorder(const vector<Bool3>& model,
vector<ymuint>& iorder) const
{
ymuint ni = iorder.size();
for (ymuint i = 0; i < ni; ++ i) {
ymuint pos = 0;
ymuint base = i * mIorderBitWidth;
for (ymuint j = 0; j < mIorderBitWidth; ++ j) {
VarId vid = mIorderVarArray[base + j];
if ( model[vid.val()] == kB3True ) {
pos += (1U << j);
}
}
iorder[i] = pos;
}
}
END_NAMESPACE_YM
|
/*************************************************************************
> File Name : CertificateRequestError.cpp
> Author : YangShuai
> Created Time: 2016年07月29日 星期五 21时32分23秒
> Description :
************************************************************************/
#include<cstring>
#include"Itsdata.h"
#include"data_handle.h"
int32 CertificateRequestError::_tobe_signeddata(Data& data){
u8* buf = data.getbufptr();
int32 initsize = data.currpos;
int32& size = data.currpos;
if(data.unused() < _tbs_datasize()){
ERROR_PRINT_AND_RETURN("缓存空间不足");
}
if(signer._encode(data) < 0){
ERROR_PRINT_AND_RETURN("SignerInfo编码失败");
}
buf = data.getbufptr();
memcpy(buf, request_hash, 10);
buf += 10;
size += 10;
*buf++ = reason;
size++;
return size - initsize;
}
int32 CertificateRequestError::_encode(Data& data){
int32 initsize = data.currpos;
int32& size = data.currpos;
if(data.unused() < _datasize()){
ERROR_PRINT_AND_RETURN("缓存空间不足");
}
if(_tobe_signeddata(data) < 0){
ERROR_PRINT_AND_RETURN("数据编码失败");
}
if(signature._encode(data) < 0){
ERROR_PRINT_AND_RETURN("Signature编码失败");
}
return size - initsize;
}
int32 CertificateRequestError::_decode(Data& data){
u8* buf = data.getbufptr();
int32 initsize = data.currpos;
int32& size = data.currpos;
if(data.unused() < 14){
ERROR_PRINT_AND_RETURN("填充数据不足");
}
if(signer._decode(data) < 0){
ERROR_PRINT_AND_RETURN("SignerInfo解码失败");
}
buf = data.getbufptr();
memcpy(request_hash, buf, 10);
buf += 10;
size += 10;
reason = (CertificateRequestErrorCode)*buf++;
size++;
if(signature._decode(data) < 0){
ERROR_PRINT_AND_RETURN("Signature解码失败");
}
datasize = size - initsize;
return size - initsize;
}
int32 CertificateRequestError::_datasize(){
if(datasize) goto end;
datasize += signer._datasize();
datasize += 11;
datasize += signature._datasize();
end:
return datasize;
}
int32 CertificateRequestError::_tbs_datasize(){
return signer._datasize() + 11;
}
|
#pragma once
#include <iterator>
#include "CIL/defs.h"
#include "CIL/error.h"
#include "CIL/point.h"
namespace cil {
class CIL_EXPORTS MatConstIterator {
public:
typedef uchar* value_type;
typedef ptrdiff_t difference_type;
typedef const uchar** pointer;
typedef uchar* reference;
typedef std::random_access_iterator_tag iterator_category;
//! default constructor
MatConstIterator();
//! constructor that sets the iterator to the beginning of the matrix
MatConstIterator(const Mat* _m);
//! constructor that sets the iterator to the specified element of the matrix
MatConstIterator(const Mat* _m, int _row, int _col = 0);
//! constructor that sets the iterator to the specified element of the matrix
MatConstIterator(const Mat* _m, Point _pt);
//! constructor that sets the iterator to the specified element of the matrix
MatConstIterator(const Mat* _m, const int* _idx);
//! copy constructor
MatConstIterator(const MatConstIterator& it);
//! copy operator
MatConstIterator& operator=(const MatConstIterator& it);
//! returns the current matrix element
const uchar* operator*() const;
//! returns the i-th matrix element, relative to the current
const uchar* operator[](ptrdiff_t i) const;
//! shifts the iterator forward by the specified number of elements
MatConstIterator& operator+=(ptrdiff_t ofs);
//! shifts the iterator backward by the specified number of elements
MatConstIterator& operator-=(ptrdiff_t ofs);
//! decrements the iterator
MatConstIterator& operator--();
//! decrements the iterator
MatConstIterator operator--(int);
//! increments the iterator
MatConstIterator& operator++();
//! increments the iterator
MatConstIterator operator++(int);
//! returns the current iterator position
Point pos() const;
//! returns the current iterator position
void pos(int* _idx) const;
ptrdiff_t lpos() const;
void seek(ptrdiff_t ofs, bool relative = false);
void seek(const int* _idx, bool relative = false);
const Mat* m;
size_t elemSize;
const uchar* ptr;
const uchar* sliceStart;
const uchar* sliceEnd;
};
template <typename _Tp>
class MatConstIterator_ : public MatConstIterator {
public:
typedef _Tp value_type;
typedef ptrdiff_t difference_type;
typedef const _Tp* pointer;
typedef const _Tp& reference;
typedef std::random_access_iterator_tag iterator_category;
//! default constructor
MatConstIterator_();
//! constructor that sets the iterator to the beginning of the matrix
MatConstIterator_(const Mat_<_Tp>* _m);
//! constructor that sets the iterator to the specified element of the matrix
MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col = 0);
//! constructor that sets the iterator to the specified element of the matrix
MatConstIterator_(const Mat_<_Tp>* _m, Point _pt);
//! constructor that sets the iterator to the specified element of the matrix
MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx);
//! copy constructor
MatConstIterator_(const MatConstIterator_& it);
//! copy operator
MatConstIterator_& operator=(const MatConstIterator_& it);
//! returns the current matrix element
const _Tp& operator*() const;
//! returns the i-th matrix element, relative to the current
const _Tp& operator[](ptrdiff_t i) const;
//! shifts the iterator forward by the specified number of elements
MatConstIterator_& operator+=(ptrdiff_t ofs);
//! shifts the iterator backward by the specified number of elements
MatConstIterator_& operator-=(ptrdiff_t ofs);
//! decrements the iterator
MatConstIterator_& operator--();
//! decrements the iterator
MatConstIterator_ operator--(int);
//! increments the iterator
MatConstIterator_& operator++();
//! increments the iterator
MatConstIterator_ operator++(int);
//! returns the current iterator position
Point pos() const;
};
template <typename _Tp>
class MatIterator_ : public MatConstIterator_<_Tp> {
public:
typedef _Tp* pointer;
typedef _Tp& reference;
typedef std::random_access_iterator_tag iterator_category;
//! the default constructor
MatIterator_();
//! constructor that sets the iterator to the beginning of the matrix
MatIterator_(Mat_<_Tp>* _m);
//! constructor that sets the iterator to the specified element of the matrix
MatIterator_(Mat_<_Tp>* _m, int _row, int _col = 0);
//! constructor that sets the iterator to the specified element of the matrix
MatIterator_(Mat_<_Tp>* _m, Point _pt);
//! constructor that sets the iterator to the specified element of the matrix
MatIterator_(Mat_<_Tp>* _m, const int* _idx);
//! copy constructor
MatIterator_(const MatIterator_& it);
//! copy operator
MatIterator_& operator=(const MatIterator_<_Tp>& it);
//! returns the current matrix element
_Tp& operator*() const;
//! returns the i-th matrix element, relative to the current
_Tp& operator[](ptrdiff_t i) const;
//! shifts the iterator forward by the specified number of elements
MatIterator_& operator+=(ptrdiff_t ofs);
//! shifts the iterator backward by the specified number of elements
MatIterator_& operator-=(ptrdiff_t ofs);
//! decrements the iterator
MatIterator_& operator--();
//! decrements the iterator
MatIterator_ operator--(int);
//! increments the iterator
MatIterator_& operator++();
//! increments the iterator
MatIterator_ operator++(int);
};
class CIL_EXPORTS NAryMatIterator {
public:
//! the default constructor
NAryMatIterator();
//! the full constructor taking arbitrary number of n-dim matrices
NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays = -1);
//! the full constructor taking arbitrary number of n-dim matrices
NAryMatIterator(const Mat** arrays, Mat* planes, int narrays = -1);
//! the separate iterator initialization method
void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays = -1);
//! proceeds to the next plane of every iterated matrix
NAryMatIterator& operator++();
//! proceeds to the next plane of every iterated matrix (postfix increment
//! operator)
NAryMatIterator operator++(int);
//! the iterated arrays
const Mat** arrays;
//! the current planes
Mat* planes;
//! data pointers
uchar** ptrs;
//! the number of arrays
int narrays;
//! the number of hyper-planes that the iterator steps through
size_t nplanes;
//! the size of each segment (in elements)
size_t size;
protected:
int iterdepth;
size_t idx;
};
} // namespace cil
|
#ifndef PIZZAREPOSITORY_H
#define PIZZAREPOSITORY_H
#include "../main.h"
#include "OrderRepository.h"
class PizzaRepository
{
private:
OrderRepository OrderRepo;
int total;
int totalPizza;
int totalDrink;
int totalSides;
string phoneNr;
vector<string> listOfToppings;
vector<string> listOfDrinks;
vector<string> listOfSides;
vector<string> listOfCombo;
vector<string> comboToppings;
vector<int> listOfToppingPrice;
vector<int> listOfDrinkPrice;
vector<int> listOfSidesPrice;
vector<int> listOfComboPrice;
vector<string> OrderList;
char stateOfPizza;
public:
PizzaRepository();
void init();
int numOfItems();
void input_Drinks();
void input_Sides();
void input_Toppings(string str);
string select_Combo(string str);
void orderTotal(int money);
int get_Total();
int getTotalPizza();
int getTotalDrink();
int getTotalSides();
string getPhoneNr();
char getPizzaStatus();
string whatPizzaState(char s);
void clearMem();
void newTotal(int total);
void newTotalPizza(int totalPizza);
void newTotalDrink(int totalDrink);
void newTotalSides(int totalSides);
void newPhoneNr(string phoneNr);
void newPizzaStatus(char pizzaState);
void storePizza(string pizza, int items);
void saveOrder(int file, string phone);
void loadOrder(int file);
void printOrder();
void addVectorString(string str);
void toppingHeader();
void comboHeader();
void drinksHeader();
void sidesHeader();
};
#endif // PIZZAREPOSITORY_H
|
/* traits.h -*- C++ -*-
Rémi Attab (remi.attab@gmail.com), 22 Mar 2015
FreeBSD-style copyright and disclaimer apply
Traits container
*/
#include "reflect.h"
#pragma once
namespace reflect {
/******************************************************************************/
/* TRAITS */
/******************************************************************************/
struct Traits
{
template<typename T>
void addTrait(const std::string& trait, T&& value);
void addTrait(const std::string& trait, Value value = {});
std::vector<std::string> traits() const;
bool is(const std::string& trait) const;
template<typename Ret>
Ret getValue(const std::string& trait) const;
protected:
std::string print() const;
private:
std::unordered_map<std::string, Value> traits_;
};
} // namespace reflect
|
#include "MyForm.h"
System::Void ImageProcessor::MyForm::monochromeTint_Click(System::Object^ sender, System::EventArgs^ e) {
saveCurrentImage();
this->monochromeTint->Hide();
this->customTint->Hide();
this->chooseMonoTintColor->Show();
}
System::Void ImageProcessor::MyForm::chooseMonoTintColor_Click(System::Object^ sender, System::EventArgs^ e) {
System::Windows::Forms::ColorDialog^ tintColors = gcnew ColorDialog();
tintColors->AllowFullOpen = true;
tintColors->ShowHelp = true;
if (tintColors->ShowDialog() == ::System::Windows::Forms::DialogResult::OK) {
tintColorSelect = tintColors->Color;
changes->push(gcnew Bitmap(currentImage->Image));
System::Drawing::Bitmap^ changedBitmap = gcnew Bitmap(currentImage->Image); // new bitmap of current picturebox image
System::Drawing::Rectangle rect = Rectangle(0, 0, changedBitmap->Width, changedBitmap->Height); // new rectangle object w/ same image dimensions
System::Drawing::Imaging::BitmapData^ bitmapData = changedBitmap->LockBits(rect, System::Drawing::Imaging::ImageLockMode::ReadOnly, changedBitmap->PixelFormat); // locks bitmap
IntPtr ptr = bitmapData->Scan0; // idk scans bitmap data
int bytes = Math::Abs(bitmapData->Stride) * changedBitmap->Height; // rgb values converted into byte value
array<Byte>^ rgbValues = gcnew array<Byte>(bytes); // byte array to hold rgb values
System::Runtime::InteropServices::Marshal::Copy(ptr, rgbValues, 0, bytes); // copies values to rgb array
for (int i = 0; i < rgbValues->Length; i += 4) {
Byte r = rgbValues[i]; // value of red / 255
Byte g = rgbValues[i + 1]; // value of green / 255
Byte b = rgbValues[i + 2]; // value of blue / 255
Byte average = (r + g + b) / 3; // average of three rgb values
rgbValues[i] = average + tintColorSelect.B < 255 ? average + tintColorSelect.B : 255;
rgbValues[i + 1] = average + tintColorSelect.G < 255 ? average + tintColorSelect.G : 255;
rgbValues[i + 2] = average + tintColorSelect.R < 255 ? average + tintColorSelect.R : 255;
}
System::Runtime::InteropServices::Marshal::Copy(rgbValues, 0, ptr, bytes); // copies rgb values to bitmap data
changedBitmap->UnlockBits(bitmapData); // transfers bitmap data back to bitmap & unlocks bitmap
currentImage->Image = changedBitmap; // current picturebox image set to bitmap
}
}
System::Void ImageProcessor::MyForm::customTint_Click(System::Object^ sender, System::EventArgs^ e) {
saveCurrentImage();
this->monochromeTint->Hide();
this->customTint->Hide();
this->tintColor->Show();
}
System::Void ImageProcessor::MyForm::tintColor_Click(System::Object^ sender, System::EventArgs^ e) {
System::Windows::Forms::ColorDialog^ tintColors = gcnew ColorDialog();
tintColors->AllowFullOpen = true;
tintColors->ShowHelp = true;
if (tintColors->ShowDialog() == System::Windows::Forms::DialogResult::OK) {
tintColorSelect = tintColors->Color;
this->tintIntensitySlider->Value = 0;
this->tintIntensityValue->Text = "0";
tintIntensityValue->ForeColor = ((tintColorSelect.R + tintColorSelect.G + tintColorSelect.B) / 3 < 127.5) ? Color::White : Color::Black;
this->tintIntensityValue->BackColor = tintColorSelect;
this->tintIntensitySlider->Show();
this->tintIntensityValue->Show();
this->percentLabelTint->Show();
changes->push(gcnew Bitmap(currentImage->Image));
}
}
System::Void ImageProcessor::MyForm::tintIntensitySlider_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
this->tintIntensityTimer->Enabled = true;
}
System::Void ImageProcessor::MyForm::tintIntensitySlider_MouseUp(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
this->tintIntensityTimer->Enabled = false;
this->tintIntensityTimer->Enabled = true;
this->tintIntensityTimer->Enabled = false;
}
System::Void ImageProcessor::MyForm::tintIntensitySlider_ValueChanged(System::Object^ sender, System::EventArgs^ e) {
int percentage = (this->tintIntensitySlider->Value * 100) / 255;
this->tintIntensityValue->Text = System::Convert::ToString(percentage);
}
System::Void ImageProcessor::MyForm::tintIntensityValue_KeyDown(System::Object^ sender, System::Windows::Forms::PreviewKeyDownEventArgs^ e) {
if (e->KeyCode == Keys::Enter) {
int tintIntensityVal;
if (System::Int32::TryParse(this->tintIntensityValue->Text, tintIntensityVal)) {
if (tintIntensityVal > 100) {
this->tintIntensitySlider->Value = 255;
}
else if (tintIntensityVal < 0) {
this->tintIntensitySlider->Value = 0;
}
else {
this->tintIntensitySlider->Value = (tintIntensityVal * 255) / 100;
}
tintIntensitySlider_ValueChange();
}
}
}
System::Void ImageProcessor::MyForm::tintIntensityTimer_Tick(System::Object^ sender, System::EventArgs^ e) {
tintIntensitySlider_ValueChange();
}
System::Void ImageProcessor::MyForm::tintIntensitySlider_ValueChange() {
System::Drawing::Bitmap^ tempBitmap = changes->bitmapPeek();
float intensity = this->tintIntensitySlider->Value / 255.0f;
System::Drawing::Bitmap^ newBitmap = gcnew Bitmap(tempBitmap->Width, tempBitmap->Height);
System::Drawing::Graphics^ newGraphics = System::Drawing::Graphics::FromImage(newBitmap);
System::Drawing::Imaging::ColorMatrix^ colorMatrix = gcnew System::Drawing::Imaging::ColorMatrix();
float r = (tintColorSelect.R / 255.0f) * intensity;
float g = (tintColorSelect.G / 255.0f) * intensity;
float b = (tintColorSelect.B / 255.0f) * intensity;
// [ 1 ] [ 0 ] [ 0 ] [ 0 ] [ 0 ]
colorMatrix->Matrix00 = 1;
colorMatrix->Matrix01 = 0;
colorMatrix->Matrix02 = 0;
colorMatrix->Matrix03 = 0;
colorMatrix->Matrix04 = 0;
// [ 0 ] [ 1 ] [ 0 ] [ 0 ] [ 0 ]
colorMatrix->Matrix10 = 0;
colorMatrix->Matrix11 = 1;
colorMatrix->Matrix12 = 0;
colorMatrix->Matrix13 = 0;
colorMatrix->Matrix14 = 0;
// [ 0 ] [ 0 ] [ 1 ] [ 0 ] [ 0 ]
colorMatrix->Matrix20 = 0;
colorMatrix->Matrix21 = 0;
colorMatrix->Matrix22 = 1;
colorMatrix->Matrix23 = 0;
colorMatrix->Matrix24 = 0;
// [ 0 ] [ 0 ] [ 0 ] [ 1 ] [ 0 ]
colorMatrix->Matrix30 = 0;
colorMatrix->Matrix31 = 0;
colorMatrix->Matrix32 = 0;
colorMatrix->Matrix33 = 1;
colorMatrix->Matrix34 = 0;
// [ r ] [ g ] [ b ] [ 0 ] [ 1 ]
colorMatrix->Matrix40 = r;
colorMatrix->Matrix41 = g;
colorMatrix->Matrix42 = b;
colorMatrix->Matrix43 = 0;
colorMatrix->Matrix44 = 1;
// [ 1 ] [ 0 ] [ 0 ] [ 0 ] [ 0 ]
// [ 0 ] [ 1 ] [ 0 ] [ 0 ] [ 0 ]
// [ 0 ] [ 0 ] [ 1 ] [ 0 ] [ 0 ]
// [ 0 ] [ 0 ] [ 0 ] [ 1 ] [ 0 ]
// [ b ] [ b ] [ b ] [ 0 ] [ 1 ]
// Matrix which will manipulate the tint of the image
System::Drawing::Imaging::ImageAttributes^ attributes = gcnew System::Drawing::Imaging::ImageAttributes();
attributes->SetColorMatrix(colorMatrix);
newGraphics->DrawImage(tempBitmap, Rectangle(0, 0, tempBitmap->Width, tempBitmap->Height), 0, 0, tempBitmap->Width, tempBitmap->Height, GraphicsUnit::Pixel, attributes);
currentImage->Image = newBitmap;
}
|
//
// Created by Valery on 19.01.2019.
//
#ifndef FUNCTION_MYFUNCTION_H
#define FUNCTION_MYFUNCTION_H
#include <iostream>
#include <algorithm>
#include <memory>
const size_t BUFF_SIZE = 16;
const size_t BUFF_ALIGN = 16;
template<typename T>
struct myFunction;
template<typename Ret, typename ... Args>
struct myFunction<Ret(Args ...)> {
private:
struct concept {
concept() = default;
virtual ~concept() = default;
virtual std::unique_ptr<concept> copy() const = 0;
virtual Ret invoke(Args &&... args) = 0;
virtual void placementSmall(void *to) const = 0;
virtual void movePlacementSmall(void *to) = 0;
};
template<typename F>
struct model : concept {
explicit model(F func) : concept(), func(std::move(func)) {}
virtual std::unique_ptr<concept> copy() const {
return std::make_unique<model<F>>(func);
}
virtual Ret invoke(Args &&...args) {
return func(std::forward<Args>(args)...);
}
virtual void placementSmall(void *to) const {
new(to) model<F>(func);
}
virtual void movePlacementSmall(void *to) {
new(to) model<F>(std::move(func));
}
private:
F func;
};
public:
myFunction() noexcept {}
myFunction(std::nullptr_t) noexcept : myFunction() {}
~myFunction() {
if (isSmall) {
reinterpret_cast<concept *>(&st)->~concept();
} else {
ptr.~unique_ptr();
}
}
template<typename F>
myFunction(F f) {
if constexpr (sizeof(model<F>) <= BUFF_SIZE && alignof(F) <= BUFF_ALIGN && std::is_nothrow_move_constructible<F>::value) {
isSmall = true;
new(&st) model<F>(std::move(f));
} else {
isSmall = false;
ptr = std::make_unique<model<F>>(std::move(f));
}
}
myFunction(const myFunction &other) {
if (other.isSmall) {
reinterpret_cast<const concept *>(&other.st)->placementSmall(&st);
} else {
ptr = other.ptr->copy();
}
isSmall = other.isSmall;
}
myFunction(myFunction &&other) noexcept {
isSmall = other.isSmall;
if (other.isSmall) {
reinterpret_cast<concept *>(&other.st)->movePlacementSmall(&st);
reinterpret_cast<concept *>(&other.st)->~concept();
new(&other.ptr) std::unique_ptr<concept>(nullptr);
other.isSmall = false;
} else {
ptr = std::move(other.ptr);
}
}
myFunction &operator=(const myFunction &other) {
myFunction tmp(other);
swap(tmp);
return *this;
}
myFunction &operator=(myFunction &&other) noexcept {
if (isSmall) {
reinterpret_cast<concept *>(&st)->~concept();
} else {
ptr.~unique_ptr();
}
isSmall = other.isSmall;
if (other.isSmall) {
reinterpret_cast<concept *>(&other.st)->movePlacementSmall(&st);
reinterpret_cast<concept *>(&other.st)->~concept();
new(&other.ptr) std::unique_ptr<concept>(nullptr);
other.isSmall = false;
} else {
new(&ptr) std::unique_ptr<concept>(std::move(other.ptr));
}
return *this;
}
Ret operator()(Args &&... args) {
if (isSmall) {
return reinterpret_cast<concept *>(&st)->invoke(std::forward<Args>(args)...);
}
return ptr->invoke(std::forward<Args>(args)...);
}
explicit operator bool() const noexcept {
return isSmall || ptr;
}
void swap(myFunction &other) noexcept {
if (other.isSmall == isSmall) {
if (isSmall) {
std::swap(st, other.st);
} else {
std::swap(ptr, other.ptr);
}
} else if (other.isSmall) {
auto tmp = std::move(ptr);
ptr.~unique_ptr();
reinterpret_cast<concept *>(&other.st)->movePlacementSmall(&st);
reinterpret_cast<concept *>(&other.st)->~concept();
new(&other.ptr) std::unique_ptr<concept>(std::move(tmp));
} else {
auto tmp = std::move(other.ptr);
other.ptr.~unique_ptr();
reinterpret_cast<concept *>(&st)->movePlacementSmall(&other.st);
reinterpret_cast<concept *>(&st)->~concept();
new(&ptr) std::unique_ptr<concept>(std::move(tmp));
}
std::swap(isSmall, other.isSmall);
}
private:
union {
std::unique_ptr<concept> ptr = nullptr;
std::aligned_storage<BUFF_SIZE, BUFF_ALIGN>::type st;
};
bool isSmall = false;
};
#endif //FUNCTION_MYFUNCTION_H
|
#include "Graph.h"
Graph::Graph()
{
}
void Graph::AddNode(GraphNode* a_pNode)
{
m_aNodes.push_back(a_pNode);
}
void Graph::RemoveNode(GraphNode* node)
{
//loop through every node in the vector
for (int i = 0; i < m_aNodes.size(); i++)
{
//looping through every edge in each node
for (int j = 0; j < m_aNodes[i]->m_aEdges.size(); j++)
{
// check if the edge ends with the node we are trying to remove
if (m_aNodes[i]->m_aEdges[j].m_pEnd == node)
{
// erase that edge
m_aNodes[i]->m_aEdges.erase(m_aNodes[i]->m_aEdges.begin()+j);
}
}
}
// loop over each node in the node list
for (int i = 0; i < m_aNodes.size(); ++i)
{
if (node == m_aNodes[i])
{
m_aNodes.erase(m_aNodes.begin()+i);
break;
}
}
// check if we've found the node we're trying to remove
// remove it
}
void Graph::ResetVisited()
{
bool Visited = false;
}
bool Graph::SearchDFS(GraphNode* a_pStart, GraphNode* a_pEnd)//Add to SearchDFS function
{
std::stack<GraphNode*> oNodeStack;
oNodeStack.push(a_pStart);
//add to the SearchDFS function
//keep looping until the stack is empty.
//This will only happen once we've checked every node.
while (!oNodeStack.empty())
{
//the rest of the algorithm goes in here
GraphNode* pCurrent = oNodeStack.top();
oNodeStack.pop();
if (pCurrent->Visited == true)
{
continue;
}
pCurrent->Visited = true;
if (pCurrent == a_pEnd)
{
return true;
}
for (int i = 0; i < pCurrent->m_aEdges.size(); ++i)
{
oNodeStack.push(pCurrent->m_aEdges[i].m_pEnd);
}
}
//return false if we didn't find a_pEnd
return false;
}
bool Graph::SearchBFS(GraphNode* a_pStart, GraphNode* a_pEnd)//Add to SearchDFS function
{
std::queue <GraphNode*> oNodeQueue;
oNodeQueue.push(a_pStart);
//add to the SearchDFS function
//keep looping until the stack is empty.
//This will only happen once we've checked every node.
while (!oNodeQueue.empty())
{
//the rest of the algorithm goes in here
GraphNode* pCurrent = oNodeQueue.front();
oNodeQueue.pop();
if (pCurrent->m_aEdges[0].m_pEnd->Visited == true)
{
continue;
}
pCurrent->Visited = true;
if (pCurrent == a_pEnd)
{
return true;
}
for (int i = 0; i < pCurrent->m_aEdges.size(); ++i)
{
oNodeQueue.push(pCurrent->m_aEdges[i].m_pEnd);
}
}
//return false if we didn't find a_pEnd
return false;
}
Graph Graph::CreateGraph(float xSpace, float ySpace, int xNum, int yNum)
{
Graph tempGraph;
// creating the graph
for (int i = 0, id = 0; i < xNum; i++)
{
for (int j = 0; j < yNum; j++)
{
GraphNode * temp = new GraphNode();
temp->x = i;
temp->y = j;
temp->id = id;
// todo
//temp2->x = i + xSpace;
//temp2->y = j + ySpace;
id++;
tempGraph.AddNode(temp);
//// goes right
//if (yNum*2>id>0 && id != xNum)
//{
// Edge tempEdge1;
// tempEdge1.m_pStart = temp;
// tempEdge1.m_pEnd = temp2;
// tempEdge1.m_fCost = 1;
//
// temp->m_aEdges.push_back(tempEdge1);
//}
//temp->PrintNeighbors();
}
}
// adding neighbors
for (int k = 0, currentID = 0; k < xNum; k++)
{
for (int l = 0; l < yNum; l++)
{
GraphNode * currentNode = tempGraph.m_aNodes[currentID];
std::cout << "Working on: " << currentNode->id << "\n";
// up
if (currentID + yNum < tempGraph.m_aNodes.size())
{
Edge temp(currentNode, tempGraph.m_aNodes[currentID + yNum], 1);
currentNode->m_aEdges.push_back(temp);
tempGraph.m_aNodes[currentID + yNum]->m_aEdges.push_back(temp);
}
// down
if ( currentID - yNum > 0)
{
Edge temp(currentNode, tempGraph.m_aNodes[currentID - yNum], 1);
currentNode->m_aEdges.push_back(temp);
tempGraph.m_aNodes[currentID - yNum]->m_aEdges.push_back(temp);
}
//left
if (currentID - 1 >= 0 && // not below 0
currentID % xNum != 0) // not a multiple of the xNum
{
Edge temp(currentNode, tempGraph.m_aNodes[currentID-1], 1);
currentNode->m_aEdges.push_back(temp);
tempGraph.m_aNodes[currentID-1]->m_aEdges.push_back(temp);
}
//right
if (currentID + 1 < xNum * yNum &&
(currentID + 1) % xNum != 0)
{
Edge temp(currentNode, tempGraph.m_aNodes[currentID+1], 1);
currentNode->m_aEdges.push_back(temp);
tempGraph.m_aNodes[currentID+1]->m_aEdges.push_back(temp);
}
// left
// right
//temp->x = k;
//temp->y = l;
//temp->id = id;
//temp2->x = k + xSpace;
//temp2->y = l + ySpace;
//temp2->id = id + yNum;
//if (yNum*xNum>id>0)
//{
// Edge tempEdge2;
// tempEdge2.m_pStart = temp;
// tempEdge2.m_pEnd = temp2;
// tempEdge2.m_fCost = 1;
// temp->m_aEdges.push_back(tempEdge2);
//}
//currentNode->PrintNeighbors();
//tempGraph.m_aNodes[currentID + yNum]->PrintNeighbors();
currentID++;
}
}
// creating the graph
for (int i = 0, id = 0; i < xNum; i++)
{
for (int j = 0; j < yNum; j++)
{
tempGraph.m_aNodes[id]->PrintNeighbors();
id++;
}
}
return tempGraph;
}
Graph::~Graph()
{
}
|
#pragma once
#include <vector>
#include <string>
namespace vazgen {
class ProtoMessage
{
public:
struct Field
{
std::string m_attribute;
std::string m_type;
std::string m_name;
int m_number = 1;
};
struct Enum
{
std::string m_name;
using Value = std::pair<std::string, int>;
std::vector<Value> m_values;
};
using Fields = std::vector<Field>;
using Enums = std::vector<Enum>;
public:
ProtoMessage() = default;
ProtoMessage(const std::string& name)
: m_name(name)
{
}
ProtoMessage(const ProtoMessage& ) = default;
ProtoMessage(ProtoMessage&& ) = default;
ProtoMessage& operator =(const ProtoMessage& ) = default;
ProtoMessage& operator =(ProtoMessage&& ) = default;
public:
const std::string& getName() const
{
return m_name;
}
const std::string& getAsString() const
{
return m_name;
}
const Fields& getFields() const
{
return m_fields;
}
const Enums& getEnums() const
{
return m_enums;
}
void setName(const std::string& name)
{
m_name = name;
}
void setFields(const Fields& fields)
{
m_fields = fields;
}
void setFields(Fields&& fields)
{
m_fields = std::move(fields);
}
void setEnums(const Enums& enums)
{
m_enums = enums;
}
void setFields(Enums&& enums)
{
m_enums = std::move(enums);
}
void addField(const Field& f)
{
m_fields.push_back(f);
}
void addField(Field&& f)
{
m_fields.push_back(std::move(f));
}
void addEnum(const Enum& e)
{
m_enums.push_back(e);
}
void addEnum(Enum&& e)
{
m_enums.push_back(std::move(e));
}
private:
std::string m_name;
Fields m_fields;
Enums m_enums;
}; // class ProtoMessage
} // namespace vazgen
|
#ifndef ASIO_UDP_SERVER_HPP
#define ASIO_UDP_SERVER_HPP
class udp_connection : public asio_connection
{
public:
udp_connection(boost::asio::io_service & io_service, std::unique_ptr<deviceDescription> description)
: asio_connection(io_service, std::move(description))
{
}
};
class udp_server : public asio_connection
{
public:
udp_server(boost::asio::io_service & io_service, std::unique_ptr<deviceDescription> description)
: asio_connection(io_service, std::move(description))
{
}
};
#endif
|
// Reference - https://www.geeksforgeeks.org/find-whether-path-two-cells-matrix/?ref=rp
#include<bits/stdc++.h>
using namespace std;
class Graph
{
int V ;
list < int > *adj;
public :
Graph( int V )
{
this->V = V ;
adj = new list<int>[V];
}
void addEdge (int s , int d)
{
adj[s].push_back(d);
adj[d].push_back(s);
}
bool BFS (int s ,int d);
};
bool Graph :: BFS(int s, int d)
{
// Base case
if (s == d)
return true;
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
list<int> queue;
visited[s] = true;
queue.push_back(s);
list<int>::iterator i;
while (!queue.empty())
{
s = queue.front();
queue.pop_front();
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{
if (*i == d)
return true;
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
return false;
}
bool isSafe(int i, int j, vector < vector <int> > M, int N)
{
if ((i < 0 || i >= N) || (j < 0 || j >= N ) || M[i][j] == 0)
return false;
return true;
}
bool findPath(vector < vector<int> > M, int N)
{
int s , d ; // source and destination
int V = N*N+2;
Graph g(V);
int k=1;
for (int i =0 ; i < N ; i++)
{
for (int j = 0 ; j < N; j++)
{
if (M[i][j] != 0)
{
if (isSafe( i , j+1 , M, N))
g.addEdge ( k , k+1 );
if (isSafe( i , j-1 , M, N))
g.addEdge ( k , k-1 );
if (j< N-1 && isSafe( i+1 , j , M, N))
g.addEdge ( k , k+N );
if (i > 0 && isSafe( i-1 , j , M, N))
g.addEdge ( k , k-N );
}
// source index
if( M[i][j] == 1 )
s = k ;
// destination index
if (M[i][j] == 2)
d = k;
k++;
}
}
return g.BFS (s, d) ;
}
int main()
{
bool flag=true;
int N;
cin>>N;
vector < vector<int> > M(N, vector <int>(N));
for(int i=0; i<N; i++)
for(int j=0; j<N; j++)
cin>>M[i][j];
flag = findPath(M, N);
if(flag)
cout<<"Yes\n";
else
cout<<"No\n";
return 0;
}
|
#include "MoveModifier.h"
MoveModifier::MoveModifier(void)
{
}
MoveModifier::~MoveModifier(void)
{
}
void MoveModifier::Update(ParticleCollection* c, float delta)
{
for (int i = 0; i < c->Count(); i++)
{
Particle* p = c->Particles[i];
p->Position += p->Velocity * delta;
c->Particles[i] = p;
}
}
|
/*
* Landscape.cpp
*
* Created on: 10 сент. 2017 г.
* Author: Соня
*/
#include "Landscape.h"
Landscape::Landscape(const String &filename) {
//Msg::Error(L"%s", filename.c_str());
mesh.LoadFromFile(filename);
}
Landscape::~Landscape() {
// TODO Auto-generated destructor stub
}
|
//
// StickerControlView.h
// iPet
//
// Created by KimSteve on 2017. 5. 19..
// Copyright © 2017년 KimSteve. All rights reserved.
//
#ifndef StickerControlView_h
#define StickerControlView_h
#include "../Base/SMView.h"
#include "../Base/SMButton.h"
class DashedRoundRect;
class StickerControlListener {
public:
virtual void onStickerMenuClick(cocos2d::Node* sticker, int menuId) {}
};
class StickerControlView : public SMView, public OnTouchListener, public OnClickListener
{
public:
static StickerControlView * create();
void linkStickerNode(cocos2d::Node* node);
void startGeineRemove(cocos2d::Node * node);
bool canSwipe(const cocos2d::Vec2& worldPoint) const;
void setStickerListener(StickerControlListener* l);
void highlightSizeButton() {};
protected:
StickerControlView();
virtual ~StickerControlView();
virtual void onClick(SMView* view) override;
virtual int onTouch(SMView* view, const int action, const cocos2d::Touch* touch, const cocos2d::Vec2* point, MotionEvent* event) override;
virtual bool init() override;
virtual void onUpdateOnVisit() override;
virtual int dispatchTouchEvent(MotionEvent* event, SMView * view, bool checkBounds) override;
private:
SMView * _uiView;
DashedRoundRect * _borderSprite;
SMButton * _sizeButton;
SMButton * _utilButton; // for Trash
cocos2d::Node * _targetNode;
cocos2d::Size _targetSize;
cocos2d::Vec2 _grabPt;
cocos2d::Vec2 _deltaPt;
bool _reset;
StickerControlListener* _listener;
int _utilButtonMode;
cocos2d::Node * _sizeButtonIndicator;
bool _highlightSizeButton;
};
#endif /* StickerControlView_h */
|
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
#include <cassert>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
#include <ctime>
#include <algorithm>
using namespace std;
// is sushkov using his mac or not?
const int MAC = 0;
// 123: 98291669
// 123_86%of4: 99473899
// 2: 1965045
const int NUM_POINTS = 98291669;
// Filenames
const char dataFilePath[] = "/home/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/data/mu/data123.txt";
const char dataFilePathUM[] = "/home/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/data/um/data123.txt";
const char outOfSampleFile[] = "/home/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/data/mu/data_4.txt";
const char qualFilePath[] = "/home/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/data/mu/qual.dta";
const char aggrFilePath[] = "/home/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/data/mu/data_7%of4(aggr).dta";
const char aggrOutFilePath[] = "/home/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/submissions/aggregation/svd++/SVD++_80f_aggr";
const char outputFilePath[] = "/home/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/submissions/SVD++/SVD++_80f_123_86%of4.txt";
const char outputUserFeatureFile[] = "/home/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/data/feature_matrices/userFeatures_SVD++_40f_version1.txt";
const char outputMovieFeatureFile[] = "/home/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/data/feature_matrices/movieFeatures_SVD++_40f_version1.txt";
const char dataFilePathMAC[] = "/Users/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/data/mu/data123.txt";
const char dataFilePathUMMAC[] = "/Users/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/data/um/data123.txt";
const char outOfSampleFileMAC[] = "/Users/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/data/mu/data4.txt";
const char qualFilePathMAC[] = "/Users/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/data/mu/qual.dta";
const char outputFilePathMAC[] = "/Users/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/submissions/SVD/SVDreg_40f_min150e_K=0.02.txt";
const char outputUserFeatureFileMAC[] = "/Users/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/data/feature_matrices/user/userFeatures_SVD++_50f_K=0.02_min150e.txt";
const char outputMovieFeatureFileMAC[] = "/Users/msushkov/Dropbox/Caltech/Caltech Classes/CS/CS 156b/data/feature_matrices/movie/movieFeatures_SVD++_50f_K=0.02_min150e.txt";
// constants
const float GLOBAL_AVG_MOVIE_RATING = 3.60951619727;
const int NUM_USERS = 458293;
const int NUM_MOVIES = 17770;
const int NUM_FEATURES = 80;
const int NUM_EPOCHS = 30;
float LEARNING_RATE_Y = 0.001;
float LEARNING_RATE_USER = 0.006;
float LEARNING_RATE_MOVIE = 0.011;
float LRATE_ub = 0.012;
float LRATE_mb = 0.003;
float K_user = 0.08;
float K_movie = 0.006;
float LAMBDA_Y = 0.03;
float LAMBDA_ub = 0.03;
float LAMBDA_mb = 0.001;
const float LEARNING_RATE_DECREASE_RATE = 0.9;
const float EPSILON = 0.0001;
const float VARIANCE_RATIO = 25;
// defines a single training data point
class DataPoint {
public:
int user;
int movie;
float rating;
DataPoint() {
this->user = 0;
this->movie = 0;
this->rating = 0;
}
DataPoint(int user, int movie, float rating) {
this->user = user;
this->movie = movie;
this->rating = rating;
}
};
// a vector of datapoints to hold data
//vector<DataPoint*> *trainingData = new vector<DataPoint*>;
//vector<DataPoint> **trainingData = new vector<DataPoint>*[NUM_USERS]; // an array of vector pointers to DataPoint pointers
int *movies = new int[NUM_POINTS];
int *users = new int[NUM_POINTS];
int *ratings = new int[NUM_POINTS];
int *times = new int[NUM_POINTS];
// feature matrices (2D arrays); feature k for user u is userFeatures[u][k]
float **userFeatures = new float*[NUM_USERS];
float **movieFeatures = new float*[NUM_MOVIES];
float **userFeaturesA = new float*[NUM_USERS];
float **userFeaturesB = new float*[NUM_USERS];
float **userFeaturesC = new float*[NUM_USERS];
float **userFeaturesD = new float*[NUM_USERS];
float **movieFeaturesA = new float*[NUM_MOVIES];
float **movieFeaturesB = new float*[NUM_MOVIES];
float **movieFeaturesC = new float*[NUM_MOVIES];
float **movieFeaturesD = new float*[NUM_MOVIES];
// arrays to hold the average ratings for each movie and for each user
float *avgUserRatings = new float[NUM_USERS];
float *avgMovieRatings = new float[NUM_MOVIES];
// the average offset for a given user
float *avgUserOffset = new float[NUM_USERS];
float *avgMovieOffset = new float[NUM_MOVIES];
// b_u and b_i
float *userBias = new float[NUM_USERS];
float *movieBias = new float[NUM_MOVIES];
float *userBiasA = new float[NUM_USERS];
float *userBiasB = new float[NUM_USERS];
float *userBiasC = new float[NUM_USERS];
float *userBiasD = new float[NUM_USERS];
float *movieBiasA = new float[NUM_MOVIES];
float *movieBiasB = new float[NUM_MOVIES];
float *movieBiasC = new float[NUM_MOVIES];
float *movieBiasD = new float[NUM_MOVIES];
// For each user, the number of movies they rated
int *movieRatingsByUser = new int[NUM_USERS];
// the inverse square root of the number of movie ratings
float *norm = new float[NUM_USERS];
// stores the y-values of each y[movie][feature]
float **y = new float*[NUM_MOVIES]; // less than 5 movies
//float **y = new float*[NUM_FEATURES];
float **yA = new float*[NUM_MOVIES]; // between 5 and 20 movies
float **yB = new float*[NUM_MOVIES]; // between 20 and 60 movies
float **yC = new float*[NUM_MOVIES]; // between 60 and 100 movies
float **yD = new float*[NUM_MOVIES]; // over 100 movies
// stores the sum of the y's: sumY[user][feature]
float **sumY = new float*[NUM_USERS];
float **sumYA = new float*[NUM_USERS];
float **sumYB = new float*[NUM_USERS];
float **sumYC = new float*[NUM_USERS];
float **sumYD = new float*[NUM_USERS];
void computeNorms() {
for (int i = 0; i < NUM_USERS; i++) {
int numMovies = movieRatingsByUser[i];
//int numMovies = trainingData[i]->size();
numMovies++;
if (numMovies > 1)
norm[i] = pow(numMovies, -0.5);
else
norm[i] = 1;
}
}
// returns a random value between -0.01 and 0.01
float getRandom() {
//return 10.0 / 10.0 * ((float) rand() / ((float) RAND_MAX)) - 0.0;
int num = ((int) rand()) % 100;
return 2.0 * num / 10000.0 - 0.01;
}
// initialize each element of the feature matrices
void initialize() {
for (int i = 0; i < NUM_POINTS; i++) {
movies[i] = 0;
users[i] = 0;
ratings[i] = 0;
times[i] = 0;
}
for (int i = 0; i < NUM_USERS; i++) {
userFeatures[i] = new float[NUM_FEATURES];
userFeaturesA[i] = new float[NUM_FEATURES];
userFeaturesB[i] = new float[NUM_FEATURES];
userFeaturesC[i] = new float[NUM_FEATURES];
userFeaturesD[i] = new float[NUM_FEATURES];
for (int j = 0; j < NUM_FEATURES; j++) {
//float rand = sqrt(GLOBAL_AVG_MOVIE_RATING / (float) NUM_FEATURES[0]) + getRandom();
userFeatures[i][j] = getRandom();
//userFeatures[i][j] = sqrt(GLOBAL_AVG_MOVIE_RATING / (float) NUM_FEATURES) + getRandom();
userFeaturesA[i][j] = getRandom();
userFeaturesB[i][j] = getRandom();
userFeaturesC[i][j] = getRandom();
userFeaturesD[i][j] = getRandom();
}
}
// initialize the movie feature matrix
for (int i = 0; i < NUM_MOVIES; i++) {
movieFeatures[i] = new float[NUM_FEATURES];
movieFeaturesA[i] = new float[NUM_FEATURES];
movieFeaturesB[i] = new float[NUM_FEATURES];
movieFeaturesC[i] = new float[NUM_FEATURES];
movieFeaturesD[i] = new float[NUM_FEATURES];
for (int j = 0; j < NUM_FEATURES; j++) {
//float rand = sqrt(GLOBAL_AVG_MOVIE_RATING / (float) NUM_FEATURES[0]) + getRandom();
movieFeatures[i][j] = getRandom();
//movieFeatures[i][j] = sqrt(GLOBAL_AVG_MOVIE_RATING / (float) NUM_FEATURES) + getRandom();
movieFeaturesA[i][j] = getRandom();
movieFeaturesB[i][j] = getRandom();
movieFeaturesC[i][j] = getRandom();
movieFeaturesD[i][j] = getRandom();
}
}
for (int i = 0; i < NUM_USERS; i++) {
userBias[i] = 0.0;
movieRatingsByUser[i] = 0;
norm[i] = 0.0;
userBiasA[i] = 0.0;
userBiasB[i] = 0.0;
userBiasC[i] = 0.0;
userBiasD[i] = 0.0;
}
for (int i = 0; i < NUM_MOVIES; i++) {
movieBias[i] = 0.0;
movieBiasA[i] = 0.0;
movieBiasB[i] = 0.0;
movieBiasC[i] = 0.0;
movieBiasD[i] = 0.0;
}
for (int i = 0; i < NUM_MOVIES; i++) {
y[i] = new float[NUM_FEATURES];
yA[i] = new float[NUM_FEATURES];
yB[i] = new float[NUM_FEATURES];
yC[i] = new float[NUM_FEATURES];
yD[i] = new float[NUM_FEATURES];
for (int j = 0; j < NUM_FEATURES; j++) {
y[i][j] = getRandom();
//y[i][j] = 0;
yA[i][j] = getRandom();
yB[i][j] = getRandom();
yC[i][j] = getRandom();
yD[i][j] = getRandom();
}
}
for (int i = 0; i < NUM_USERS; i++) {
sumY[i] = new float[NUM_FEATURES];
sumYA[i] = new float[NUM_FEATURES];
sumYB[i] = new float[NUM_FEATURES];
sumYC[i] = new float[NUM_FEATURES];
sumYD[i] = new float[NUM_FEATURES];
for (int j = 0; j < NUM_FEATURES; j++) {
sumY[i][j] = 0.0;
sumYA[i][j] = 0.0;
sumYB[i][j] = 0.0;
sumYC[i][j] = 0.0;
sumYD[i][j] = 0.0;
}
}
//for (int i = 0; i < NUM_USERS; i++)
//trainingData[i] = new vector<DataPoint>;
}
// helper function that splits a string
vector<string> &split(const string &s, char delim, vector<string> &elems) {
stringstream ss(s);
string item;
while(getline(ss, item, delim))
elems.push_back(item);
return elems;
}
// helper function to split a string
vector<string> split(const string &s, char delim) {
vector<string> elems;
return split(s, delim, elems);
}
float predictRating(int movie, int user) {
/*float result = GLOBAL_AVG_MOVIE_RATING + userBias[user] + movieBias[movie];
// find the dot product
for (int f = 0; f < NUM_FEATURES; f++)
result += movieFeatures[movie][f] * (userFeatures[user][f] + norm[user] * sumY[user][f]);
return result;*/
return GLOBAL_AVG_MOVIE_RATING + avgUserOffset[user] + avgMovieOffset[movie];
}
float predictRating1(int movie, int user) {
float result = GLOBAL_AVG_MOVIE_RATING + userBiasA[user] + movieBiasA[movie];
// find the dot product
for (int f = 0; f < NUM_FEATURES; f++)
result += movieFeaturesA[movie][f] * (userFeaturesA[user][f] + norm[user] * sumYA[user][f]);
return result;
}
float predictRating2(int movie, int user) {
float result = GLOBAL_AVG_MOVIE_RATING + userBiasB[user] + movieBiasB[movie];
// find the dot product
for (int f = 0; f < NUM_FEATURES; f++)
result += movieFeaturesB[movie][f] * (userFeaturesB[user][f] + norm[user] * sumYB[user][f]);
return result;
}
float predictRating3(int movie, int user) {
float result = GLOBAL_AVG_MOVIE_RATING + userBiasC[user] + movieBiasC[movie];
// find the dot product
for (int f = 0; f < NUM_FEATURES; f++)
result += movieFeaturesC[movie][f] * (userFeaturesC[user][f] + norm[user] * sumYC[user][f]);
return result;
}
float predictRating4(int movie, int user) {
float result = GLOBAL_AVG_MOVIE_RATING + userBiasD[user] + movieBiasD[movie];
// find the dot product
for (int f = 0; f < NUM_FEATURES; f++)
result += movieFeaturesD[movie][f] * (userFeaturesD[user][f] + norm[user] * sumYD[user][f]);
return result;
}
float predictRating_training(int movie, float userBiasArg, float movieBiasArg, float *sumYArray, float normArg, float *userFeatureVec, float *movieFeatureVec) {
float result = GLOBAL_AVG_MOVIE_RATING + userBiasArg + movieBiasArg;
// find the dot product
for (int f = 0; f < NUM_FEATURES; f++)
result += movieFeatureVec[f] * (userFeatureVec[f] + normArg * sumYArray[f]);
return result;
}
// compute the in-sample error
float computeInSample(int numFeatures) {
float error = 0;
int size = 0;
// go through each training point and calculate the error for it
/*for (int i = 0; i < NUM_USERS; i++) {
for (int j = 0; j < trainingData[i]->size(); j++) {
DataPoint currData = trainingData[i]->at(j);
size++;
int currUser = currData.user;
int currMovie = currData.movie;
float actualRating = currData.rating;
float predicted = predictRating(currMovie - 1, currUser - 1);
// make sure the rating is between 1 and 5
if (predicted > 5)
predicted = 5;
else if (predicted < 1)
predicted = 1;
error += (predicted - actualRating) * (predicted - actualRating);
}
}*/
for (int i = 0; i < NUM_POINTS; i++) {
int currUser = users[i];
int currMovie = movies[i];
float actualRating = ratings[i];
float predicted = predictRating(currMovie - 1, currUser - 1);
// make sure the rating is between 1 and 5
if (predicted > 5)
predicted = 5;
else if (predicted < 1)
predicted = 1;
error += (predicted - actualRating) * (predicted - actualRating);
}
return sqrt(error / NUM_POINTS);
}
// compute the out of sample error
float computeOutOfSample(int numFeatures) {
float error = 0;
int numPoints = 0;
string line;
ifstream outOfSample;
if (MAC == 0)
outOfSample.open(outOfSampleFile, ios::in);
else
outOfSample.open(outOfSampleFileMAC, ios::in);
// go through the input data line by line
while (getline(outOfSample, line)) {
// where are we in the current line?
int count = 0;
int user = -1;
int movie = -1;
int actualRating = -1;
int actualTime = -1;
istringstream lineIn(line);
while (lineIn) {
int val = 0;
if (lineIn >> val) {
if (count == 0)
user = val;
else if (count == 1)
movie = val;
else if (count == 3)
actualRating = val;
else if (count == 4)
actualTime = val;
count++;
}
}
int numRatings = movieRatingsByUser[user - 1];
float predictedRating;
if (numRatings < 5)
predictedRating = predictRating(movie - 1, user - 1);
else if (numRatings >= 5 && numRatings < 20)
predictedRating = predictRating1(movie - 1, user - 1);
else if (numRatings >= 20 && numRatings < 60)
predictedRating = predictRating2(movie - 1, user - 1);
else if (numRatings >= 60 && numRatings < 100)
predictedRating = predictRating3(movie - 1, user - 1);
else
predictedRating = predictRating4(movie - 1, user - 1);
// make sure the rating is between 1 and 5
if (predictedRating > 5)
predictedRating = 5;
else if (predictedRating < 1)
predictedRating = 1;
assert(actualRating != -1);
// get the squared error for this point
error += (predictedRating - actualRating) * (predictedRating - actualRating);
numPoints++;
}
outOfSample.close();
return sqrt(error / numPoints);
}
// iterate through the epochs and all the data points for each epoch
/*void learn() {
float Eout = 10000;
float prevEout = 1000000;
int i = 0;
// go N times through the data
//for (int i = 0; i < NUM_EPOCHS; i++) {
while (i < NUM_EPOCHS || (prevEout - Eout) > EPSILON) {
const clock_t begin_time = clock();
for (int p = 0; p < NUM_USERS; p++) {
float tempSumY[NUM_FEATURES];
vector<DataPoint> *currUserVector = trainingData[p];
int size = currUserVector->size();
float *currSumY = sumY[p];
// for each movie the user rated
for (int j = 0; j < size; j++) {
DataPoint currData = currUserVector->at(j);
int user = currData.user;
int movie = currData.movie;
int rating = currData.rating;
// train the SVD on each point (will go through all features)
float *userFeature = userFeatures[user - 1];
float *movieFeature = movieFeatures[movie - 1];
float userBiasVal = userBias[user - 1];
float movieBiasVal = movieBias[movie - 1];
//float error = rating - predictRating(movie - 1, user - 1);
float error = rating - predictRating_training(movie - 1, userBiasVal, movieBiasVal, currSumY, norm[user - 1], userFeature, movieFeature);
//predictRating_training(int movie, float userBiasArg, float *sumYArray, float normArg, float *userFeatureVec)
userBias[user - 1] += (LRATE_ub * (error - LAMBDA_ub * userBiasVal));
movieBias[movie - 1] += (LRATE_mb * (error - LAMBDA_mb * movieBiasVal));
// iterate over features 0 through N - 1
for (int k = 0; k < NUM_FEATURES; k++) {
float oldUserFeature = userFeature[k];
float oldMovieFeature = movieFeature[k];
userFeature[k] += (LEARNING_RATE_USER * (error * oldMovieFeature - K * oldUserFeature));
movieFeature[k] += (LEARNING_RATE_MOVIE * (error * (oldUserFeature + norm[user - 1] * currSumY[k]) - K * oldMovieFeature));
tempSumY[k] += (error * norm[user - 1] * oldMovieFeature);
} // end for loop over features
} // end movie loop
// for each movie the user rated
for (int j = 0; j < size; j++) {
int movie = currUserVector->at(j).movie;
float *currY = y[movie - 1];
for (int k = 0; k < NUM_FEATURES; k++) {
float update = LEARNING_RATE_Y * (tempSumY[k] - LAMBDA_Y * currY[k]);
currY[k] += update;
currSumY[k] += update;
}
} // end movie loop
} // end user loop
// decrease the learning rates
LEARNING_RATE_Y *= LEARNING_RATE_DECREASE_RATE;
LEARNING_RATE_USER *= LEARNING_RATE_DECREASE_RATE;
LEARNING_RATE_MOVIE *= LEARNING_RATE_DECREASE_RATE;
LRATE_ub *= LEARNING_RATE_DECREASE_RATE;
LRATE_mb *= LEARNING_RATE_DECREASE_RATE;
// only check Eout every 5 iterations
if (i % 3 == 0) {
prevEout = Eout;
Eout = computeOutOfSample(NUM_FEATURES);
cout << " Eout = " << Eout << endl;
}
cout << "Finished epoch: " << i + 1 << " out of " << NUM_EPOCHS << endl;
cout << " --> " << float(clock() - begin_time) / CLOCKS_PER_SEC << " seconds" << endl;
i++;
} // end epoch loop
// print out the results
cout << endl << "RESULTS: (K, # of features, Ein, Eout)" << endl;
cout << K << ", " << NUM_FEATURES << ", " << computeInSample(NUM_FEATURES) << ", " << computeOutOfSample(NUM_FEATURES) << endl;
}*/
void learn() {
computeNorms();
float Eout = 10000;
float prevEout = 1000000;
int iterations = 0;
int prevUser = 1;
// go N times through the data
while (iterations < NUM_EPOCHS || (prevEout - Eout) > EPSILON) {
const clock_t begin_time = clock();
int countForCurrUser = 0;
vector<int> moviesRatedByCurrUser;
float tempSumY[NUM_FEATURES];
for (int i = 0; i < NUM_FEATURES; i++) {
tempSumY[i] = 0.0;
}
// go through each point
for (int p = 0; p < NUM_POINTS; p++) {
int user = users[p];
int movie = movies[p];
int rating = ratings[p];
int numMovies = movieRatingsByUser[user - 1];
float *userFeature;
float *movieFeature;
float userBiasVal;
float movieBiasVal;
float *currSumY;
float error;
if (numMovies <= 5) {
userFeature = userFeatures[user - 1];
movieFeature = movieFeatures[movie - 1];
userBiasVal = userBias[user - 1];
movieBiasVal = movieBias[movie - 1];
currSumY = sumY[user - 1];
error = rating - predictRating(movie - 1, user - 1);
} else if (numMovies > 5 && numMovies <= 20) {
userFeature = userFeaturesA[user - 1];
movieFeature = movieFeaturesA[movie - 1];
userBiasVal = userBiasA[user - 1];
movieBiasVal = movieBiasA[movie - 1];
currSumY = sumYA[user - 1];
error = rating - predictRating1(movie - 1, user - 1);
} else if (numMovies > 20 && numMovies <= 60) {
userFeature = userFeaturesB
[user - 1];
movieFeature = movieFeaturesB[movie - 1];
userBiasVal = userBiasB[user - 1];
movieBiasVal = movieBiasB[movie - 1];
currSumY = sumYB[user - 1];
error = rating - predictRating2(movie - 1, user - 1);
} else if (numMovies > 60 && numMovies <= 100) {
userFeature = userFeaturesC[user - 1];
movieFeature = movieFeaturesC[movie - 1];
userBiasVal = userBiasC[user - 1];
movieBiasVal = movieBiasC[movie - 1];
currSumY = sumYC[user - 1];
error = rating - predictRating3(movie - 1, user - 1);
} else {
userFeature = userFeaturesD[user - 1];
movieFeature = movieFeaturesD[movie - 1];
userBiasVal = userBiasD[user - 1];
movieBiasVal = movieBiasD[movie - 1];
currSumY = sumYD[user - 1];
error = rating - predictRating4(movie - 1, user - 1);
}
userBias[user - 1] += (LRATE_ub * (error - LAMBDA_ub * userBiasVal));
movieBias[movie - 1] += (LRATE_mb * (error - LAMBDA_mb * movieBiasVal));
// the user changed
if (user != prevUser) {
countForCurrUser = 1;
moviesRatedByCurrUser.clear();
} else {
countForCurrUser++;
}
moviesRatedByCurrUser.push_back(movie);
// iterate over features 0 through N - 1
for (int k = 0; k < NUM_FEATURES; k++) {
float oldUserFeature = userFeature[k];
float oldMovieFeature = movieFeature[k];
userFeature[k] += (LEARNING_RATE_USER * (error * oldMovieFeature - K_user * oldUserFeature));
movieFeature[k] += (LEARNING_RATE_MOVIE * (error * (oldUserFeature + norm[user - 1] * currSumY[k]) - K_movie * oldMovieFeature));
tempSumY[k] += (error * norm[user - 1] * oldMovieFeature);
// if we had just finished going through all the movies this user has seen
if (countForCurrUser == numMovies) { // user is going to change on the next data point
float totalUpdate = 0;
// for each movie the user rated
for (int j = 0; j < numMovies; j++) {
float *currY;
if (numMovies <= 5)
currY = y[moviesRatedByCurrUser.at(j) - 1];
else if (numMovies > 5 && numMovies <= 20)
currY = yA[moviesRatedByCurrUser.at(j) - 1];
else if (numMovies > 20 && numMovies <= 60)
currY = yB[moviesRatedByCurrUser.at(j) - 1];
else if (numMovies > 60 && numMovies <= 100)
currY = yC[moviesRatedByCurrUser.at(j) - 1];
else
currY = yD[moviesRatedByCurrUser.at(j) - 1];
float update = LEARNING_RATE_Y * (tempSumY[k] - LAMBDA_Y * currY[k]);
currY[k] += update;
totalUpdate += update;
} // end movie loop
currSumY[k] += totalUpdate;
} // end if
} // end for loop over features
// reset the temp sum array before the next user
if (countForCurrUser == numMovies) {
for (int i = 0; i < NUM_FEATURES; i++) {
tempSumY[i] = 0.0;
}
}
prevUser = user;
//if (p % 10000000 == 0)
//cout << p / 1000000 << " million" << endl;
} // end points loop
// decrease the learning rates
LEARNING_RATE_Y *= LEARNING_RATE_DECREASE_RATE;
LEARNING_RATE_USER *= LEARNING_RATE_DECREASE_RATE;
LEARNING_RATE_MOVIE *= LEARNING_RATE_DECREASE_RATE;
LRATE_ub *= LEARNING_RATE_DECREASE_RATE;
LRATE_mb *= LEARNING_RATE_DECREASE_RATE;
// only check Eout every few iterations
if (iterations % 3 == 0) {
prevEout = Eout;
Eout = computeOutOfSample(NUM_FEATURES);
cout << " Eout = " << Eout << endl;
}
cout << "Finished epoch: " << iterations + 1 << " out of " << NUM_EPOCHS << endl;
cout << " --> " << float(clock() - begin_time) / CLOCKS_PER_SEC << " seconds" << endl;
iterations++;
} // end epoch loop
// print out the results
cout << endl << "RESULTS: (# of features, Ein, Eout)" << endl;
cout << NUM_FEATURES << ", " << computeInSample(NUM_FEATURES) << ", " << computeOutOfSample(NUM_FEATURES) << endl;
}
// computes the average ratings for each user (uses UM data set)
// also computes the user offset
void getAvgUserRatings() {
string line;
// get the UM data file
ifstream dataFile;
if (MAC == 0)
dataFile.open(dataFilePathUM, ios::in);
else
dataFile.open(dataFilePathUMMAC, ios::in);
int numLinesSoFar = 0;
int prevUser = 1;
float totalRating = 0;
int index = 0; // counts the # of movies each user rated
float currTotalUserOffset = 0;
// go through the input data line by line
while (getline(dataFile, line)) {
// where are we in the current line?
int count = 0;
int currUser = -1;
int currMovie = -1;
int currRating = -1;
int currTime = -1;
istringstream lineIn(line);
while (lineIn) {
int val = 0;
if (lineIn >> val) {
if (count == 0)
currUser = val;
else if (count == 1)
currMovie = val;
else if (count == 3)
currRating = val;
//else if (count == 4)
//currTime = val;
count++;
}
}
//DataPoint *currPoint = new DataPoint(currUser, currMovie, currRating);
//DataPoint currPoint(currUser, currMovie, currRating);
movies[numLinesSoFar] = currMovie;
users[numLinesSoFar] = currUser;
ratings[numLinesSoFar] = currRating;
times[numLinesSoFar] = currTime;
// if the user changes
if (prevUser != currUser) {
//avgUserRatings[prevUser - 1] = totalRating / index;
avgUserRatings[prevUser - 1] = (GLOBAL_AVG_MOVIE_RATING * VARIANCE_RATIO + totalRating) / (VARIANCE_RATIO + index);
totalRating = currRating;
avgUserOffset[prevUser - 1] = currTotalUserOffset / index;
currTotalUserOffset = currRating - avgMovieRatings[currMovie - 1];
//currTotalUserOffset = currRating - GLOBAL_AVG_MOVIE_RATING;
movieRatingsByUser[prevUser - 1] = index;
// we see a new user, so he starts off with the only rating we have seen for him
//moviesByUser[currUser - 1]->push_back(currMovie);
//trainingData[currUser - 1]->push_back(currPoint);
index = 1;
} else { // if we keep seeing data for the same user
index++;
totalRating += currRating;
currTotalUserOffset += (currRating - avgMovieRatings[currMovie - 1]);
//currTotalUserOffset += (currRating - GLOBAL_AVG_MOVIE_RATING);
//moviesByUser[currUser - 1]->push_back(currMovie);
//trainingData[currUser - 1]->push_back(currPoint);
}
prevUser = currUser;
numLinesSoFar++;
if (numLinesSoFar % 1000000 == 0)
cout << "Computing avg user ratings: " << numLinesSoFar / 1000000 << " million" << endl;
}
// deals with end of file
avgUserRatings[prevUser - 1] = totalRating / index;
avgUserOffset[prevUser - 1] = currTotalUserOffset / index;
movieRatingsByUser[prevUser - 1] = index;
dataFile.close();
}
// reads data in (MU) and also computes avg ratings for each movie
// also computes the movie offset
void getData() {
string line;
ifstream dataFile;
if (MAC)
dataFile.open(dataFilePathMAC, ios::in);
else
dataFile.open(dataFilePath, ios::in);
int numLinesSoFar = 0;
int prevMovie = 1;
float totalRating = 0;
int index = 0; // counts the # of users that watched each movie
float currTotalMovieOffset = 0;
// go through the input data line by line
while (getline(dataFile, line)) {
// where are we in the current line?
int count = 0;
int currUser = -1;
int currMovie = -1;
float currRating = -1;
istringstream lineIn(line);
while (lineIn) {
int val = 0;
if (lineIn >> val) {
if (count == 0)
currUser = val;
else if (count == 1)
currMovie = val;
else if (count == 3)
currRating = val;
count++;
}
}
// add the point to our data vector
//trainingData->push_back(currPoint);
// to calculate the average ratings for the movies
if (prevMovie != currMovie) {
//avgMovieRatings[prevMovie - 1] = totalRating / index;
avgMovieRatings[prevMovie - 1] = (VARIANCE_RATIO * GLOBAL_AVG_MOVIE_RATING + totalRating) / (VARIANCE_RATIO + index);
totalRating = currRating;
avgMovieOffset[prevMovie - 1] = currTotalMovieOffset / index;
//currTotalMovieOffset = currPoint->rating - avgUserRatings[currPoint->user - 1];
currTotalMovieOffset = currRating - GLOBAL_AVG_MOVIE_RATING;
index = 1;
} else {
if (currRating != 0) {
index++;
totalRating += currRating;
//currTotalMovieOffset += (currPoint->rating - avgUserRatings[currPoint->user - 1]);
currTotalMovieOffset += (currRating - GLOBAL_AVG_MOVIE_RATING);
}
}
prevMovie = currMovie;
numLinesSoFar++;
if (numLinesSoFar % 1000000 == 0)
cout << numLinesSoFar / 1000000 << " million" << endl;
}
// deals with last line with respect to calculating the average movie rating
//avgMovieRatings[prevMovie - 1] = totalRating / index;
avgMovieRatings[prevMovie - 1] = (VARIANCE_RATIO * GLOBAL_AVG_MOVIE_RATING + totalRating) / (VARIANCE_RATIO + index);
avgMovieOffset[prevMovie - 1] = currTotalMovieOffset / index;
dataFile.close();
// at this point we have the avg movie ratings filled out
// now calculate the avg user ratings
getAvgUserRatings();
}
void outputVectors() {
cout << "Output vectors" << endl;
// output files
ofstream outputFileUser;
if (MAC == 0)
outputFileUser.open(outputUserFeatureFile, ios::out);
else
outputFileUser.open(outputUserFeatureFileMAC, ios::out);
ofstream outputFileMovie;
if (MAC == 0)
outputFileMovie.open(outputMovieFeatureFile, ios::out);
else
outputFileMovie.open(outputMovieFeatureFileMAC, ios::out);
// output the user features
for (int i = 0; i < NUM_USERS; i++) {
for (int k = 0; k < NUM_FEATURES; k++) {
outputFileUser << userFeatures[i][k] << " ";
}
outputFileUser << endl;
}
// output the movie features
for (int i = 0; i < NUM_MOVIES; i++) {
for (int k = 0; k < NUM_FEATURES; k++) {
outputFileMovie << movieFeatures[i][k] << " ";
}
outputFileMovie << endl;
}
outputFileMovie.close();
outputFileUser.close();
}
void outputAggr() {
// output file
ofstream outputFile;
outputFile.open(aggrOutFilePath, ios::out);
// aggregation file
string line;
ifstream aggrFile;
aggrFile.open(aggrFilePath, ios::in);
// go through each line of the qual file
while (getline(aggrFile, line)) {
// where are we in the current line?
int count = 0;
int user = -1;
int movie = -1;
// read the values on the current line one by one
istringstream lineIn(line);
while (lineIn) {
int val = 0;
if (lineIn >> val) {
if (count == 0)
user = val;
else if (count == 1)
movie = val;
count++;
}
}
// calculate the rating for user, movie
float predictedScore = predictRating(movie - 1, user - 1);
// make sure the rating is between 1 and 5
if (predictedScore > 5)
predictedScore = 5;
else if (predictedScore < 1)
predictedScore = 1;
// write to file
outputFile << predictedScore << endl;
}
aggrFile.close();
outputFile.close();
}
// writes data out
void outputResults() {
// output file
ofstream outputFile;
if (MAC)
outputFile.open(outputFilePathMAC, ios::out);
else
outputFile.open(outputFilePath, ios::out);
// qual file
string line;
ifstream qualFile;
if (MAC)
qualFile.open(qualFilePathMAC, ios::in);
else
qualFile.open(qualFilePath, ios::in);
// go through each line of the qual file
while (getline(qualFile, line)) {
// where are we in the current line?
int count = 0;
int user = -1;
int movie = -1;
// read the values on the current line one by one
istringstream lineIn(line);
while (lineIn) {
int val = 0;
if (lineIn >> val) {
if (count == 0)
user = val;
else if (count == 1)
movie = val;
count++;
}
}
int numRatings = movieRatingsByUser[user - 1];
float predictedRating;
if (numRatings < 5)
predictedRating = predictRating(movie - 1, user - 1);
else if (numRatings >= 5 && numRatings < 20)
predictedRating = predictRating1(movie - 1, user - 1);
else if (numRatings >= 20 && numRatings < 60)
predictedRating = predictRating2(movie - 1, user - 1);
else if (numRatings >= 60 && numRatings < 100)
predictedRating = predictRating3(movie - 1, user - 1);
else
predictedRating = predictRating4(movie - 1, user - 1);
// make sure the rating is between 1 and 5
if (predictedRating > 5)
predictedRating = 5;
else if (predictedRating < 1)
predictedRating = 1;
// write to file
outputFile << predictedRating << endl;
}
qualFile.close();
outputFile.close();
outputAggr();
//outputVectors();
}
void cleanup() {
for (int i = 0; i < NUM_USERS; i++)
delete[] userFeatures[i];
for (int i = 0; i < NUM_MOVIES; i++)
delete[] movieFeatures[i];
delete[] userFeatures;
delete[] movieFeatures;
/*delete[] avgMovieRatings;
delete[] avgUserRatings;
delete[] avgUserOffset;
delete[] avgMovieOffset;*/
//delete[] userBias;
//delete[] movieBias;
//delete[] movieRatingsByUser;
//delete[] norm;
}
// K-value, # features, # epochs
int main(int argc, char *argv[]) {
srand((unsigned) time(0));
initialize();
if (argc != 11) {
cout << "Usage: ./SVD++ [LEARNING_RATE_Y] [LEARNING_RATE_USER] [LEARNING_RATE_MOVIE] [LRATE_ub] [LRATE_mb] [K_user] [K_movie] [LAMBDA_Y] [LAMBDA_ub] [LAMBDA_mb]" << endl;
return 1;
} else {
LEARNING_RATE_Y = atof(argv[1]);
LEARNING_RATE_USER = atof(argv[2]);
LEARNING_RATE_MOVIE = atof(argv[3]);
LRATE_ub = atof(argv[4]);
LRATE_mb = atof(argv[5]);
K_user = atof(argv[6]);
K_movie = atof(argv[7]);
LAMBDA_Y = atof(argv[8]);
LAMBDA_ub = atof(argv[9]);
LAMBDA_mb = atof(argv[10]);
}
getData();
cout << "Done with getData()" << endl;
// run the SVD algorithm
learn();
cout << "Done learning" << endl;
//outputResults();
cout << "Done with outputResults()" << endl;
//cleanup();
cout << "DONE!" << endl;
return 0;
}
|
/*
* Copyright (c) 2013 William Linna <william.linna@kapsi.fi>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
#ifndef BALLS_H
#define BALLS_H
extern const double SCREEN_WIDTH;
extern const double SCREEN_HEIGHT;
#include <vector>
#include "vector2.hpp"
struct SDL_Surface;
class Circles
{
public:
Circles();
int getCount() const;
bool addCircle(double x, double y, double radius, double vx, double vy, long double mass);
void update();
void draw(SDL_Surface *screen);
private:
void updatePositions();
void updateVelocities();
void updateCollisions();
int count_;
std::vector<Vector2> positions_;
std::vector<Vector2> velocities_;
std::vector<double> radiuses_;
std::vector<long double> masses_;
Circles(const Circles& other);
Circles& operator=(const Circles& other);
};
#endif // BALLS_H
|
#include "../Include/Application.h"
#include "../Include/World.h"
#include "../Include/Window.h"
#include<iostream>
Window* window;
World* world;
int curPosX, curPosY;
int motionPosX, motionPosY;
int mShapeStatus;
int mLineWidthStatus;
int mColorStatus;
Application::Application()
: isPreviewing(false)
{
world = new World;
window = new Window(1280, 720, "test");
mWorld = world;
mWindow = window;
}
void Application::init() {
glClearColor(1, 1, 1, 0);
}
void mouseButton(int button, int state, int x, int y)
{
switch (button) {
case GLUT_LEFT_BUTTON:
switch (state) {
case GLUT_DOWN:
curPosX = x + 50;
curPosY = 770 - y;
window->update(curPosX, curPosY);
motionPosX = curPosX;
motionPosY = curPosY;
printf("is in paper %d \n", window->isInPaper());
if (window->isInPaper()) {
world->previewGraph(window->getActiveTool(), window->getActiveColor(), window->getActiveLineWidth(),
curPosX, curPosY, motionPosX, motionPosY);
}
break;
case GLUT_UP:
if (window->isInPaper()) {
world->saveGraph();
}
break;
}
break;
case GLUT_MIDDLE_BUTTON:
break;
}
display();
printf("Curpos X %d Y %d\n", curPosX, curPosY);
}
void mouseMotion(int x, int y)
{
motionPosX = x + 50;
motionPosY = 770 - y;
// window->update(curPosX, curPosY);
if (window->isInPaper())
world->previewGraph(window->getActiveTool(), window->getActiveColor(), window->getActiveLineWidth(),
curPosX, curPosY, motionPosX, motionPosY);
printf("motion X %d Y %d\n", motionPosX, motionPosY);
display();
}
void Application::run() {
clock_t start, finish;
float deltaTime = 0.0;
processUserInput();
mWindow->update(curPosX, curPosY);
getFeedback();
this->render();
glutMainLoop();
}
void Application::update() {
}
void displayMenu() {
window->draw();
}
void display() {
//Çå¿Õ»²¼
glColor3f(1, 1, 1);
glBegin(GL_QUADS);
glVertex3f(0, 0, -10);
glVertex3f(1129, 0, -10);
glVertex3f(1129, 650, -10);
glVertex3f(0, 650, -10);
glEnd();
world->show();
window->draw();
glFlush();
}
void Application::render()
{
mLineWidthStatus = mWindow->getActiveLineWidth();
glutDisplayFunc(display);
}
inline void Application::processUserInput()
{
glutMouseFunc(mouseButton);
glutMotionFunc(mouseMotion);
}
inline void Application::getFeedback()
{
mShapeStatus = mWindow->getActiveTool();
mColorStatus = mWindow->getActiveColor();
}
|
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
vector<long long int>sagar;
void ck()
{
sagar.push_back(2);
sagar.push_back(3);
sagar.push_back(5);
sagar.push_back(7);
sagar.push_back(11);
sagar.push_back(13);
sagar.push_back(17);
sagar.push_back(31);
sagar.push_back(37);
sagar.push_back(71);
sagar.push_back(73);
sagar.push_back(79);
sagar.push_back(97);
sagar.push_back(113);
sagar.push_back(131);
sagar.push_back(199);
sagar.push_back(311);
sagar.push_back(337);
sagar.push_back(373);
sagar.push_back(733);
sagar.push_back(919);
sagar.push_back(991);
}
int main()
{
long long int n,res,m,i,take;
ck();
while(1)
{
cin>>n;
take=n;
res=0;
if(n==0)
break;
if(n>991)
cout<<0<<endl;
else
{
while(1)
{
m=n%10;
res=res+1;
n=n/10;
if(n==0)
{
res=pow(10,res);
break;
}
}
for(i=0; i<sagar.size(); i++)
{
if(sagar[i]>take)
{
if(sagar[i]<res)
cout<<sagar[i]<<endl;
else
cout<<0<<endl;
break;
}
}
}
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.